Truly independent web browser
LibTextCodec: Use one decoder for every encoding
Shannon Booth6e777ad0b0bd
diff --git a/Libraries/LibJS/SourceCode.cpp b/Libraries/LibJS/SourceCode.cppindex 78dcdbdc4b8..533e2077d19 100644--- a/Libraries/LibJS/SourceCode.cpp+++ b/Libraries/LibJS/SourceCode.cpp@@ -32,7 +32,7 @@ static Utf16String decode_source_bytes(ReadonlyBytes source_bytes, StringView soauto decoder = TextCodec::decoder_for(source_encoding);VERIFY(decoder.has_value());- auto code = MUST(TextCodec::decode_to_utf16(StringView { source_bytes }, *decoder));+ auto code = MUST(TextCodec::decode_to_utf16(source_bytes, *decoder));if (code.length_in_code_units() > length_in_code_units)return Utf16String::from_utf16(code.utf16_view().substring_view(0, length_in_code_units));return code;diff --git a/Libraries/LibJS/SyntaxHighlighter.cpp b/Libraries/LibJS/SyntaxHighlighter.cppindex bb0301d8947..821f7489ec3 100644--- a/Libraries/LibJS/SyntaxHighlighter.cpp+++ b/Libraries/LibJS/SyntaxHighlighter.cpp@@ -101,7 +101,7 @@ void SyntaxHighlighter::rehighlight(Palette const& palette)auto text = m_client->get_text();auto decoder = TextCodec::decoder_for("UTF-8"sv);VERIFY(decoder.has_value());- auto source = TextCodec::decode_to_utf16(text, *decoder)+ auto source = TextCodec::decode_to_utf16(text.bytes(), *decoder).release_value_but_fixme_should_propagate_errors();Vector<Syntax::TextDocumentSpan> spans;diff --git a/Libraries/LibTextCodec/Decoder.cpp b/Libraries/LibTextCodec/Decoder.cppindex 620e82f70b2..cfd7a109ca3 100644--- a/Libraries/LibTextCodec/Decoder.cpp+++ b/Libraries/LibTextCodec/Decoder.cpp@@ -17,95 +17,6 @@ namespace TextCodec {namespace {-class RustDecoder final : public Decoder {-public:- explicit RustDecoder(StringView encoding)- : m_encoding(encoding)- {- }-- virtual ErrorOr<String> to_utf8(StringView input, ErrorMode) override;- virtual ErrorOr<size_t> length_in_utf16_code_units(StringView input) override;--private:- virtual ErrorOr<void> process(StringView input, Function<ErrorOr<void>(u32)> on_code_point) override;-- StringView m_encoding;-};--class UTF8Decoder final : public Decoder {-public:- virtual ErrorOr<void> process(StringView, Function<ErrorOr<void>(u32)> on_code_point) override;- virtual ErrorOr<String> to_utf8(StringView, ErrorMode) override;- virtual ErrorOr<Utf16String> to_utf16(StringView) override;- virtual ErrorOr<size_t> length_in_utf16_code_units(StringView) override;-};--class UTF16BEDecoder final : public Decoder {-public:- virtual ErrorOr<String> to_utf8(StringView, ErrorMode) override;- virtual ErrorOr<size_t> length_in_utf16_code_units(StringView) override;--private:- virtual ErrorOr<void> process(StringView, Function<ErrorOr<void>(u32)>) override;-};--class UTF16LEDecoder final : public Decoder {-public:- virtual ErrorOr<String> to_utf8(StringView, ErrorMode) override;- virtual ErrorOr<size_t> length_in_utf16_code_units(StringView) override;--private:- virtual ErrorOr<void> process(StringView, Function<ErrorOr<void>(u32)>) override;-};--class Latin1Decoder final : public Decoder {-public:- virtual ErrorOr<void> process(StringView, Function<ErrorOr<void>(u32)> on_code_point) override;- virtual ErrorOr<size_t> length_in_utf16_code_units(StringView) override;-};--UTF8Decoder s_utf8_decoder;-UTF16BEDecoder s_utf16be_decoder;-UTF16LEDecoder s_utf16le_decoder;-Latin1Decoder s_latin1_decoder;--RustDecoder s_gb18030_decoder { "gb18030"sv };-RustDecoder s_big5_decoder { "Big5"sv };-RustDecoder s_euc_jp_decoder { "EUC-JP"sv };-RustDecoder s_iso_2022_jp_decoder { "ISO-2022-JP"sv };-RustDecoder s_shift_jis_decoder { "Shift_JIS"sv };-RustDecoder s_euc_kr_decoder { "EUC-KR"sv };-RustDecoder s_ibm866_decoder { "IBM866"sv };-RustDecoder s_latin2_decoder { "ISO-8859-2"sv };-RustDecoder s_latin3_decoder { "ISO-8859-3"sv };-RustDecoder s_latin4_decoder { "ISO-8859-4"sv };-RustDecoder s_latin_cyrillic_decoder { "ISO-8859-5"sv };-RustDecoder s_latin_arabic_decoder { "ISO-8859-6"sv };-RustDecoder s_latin_greek_decoder { "ISO-8859-7"sv };-RustDecoder s_latin_hebrew_decoder { "ISO-8859-8"sv };-RustDecoder s_latin6_decoder { "ISO-8859-10"sv };-RustDecoder s_latin7_decoder { "ISO-8859-13"sv };-RustDecoder s_latin8_decoder { "ISO-8859-14"sv };-RustDecoder s_latin9_decoder { "ISO-8859-15"sv };-RustDecoder s_latin10_decoder { "ISO-8859-16"sv };-RustDecoder s_centraleurope_decoder { "windows-1250"sv };-RustDecoder s_cyrillic_decoder { "windows-1251"sv };-RustDecoder s_hebrew_decoder { "windows-1255"sv };-RustDecoder s_koi8r_decoder { "KOI8-R"sv };-RustDecoder s_koi8u_decoder { "KOI8-U"sv };-RustDecoder s_mac_roman_decoder { "macintosh"sv };-RustDecoder s_windows874_decoder { "windows-874"sv };-RustDecoder s_windows1252_decoder { "windows-1252"sv };-RustDecoder s_windows1253_decoder { "windows-1253"sv };-RustDecoder s_turkish_decoder { "windows-1254"sv };-RustDecoder s_windows1256_decoder { "windows-1256"sv };-RustDecoder s_windows1257_decoder { "windows-1257"sv };-RustDecoder s_windows1258_decoder { "windows-1258"sv };-RustDecoder s_mac_cyrillic_decoder { "x-mac-cyrillic"sv };-RustDecoder s_x_user_defined_decoder { "x-user-defined"sv };-RustDecoder s_replacement_decoder { "replacement"sv };-struct DecodeContext {StringBuilder builder;ErrorOr<void> result {};@@ -115,7 +26,7 @@ struct Utf16DecodeContext {Utf16StringBuilder builder;};-static void append_decoded_bytes(void* context, u8 const* data, size_t length)+void append_decoded_bytes(void* context, u8 const* data, size_t length){auto& decode_context = *static_cast<DecodeContext*>(context);if (decode_context.result.is_error())@@ -123,29 +34,12 @@ static void append_decoded_bytes(void* context, u8 const* data, size_t length)decode_context.result = decode_context.builder.try_append(StringView { data, length });}-static void append_decoded_utf16(void* context, u16 const* data, size_t length)+void append_decoded_utf16(void* context, u16 const* data, size_t length){auto& decode_context = *static_cast<Utf16DecodeContext*>(context);decode_context.builder.append(Utf16View { reinterpret_cast<char16_t const*>(data), length });}-ErrorOr<String> rust_decode_to_utf8(StringView encoding, StringView input, ErrorMode error_mode)-{- DecodeContext context { .builder = StringBuilder(input.length()) };- auto succeeded = FFI::textcodec_rust_decode_to_utf8(- reinterpret_cast<u8 const*>(encoding.characters_without_null_termination()),- encoding.length(),- reinterpret_cast<u8 const*>(input.characters_without_null_termination()),- input.length(),- error_mode == ErrorMode::Fatal,- &context,- append_decoded_bytes);- if (!succeeded)- return Error::from_string_literal("Failed to decode input");- TRY(context.result);- return context.builder.to_string_without_validation();-}-ErrorOr<Utf16String> rust_streaming_decode_to_utf16(FFI::TextCodecRustStreamingDecoder* decoder, ReadonlyBytes input, bool last){Utf16DecodeContext context { .builder = Utf16StringBuilder(input.size()) };@@ -161,37 +55,6 @@ ErrorOr<Utf16String> rust_streaming_decode_to_utf16(FFI::TextCodecRustStreamingDreturn context.builder.to_string();}-ErrorOr<void> rust_process(StringView encoding, StringView input, Function<ErrorOr<void>(u32)> on_code_point)-{- auto utf8 = TRY(rust_decode_to_utf8(encoding, input, ErrorMode::Replacement));- for (auto code_point : Utf8View { utf8 })- TRY(on_code_point(code_point));- return {};-}--ErrorOr<size_t> rust_length_in_utf16_code_units(StringView encoding, StringView input)-{- auto utf8 = TRY(rust_decode_to_utf8(encoding, input, ErrorMode::Replacement));- size_t length = 0;- for (auto code_point : Utf8View { utf8 })- length += code_point <= 0xffff ? 1 : 2;- return length;-}--Optional<StringView> get_static_encoding_name_from_rust(StringView label)-{- u8 const* encoding_name = nullptr;- size_t encoding_name_length = 0;- auto succeeded = FFI::textcodec_rust_get_standardized_encoding(- reinterpret_cast<u8 const*>(label.characters_without_null_termination()),- label.length(),- &encoding_name,- &encoding_name_length);- if (!succeeded)- return {};- return StringView { encoding_name, encoding_name_length };-}-ErrorOr<String> rust_streaming_decode_to_utf8(FFI::TextCodecRustStreamingDecoder* decoder, ReadonlyBytes input, bool last){DecodeContext context { .builder = StringBuilder(input.size()) };@@ -210,112 +73,34 @@ ErrorOr<String> rust_streaming_decode_to_utf8(FFI::TextCodecRustStreamingDecoder}-Optional<Decoder&> decoder_for(StringView label)+Optional<Decoder> decoder_for(StringView label){auto encoding = get_standardized_encoding(label);- return encoding.has_value() ? decoder_for_exact_name(encoding.value()) : Optional<Decoder&> {};+ return encoding.has_value() ? Decoder { *encoding } : Optional<Decoder> {};}-Optional<Decoder&> decoder_for(Utf16View label)+Optional<Decoder> decoder_for(Utf16View label){auto encoding = get_standardized_encoding(label);- return encoding.has_value() ? decoder_for_exact_name(encoding.value()) : Optional<Decoder&> {};-}--Optional<Decoder&> decoder_for_exact_name(StringView encoding)-{- if (encoding.equals_ignoring_ascii_case("iso-8859-1"sv))- return s_latin1_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1252"sv))- return s_windows1252_decoder;- if (encoding.equals_ignoring_ascii_case("utf-8"sv))- return s_utf8_decoder;- if (encoding.equals_ignoring_ascii_case("utf-16be"sv))- return s_utf16be_decoder;- if (encoding.equals_ignoring_ascii_case("utf-16le"sv))- return s_utf16le_decoder;- if (encoding.equals_ignoring_ascii_case("big5"sv))- return s_big5_decoder;- if (encoding.equals_ignoring_ascii_case("euc-jp"sv))- return s_euc_jp_decoder;- if (encoding.equals_ignoring_ascii_case("euc-kr"sv))- return s_euc_kr_decoder;- if (encoding.equals_ignoring_ascii_case("gbk"sv))- return s_gb18030_decoder;- if (encoding.equals_ignoring_ascii_case("gb18030"sv))- return s_gb18030_decoder;- if (encoding.equals_ignoring_ascii_case("ibm866"sv))- return s_ibm866_decoder;- if (encoding.equals_ignoring_ascii_case("iso-2022-jp"sv))- return s_iso_2022_jp_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-2"sv))- return s_latin2_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-3"sv))- return s_latin3_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-4"sv))- return s_latin4_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-5"sv))- return s_latin_cyrillic_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-6"sv))- return s_latin_arabic_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-7"sv))- return s_latin_greek_decoder;- if (encoding.is_one_of_ignoring_ascii_case("iso-8859-8"sv, "iso-8859-8-i"sv))- return s_latin_hebrew_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-10"sv))- return s_latin6_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-13"sv))- return s_latin7_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-14"sv))- return s_latin8_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-15"sv))- return s_latin9_decoder;- if (encoding.equals_ignoring_ascii_case("iso-8859-16"sv))- return s_latin10_decoder;- if (encoding.equals_ignoring_ascii_case("koi8-r"sv))- return s_koi8r_decoder;- if (encoding.equals_ignoring_ascii_case("koi8-u"sv))- return s_koi8u_decoder;- if (encoding.equals_ignoring_ascii_case("macintosh"sv))- return s_mac_roman_decoder;- if (encoding.equals_ignoring_ascii_case("replacement"sv))- return s_replacement_decoder;- if (encoding.equals_ignoring_ascii_case("shift_jis"sv))- return s_shift_jis_decoder;- if (encoding.equals_ignoring_ascii_case("windows-874"sv))- return s_windows874_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1250"sv))- return s_centraleurope_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1251"sv))- return s_cyrillic_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1253"sv))- return s_windows1253_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1254"sv))- return s_turkish_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1255"sv))- return s_hebrew_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1256"sv))- return s_windows1256_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1257"sv))- return s_windows1257_decoder;- if (encoding.equals_ignoring_ascii_case("windows-1258"sv))- return s_windows1258_decoder;- if (encoding.equals_ignoring_ascii_case("x-mac-cyrillic"sv))- return s_mac_cyrillic_decoder;- if (encoding.equals_ignoring_ascii_case("x-user-defined"sv))- return s_x_user_defined_decoder;-- dbgln("TextCodec: No decoder implemented for encoding '{}'", encoding);- return {};+ return encoding.has_value() ? Decoder { *encoding } : Optional<Decoder> {};}Optional<StringView> get_standardized_encoding(StringView encoding){- auto standardized_encoding = get_static_encoding_name_from_rust(encoding);- // NB: Pages often give an empty label, such as <script charset="">. That is not worth logging.- if (!standardized_encoding.has_value() && !encoding.trim_whitespace().is_empty())- dbgln("TextCodec: Unrecognized encoding: {}", encoding);- return standardized_encoding;+ u8 const* encoding_name = nullptr;+ size_t encoding_name_length = 0;+ auto succeeded = FFI::textcodec_rust_get_standardized_encoding(+ reinterpret_cast<u8 const*>(encoding.characters_without_null_termination()),+ encoding.length(),+ &encoding_name,+ &encoding_name_length);+ if (!succeeded) {+ // NB: Pages often give an empty label, such as <script charset="">. That is not worth logging.+ if (!encoding.trim_whitespace().is_empty())+ dbgln("TextCodec: Unrecognized encoding: {}", encoding);+ return {};+ }+ return StringView { encoding_name, encoding_name_length };}Optional<StringView> get_standardized_encoding(Utf16View encoding)@@ -337,8 +122,57 @@ Optional<StringView> get_standardized_encoding(Utf16View encoding)return get_standardized_encoding(ascii_string.bytes_as_string_view());}+ErrorOr<String> Decoder::to_utf8(ReadonlyBytes input, ErrorMode error_mode) const+{+ DecodeContext context { .builder = StringBuilder(input.size()) };+ auto succeeded = FFI::textcodec_rust_decode_to_utf8(+ reinterpret_cast<u8 const*>(m_encoding.characters_without_null_termination()),+ m_encoding.length(),+ input.data(),+ input.size(),+ error_mode == ErrorMode::Fatal,+ &context,+ append_decoded_bytes);+ if (!succeeded)+ return Error::from_string_literal("Failed to decode input");+ TRY(context.result);+ return context.builder.to_string_without_validation();+}++ErrorOr<Utf16String> Decoder::to_utf16(ReadonlyBytes input) const+{+ if (m_encoding == "UTF-8"sv && Utf8View { StringView { input } }.validate(AllowLonelySurrogates::No))+ return Utf16String::from_utf8_without_validation(StringView { input });++ Utf16DecodeContext context { .builder = Utf16StringBuilder(input.size()) };+ auto succeeded = FFI::textcodec_rust_decode_to_utf16(+ reinterpret_cast<u8 const*>(m_encoding.characters_without_null_termination()),+ m_encoding.length(),+ input.data(),+ input.size(),+ &context,+ append_decoded_utf16);+ if (!succeeded)+ return Error::from_string_literal("Failed to decode input");+ return context.builder.to_string();+}++ErrorOr<size_t> Decoder::length_in_utf16_code_units(ReadonlyBytes input) const+{+ size_t length = 0;+ auto succeeded = FFI::textcodec_rust_decoded_length_in_utf16_code_units(+ reinterpret_cast<u8 const*>(m_encoding.characters_without_null_termination()),+ m_encoding.length(),+ input.data(),+ input.size(),+ &length);+ if (!succeeded)+ return Error::from_string_literal("Failed to decode input");+ return length;+}+// https://encoding.spec.whatwg.org/#bom-sniff-static Optional<Decoder&> bom_sniff_to_decoder(StringView input)+static Optional<StringView> bom_sniff(ReadonlyBytes input){// 1. Let BOM be the result of peeking 3 bytes from ioQueue, converted to a byte sequence.// 2. For each of the rows in the table below, starting with the first one and going down,@@ -350,51 +184,34 @@ static Optional<Decoder&> bom_sniff_to_decoder(StringView input)// 0xEF 0xBB 0xBF | UTF-8// 0xFE 0xFF | UTF-16BE// 0xFF 0xFE | UTF-16LE-- auto bytes = input.bytes();- if (bytes.size() < 2)- return {};-- auto first_byte = bytes[0];-- switch (first_byte) {- case 0xEF: // UTF-8- if (bytes.size() < 3)- return {};- if (bytes[1] == 0xBB && bytes[2] == 0xBF)- return s_utf8_decoder;- return {};- case 0xFE: // UTF-16BE- if (bytes[1] == 0xFF)- return s_utf16be_decoder;- return {};- case 0xFF: // UTF-16LE- if (bytes[1] == 0xFE)- return s_utf16le_decoder;- return {};- }-+ auto bom = StringView { input };+ if (bom.starts_with("\xEF\xBB\xBF"sv))+ return "UTF-8"sv;+ if (bom.starts_with("\xFE\xFF"sv))+ return "UTF-16BE"sv;+ if (bom.starts_with("\xFF\xFE"sv))+ return "UTF-16LE"sv;return {};}// https://encoding.spec.whatwg.org/#decode-static Decoder& decoder_for_decode(Decoder& fallback_decoder, StringView& input)+static Decoder decoder_for_decode(Decoder fallback_decoder, ReadonlyBytes& input){// 1. Let BOMEncoding be the result of BOM sniffing ioQueue.// 2. If BOMEncoding is non-null:- if (auto bom_decoder = bom_sniff_to_decoder(input); bom_decoder.has_value()) {+ if (auto bom_encoding = bom_sniff(input); bom_encoding.has_value()) {// 1. Set encoding to BOMEncoding.// 2. Read three bytes from ioQueue, if BOMEncoding is UTF-8; otherwise read two bytes. (Do nothing with those bytes.)- input = input.substring_view(&bom_decoder.value() == &s_utf8_decoder ? 3 : 2);- return bom_decoder.value();+ input = input.slice(*bom_encoding == "UTF-8"sv ? 3 : 2);+ return *decoder_for(*bom_encoding);}return fallback_decoder;}// https://encoding.spec.whatwg.org/#decode-ErrorOr<String> decode_to_utf8(StringView input, Decoder& fallback_decoder, ErrorMode error_mode)+ErrorOr<String> decode_to_utf8(ReadonlyBytes input, Decoder fallback_decoder, ErrorMode error_mode){- auto& decoder = decoder_for_decode(fallback_decoder, input);+ auto decoder = decoder_for_decode(fallback_decoder, input);// 3. Process a queue with an instance of encoding’s decoder, ioQueue, output, and "replacement".// 4. Return output.@@ -403,30 +220,30 @@ ErrorOr<String> decode_to_utf8(StringView input, Decoder& fallback_decoder, Erro}// https://encoding.spec.whatwg.org/#decode-ErrorOr<Utf16String> decode_to_utf16(StringView input, Decoder& fallback_decoder)+ErrorOr<Utf16String> decode_to_utf16(ReadonlyBytes input, Decoder fallback_decoder){- auto& decoder = decoder_for_decode(fallback_decoder, input);+ auto decoder = decoder_for_decode(fallback_decoder, input);return decoder.to_utf16(input);}// https://encoding.spec.whatwg.org/#decode-ErrorOr<size_t> decoded_length_in_utf16_code_units(StringView input, Decoder& fallback_decoder)+ErrorOr<size_t> decoded_length_in_utf16_code_units(ReadonlyBytes input, Decoder fallback_decoder){- auto& decoder = decoder_for_decode(fallback_decoder, input);+ auto decoder = decoder_for_decode(fallback_decoder, input);return decoder.length_in_utf16_code_units(input);}// https://encoding.spec.whatwg.org/#utf-8-decode-ErrorOr<Utf16String> utf8_decode_to_utf16(StringView input)+ErrorOr<Utf16String> utf8_decode_to_utf16(ReadonlyBytes input){// 1. Let buffer be the result of peeking three bytes from ioQueue, converted to a byte sequence.// 2. If buffer is 0xEF 0xBB 0xBF, then read three bytes from ioQueue. (Do nothing with those bytes.)- if (input.starts_with("\xEF\xBB\xBF"sv))- input = input.substring_view(3);+ if (StringView { input }.starts_with("\xEF\xBB\xBF"sv))+ input = input.slice(3);// 3. Process a queue with an instance of UTF-8’s decoder, ioQueue, output, and "replacement".// 4. Return output.- return s_utf8_decoder.to_utf16(input);+ return decoder_for("UTF-8"sv)->to_utf16(input);}// https://encoding.spec.whatwg.org/#get-an-output-encoding@@ -440,65 +257,6 @@ StringView get_output_encoding(StringView encoding)return encoding;}-ErrorOr<String> Decoder::to_utf8(StringView input, ErrorMode)-{- StringBuilder builder(input.length());- TRY(process(input, [&builder](u32 c) { return builder.try_append_code_point(c); }));- return builder.to_string_without_validation();-}--ErrorOr<Utf16String> Decoder::to_utf16(StringView input)-{- Utf16StringBuilder builder;- TRY(process(input, [&builder](u32 c) -> ErrorOr<void> {- builder.append_code_point(c);- return {};- }));- return builder.to_string();-}--ErrorOr<size_t> Decoder::length_in_utf16_code_units(StringView input)-{- size_t length = 0;- TRY(process(input, [&](u32 code_point) -> ErrorOr<void> {- length += code_point <= 0xffff ? 1 : 2;- return {};- }));- return length;-}--ErrorOr<void> Decoder::process_code_points(StringView input, Function<ErrorOr<void>(u32)> on_code_point)-{- return process(input, move(on_code_point));-}--ErrorOr<String> RustDecoder::to_utf8(StringView input, ErrorMode error_mode)-{- return rust_decode_to_utf8(m_encoding, input, error_mode);-}--ErrorOr<size_t> RustDecoder::length_in_utf16_code_units(StringView input)-{- return rust_length_in_utf16_code_units(m_encoding, input);-}--ErrorOr<void> RustDecoder::process(StringView input, Function<ErrorOr<void>(u32)> on_code_point)-{- return rust_process(m_encoding, input, move(on_code_point));-}--ErrorOr<void> Latin1Decoder::process(StringView input, Function<ErrorOr<void>(u32)> on_code_point)-{- for (u8 ch : input)- TRY(on_code_point(ch));- return {};-}--ErrorOr<size_t> Latin1Decoder::length_in_utf16_code_units(StringView input)-{- return input.length();-}-StreamingDecoder::StreamingDecoder(StringView encoding, IgnoreBOM ignore_bom, ErrorMode error_mode){m_decoder = FFI::textcodec_rust_streaming_decoder_new(@@ -534,59 +292,6 @@ ErrorOr<Utf16String> StreamingDecoder::finish_to_utf16()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)-{- return rust_process("UTF-8"sv, input, move(on_code_point));-}--ErrorOr<String> UTF8Decoder::to_utf8(StringView input, ErrorMode error_mode)-{- return rust_decode_to_utf8("UTF-8"sv, input, error_mode);-}--ErrorOr<Utf16String> UTF8Decoder::to_utf16(StringView input)-{- // NB: Valid input decodes to the same code units as through process(), without a callback per code point.- if (Utf8View { input }.validate(AllowLonelySurrogates::No))- return Utf16String::from_utf8_without_validation(input);- return Decoder::to_utf16(input);-}--ErrorOr<size_t> UTF8Decoder::length_in_utf16_code_units(StringView input)-{- return rust_length_in_utf16_code_units("UTF-8"sv, input);-}--ErrorOr<void> UTF16BEDecoder::process(StringView input, Function<ErrorOr<void>(u32)> on_code_point)-{- return rust_process("UTF-16BE"sv, input, move(on_code_point));-}--ErrorOr<String> UTF16BEDecoder::to_utf8(StringView input, ErrorMode error_mode)-{- return rust_decode_to_utf8("UTF-16BE"sv, input, error_mode);-}--ErrorOr<size_t> UTF16BEDecoder::length_in_utf16_code_units(StringView input)-{- return rust_length_in_utf16_code_units("UTF-16BE"sv, input);-}--ErrorOr<void> UTF16LEDecoder::process(StringView input, Function<ErrorOr<void>(u32)> on_code_point)-{- return rust_process("UTF-16LE"sv, input, move(on_code_point));-}--ErrorOr<String> UTF16LEDecoder::to_utf8(StringView input, ErrorMode error_mode)-{- return rust_decode_to_utf8("UTF-16LE"sv, input, error_mode);-}--ErrorOr<size_t> UTF16LEDecoder::length_in_utf16_code_units(StringView input)-{- return rust_length_in_utf16_code_units("UTF-16LE"sv, input);-}-// https://infra.spec.whatwg.org/#isomorphic-decodeString isomorphic_decode(StringView input){diff --git a/Libraries/LibTextCodec/Decoder.h b/Libraries/LibTextCodec/Decoder.hindex b3fb6ff23fa..6a737929a87 100644--- a/Libraries/LibTextCodec/Decoder.h+++ b/Libraries/LibTextCodec/Decoder.h@@ -35,17 +35,28 @@ enum class ErrorMode {Fatal,};+class Decoder;++TEXTCODEC_API Optional<Decoder> decoder_for(StringView encoding);+TEXTCODEC_API Optional<Decoder> decoder_for(Utf16View encoding);+// NB: A decoder never removes a BOM. The decode algorithms below do that.class TEXTCODEC_API Decoder {public:- virtual ErrorOr<String> to_utf8(StringView, ErrorMode = ErrorMode::Replacement);- virtual ErrorOr<Utf16String> to_utf16(StringView);- virtual ErrorOr<size_t> length_in_utf16_code_units(StringView);- ErrorOr<void> process_code_points(StringView, Function<ErrorOr<void>(u32)>);--protected:- virtual ~Decoder() = default;- virtual ErrorOr<void> process(StringView, Function<ErrorOr<void>(u32)> on_code_point) = 0;+ ErrorOr<String> to_utf8(ReadonlyBytes, ErrorMode = ErrorMode::Replacement) const;+ ErrorOr<Utf16String> to_utf16(ReadonlyBytes) const;+ ErrorOr<size_t> length_in_utf16_code_units(ReadonlyBytes) const;++private:+ friend TEXTCODEC_API Optional<Decoder> decoder_for(StringView);+ friend TEXTCODEC_API Optional<Decoder> decoder_for(Utf16View);++ explicit Decoder(StringView encoding)+ : m_encoding(encoding)+ {+ }++ StringView m_encoding;};class TEXTCODEC_API StreamingDecoder final {@@ -66,22 +77,16 @@ private:void* m_decoder { nullptr };};-// This will return a decoder for the exact name specified, skipping get_standardized_encoding.-// Use this when you want ISO-8859-1 instead of windows-1252.-TEXTCODEC_API Optional<Decoder&> decoder_for_exact_name(StringView encoding);--TEXTCODEC_API Optional<Decoder&> decoder_for(StringView encoding);-TEXTCODEC_API Optional<Decoder&> decoder_for(Utf16View encoding);TEXTCODEC_API Optional<StringView> get_standardized_encoding(StringView encoding);TEXTCODEC_API Optional<StringView> get_standardized_encoding(Utf16View encoding);// https://encoding.spec.whatwg.org/#decode-TEXTCODEC_API ErrorOr<String> decode_to_utf8(StringView, Decoder& fallback_decoder, ErrorMode = ErrorMode::Replacement);-TEXTCODEC_API ErrorOr<Utf16String> decode_to_utf16(StringView, Decoder& fallback_decoder);-TEXTCODEC_API ErrorOr<size_t> decoded_length_in_utf16_code_units(StringView, Decoder& fallback_decoder);+TEXTCODEC_API ErrorOr<String> decode_to_utf8(ReadonlyBytes, Decoder fallback_decoder, ErrorMode = ErrorMode::Replacement);+TEXTCODEC_API ErrorOr<Utf16String> decode_to_utf16(ReadonlyBytes, Decoder fallback_decoder);+TEXTCODEC_API ErrorOr<size_t> decoded_length_in_utf16_code_units(ReadonlyBytes, Decoder fallback_decoder);// https://encoding.spec.whatwg.org/#utf-8-decode-TEXTCODEC_API ErrorOr<Utf16String> utf8_decode_to_utf16(StringView);+TEXTCODEC_API ErrorOr<Utf16String> utf8_decode_to_utf16(ReadonlyBytes);TEXTCODEC_API StringView get_output_encoding(StringView encoding);diff --git a/Libraries/LibTextCodec/Rust/src/lib.rs b/Libraries/LibTextCodec/Rust/src/lib.rsindex 78c9bedf26d..02bce6b8fef 100644--- a/Libraries/LibTextCodec/Rust/src/lib.rs+++ b/Libraries/LibTextCodec/Rust/src/lib.rs@@ -19,6 +19,7 @@ pub use streaming_decoder::{DecodingFailed, StreamingDecoder};use crate::rust_panic::abort_on_panic;use ak::Utf16StringUnits;+use encoding_rs::CoderResult;use encoding_rs::EncoderResult;use encoding_rs::Encoding;use std::ffi::c_void;@@ -126,6 +127,82 @@ pub unsafe extern "C" fn textcodec_rust_decode_to_utf8(}}+/// # Safety+/// - `encoding_label`/`encoding_label_len` and `input`/`input_len` must be valid byte slices.+/// - `on_utf16` must not retain `data` beyond the duration of the callback.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn textcodec_rust_decode_to_utf16(+ encoding_label: *const u8,+ encoding_label_len: usize,+ input: *const u8,+ input_len: usize,+ ctx: *mut c_void,+ on_utf16: FfiUtf16Fn,+) -> bool {+ unsafe {+ abort_on_panic(|| {+ let Some(label) = bytes_from_raw(encoding_label, encoding_label_len) else {+ return false;+ };+ let Some(input) = bytes_from_raw(input, input_len) else {+ return false;+ };+ let Some(encoding) = Encoding::for_label(label) else {+ return false;+ };+ let Ok(output) = StreamingDecoder::new(encoding, false, true).decode_to_utf16(input, false) else {+ return false;+ };+ on_utf16(ctx, output.as_ptr(), output.len());+ true+ })+ }+}++/// # Safety+/// - `encoding_label`/`encoding_label_len` and `input`/`input_len` must be valid byte slices.+/// - `out_length` must be a valid writable pointer.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn textcodec_rust_decoded_length_in_utf16_code_units(+ encoding_label: *const u8,+ encoding_label_len: usize,+ input: *const u8,+ input_len: usize,+ out_length: *mut usize,+) -> bool {+ unsafe {+ abort_on_panic(|| {+ let Some(label) = bytes_from_raw(encoding_label, encoding_label_len) else {+ return false;+ };+ let Some(input) = bytes_from_raw(input, input_len) else {+ return false;+ };+ let Some(encoding) = Encoding::for_label(label) else {+ return false;+ };+ if out_length.is_null() {+ eprintln!("textcodec_rust_decoded_length_in_utf16_code_units: null output pointer");+ return false;+ }++ let mut decoder = encoding.new_decoder_without_bom_handling();+ let mut output = [0u16; 4096];+ let mut total_read = 0;+ let mut length = 0;+ loop {+ let (result, read, written, _) = decoder.decode_to_utf16(&input[total_read..], &mut output, true);+ total_read += read;+ length += written;+ if result == CoderResult::InputEmpty {+ *out_length = length;+ return true;+ }+ }+ })+ }+}+/// # Safety/// - `encoding_label`/`encoding_label_len` must be a valid byte slice./// - The returned pointer must be freed with `textcodec_rust_streaming_decoder_free`.diff --git a/Libraries/LibWeb/Clipboard/Clipboard.cpp b/Libraries/LibWeb/Clipboard/Clipboard.cppindex b1786386687..1fefa240a46 100644--- a/Libraries/LibWeb/Clipboard/Clipboard.cpp+++ b/Libraries/LibWeb/Clipboard/Clipboard.cpp@@ -396,7 +396,7 @@ void Clipboard::read_text(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise)// 2. Return p.auto decoder = TextCodec::decoder_for("UTF-8"sv);- auto string = MUST(TextCodec::decode_to_utf8(*data, *decoder));+ auto string = MUST(TextCodec::decode_to_utf8(data->bytes(), *decoder));WebIDL::resolve_promise(promise, JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(string)));return;diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cppindex b14d8b1c52f..eeff5b7daef 100644--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp@@ -84,7 +84,7 @@ static void convert_to_xml_error_document(DOM::Document& document, Utf16String ebool build_xml_document(DOM::Document& document, ByteBuffer const& data, Optional<StringView> content_encoding){- Optional<TextCodec::Decoder&> decoder;+ Optional<TextCodec::Decoder> decoder;// The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification,// are the ones that must be used when determining the character encoding according to the rules given in the above specifications.if (content_encoding.has_value())@@ -201,7 +201,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navigcontent_encoding = *maybe_encoding;auto process_body = GC::create_function(GC::Heap::the(), [document, url = navigation_params.response->url().value(), content_encoding = move(content_encoding), mime = type](ByteBuffer data) {- Optional<TextCodec::Decoder&> decoder;+ Optional<TextCodec::Decoder> decoder;// The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification,// are the ones that must be used when determining the character encoding according to the rules given in the above specifications.if (content_encoding.has_value())diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cppindex 035ece5d915..8fec30ce627 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp@@ -166,7 +166,7 @@ static Utf16String decode_html_parser_input(StringView input, StringView encodin{auto decoder = TextCodec::decoder_for(encoding);VERIFY(decoder.has_value());- return MUST(TextCodec::decode_to_utf16(input, *decoder));+ return MUST(TextCodec::decode_to_utf16(input.bytes(), *decoder));}extern "C" void ladybird_html_parser_log_parse_error(void*, u8 const*, size_t);diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cppindex 81807714f5e..75420465770 100644--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp@@ -128,16 +128,6 @@ static BytecodeCacheSourceHash bytecode_cache_source_hash(ReadonlyBytes source_breturn hasher->digest();}-static ErrorOr<Utf16String> decode_source_text_to_utf16(TextCodec::Decoder& fallback_decoder, StringView input)-{- return TextCodec::decode_to_utf16(input, fallback_decoder);-}--static ErrorOr<Utf16String> decode_source_text_to_utf16(TextCodec::Decoder& fallback_decoder, ReadonlyBytes bytes)-{- return decode_source_text_to_utf16(fallback_decoder, StringView { bytes });-}-static ReadonlyBytes body_bytes_view(Fetch::Infrastructure::FetchAlgorithms::BodyBytes const& body_bytes){return body_bytes.get<Core::ImmutableBytes>().bytes();@@ -714,7 +704,7 @@ void fetch_classic_script(GC::Ref<HTMLScriptElement> element, URL::URL const& ur// materialize a script straight from the validated cached bytecode without parsing or compiling.if (bytecode.has_value()) {auto source_encoding = ByteString { extracted_character_encoding };- auto source_length = TextCodec::decoded_length_in_utf16_code_units(StringView { source_bytes }, *fallback_decoder).release_value_but_fixme_should_propagate_errors();+ auto source_length = TextCodec::decoded_length_in_utf16_code_units(source_bytes, *fallback_decoder).release_value_but_fixme_should_propagate_errors();prepare_bytecode_cache_off_thread(settings_object, *bytecode, JS::ProgramType::Script, source_length, *source_hash,[response_url = move(response_url), response_url_string = move(response_url_string),source_byte_storage = move(source_byte_storage),@@ -744,7 +734,7 @@ void fetch_classic_script(GC::Ref<HTMLScriptElement> element, URL::URL const& urVERIFY(fallback_decoder.has_value());source_code = JS::SourceCode::create(utf16_string_from_url_ascii(response_url_string.view()),- decode_source_text_to_utf16(*fallback_decoder, source_byte_storage.bytes()).release_value_but_fixme_should_propagate_errors());+ TextCodec::decode_to_utf16(source_byte_storage.bytes(), *fallback_decoder).release_value_but_fixme_should_propagate_errors());}auto retain_parse_for_cache = bytecode_cache_context.has_value();@@ -780,7 +770,7 @@ void fetch_classic_script(GC::Ref<HTMLScriptElement> element, URL::URL const& urif (!source_code.has_value()) {source_code = JS::SourceCode::create(utf16_string_from_url_ascii(response_url_string.view()),- decode_source_text_to_utf16(*fallback_decoder, source_bytes).release_value_but_fixme_should_propagate_errors());+ TextCodec::decode_to_utf16(source_bytes, *fallback_decoder).release_value_but_fixme_should_propagate_errors());}auto retain_parse_for_cache = bytecode_cache_context.has_value();@@ -1160,7 +1150,7 @@ void fetch_single_module_script(JS::Realm& realm,if (bytecode.has_value()) {auto decoder = TextCodec::decoder_for("UTF-8"sv);VERIFY(decoder.has_value());- auto source_length = TextCodec::decoded_length_in_utf16_code_units(StringView { source_bytes }, *decoder).release_value_but_fixme_should_propagate_errors();+ auto source_length = TextCodec::decoded_length_in_utf16_code_units(source_bytes, *decoder).release_value_but_fixme_should_propagate_errors();prepare_bytecode_cache_off_thread(settings_object, *bytecode, JS::ProgramType::Module, source_length, *source_hash,[url = move(url), url_string = move(url_string), response_url = move(response_url),module_type_string = move(module_type_string),diff --git a/Libraries/LibWebView/Autocomplete.cpp b/Libraries/LibWebView/Autocomplete.cppindex 679c12908bf..283f8deb9c1 100644--- a/Libraries/LibWebView/Autocomplete.cpp+++ b/Libraries/LibWebView/Autocomplete.cpp@@ -538,7 +538,7 @@ static ErrorOr<Vector<String>> parse_yahoo_autocomplete(JsonValue const& json)ErrorOr<Vector<String>> Autocomplete::received_autocomplete_response(SearchSuggestions const& provider, Optional<ByteString const&> content_type, StringView response){- auto decoder = [&]() -> Optional<TextCodec::Decoder&> {+ auto decoder = [&]() -> Optional<TextCodec::Decoder> {if (!content_type.has_value())return {};@@ -554,9 +554,9 @@ ErrorOr<Vector<String>> Autocomplete::received_autocomplete_response(SearchSugge}();if (!decoder.has_value())- decoder = TextCodec::decoder_for_exact_name("UTF-8"sv);+ decoder = TextCodec::decoder_for("UTF-8"sv);- auto decoded_response = TRY(TextCodec::decode_to_utf8(response, *decoder));+ auto decoded_response = TRY(TextCodec::decode_to_utf8(response.bytes(), *decoder));auto json = TRY(JsonValue::from_string(decoded_response));switch (provider.response_format) {diff --git a/Meta/Fuzzers/FuzzTextDecoder.cpp b/Meta/Fuzzers/FuzzTextDecoder.cppindex 3125527ac7e..e4ed45d4508 100644--- a/Meta/Fuzzers/FuzzTextDecoder.cpp+++ b/Meta/Fuzzers/FuzzTextDecoder.cpp@@ -24,6 +24,6 @@ extern "C" int LLVMFuzzerTestOneInput(uint8_t const* data, size_t size)if (!decoder.has_value())return 0;- (void)decoder->to_utf8(encoded_data);+ (void)decoder->to_utf8(encoded_data.bytes());return 0;}diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cppindex cd3336ffb9d..07edb00770f 100644--- a/Services/RequestServer/Request.cpp+++ b/Services/RequestServer/Request.cpp@@ -1961,10 +1961,7 @@ size_t Request::on_header_received(void* buffer, size_t size, size_t nmemb, voidif (space_index.has_value()) {if (auto reason_phrase = HTTP::normalize_header_value(header_line.substring_view(*space_index + 1)); !reason_phrase.is_empty()) {- auto decoder = TextCodec::decoder_for_exact_name("ISO-8859-1"sv);- VERIFY(decoder.has_value());-- request.m_reason_phrase = MUST(decoder->to_utf8(reason_phrase));+ request.m_reason_phrase = TextCodec::isomorphic_decode(reason_phrase);}}diff --git a/Tests/LibTextCodec/TestTextDecoders.cpp b/Tests/LibTextCodec/TestTextDecoders.cppindex 63065d526fb..0928a935e3c 100644--- a/Tests/LibTextCodec/TestTextDecoders.cpp+++ b/Tests/LibTextCodec/TestTextDecoders.cpp@@ -14,28 +14,30 @@ static ReadonlyBytes bytes(Vector<u8> const& data)return data.span();}-static TextCodec::Decoder& decoder_for(StringView encoding)+static TextCodec::Decoder decoder_for(StringView encoding){auto decoder = TextCodec::decoder_for(encoding);VERIFY(decoder.has_value());return decoder.value();}-static Vector<u32> process_code_points(TextCodec::Decoder& decoder, StringView input)+static Vector<u32> process_code_points(TextCodec::Decoder decoder, ReadonlyBytes input){+ auto utf16 = MUST(decoder.to_utf16(input));+ EXPECT_EQ(MUST(decoder.length_in_utf16_code_units(input)), utf16.length_in_code_units());+ EXPECT_EQ(Utf16String::from_utf8(MUST(decoder.to_utf8(input))), utf16);+Vector<u32> code_points;- MUST(decoder.process_code_points(input, [&](u32 code_point) -> ErrorOr<void> {- TRY(code_points.try_append(code_point));- return {};- }));+ for (auto code_point : utf16)+ code_points.append(code_point);return code_points;}TEST_CASE(test_utf8_decode){- auto& decoder = decoder_for("UTF-8"sv);+ auto decoder = decoder_for("UTF-8"sv);// Bytes for U+1F600 GRINNING FACE- auto test_string = "\xf0\x9f\x98\x80"sv;+ auto test_string = "\xf0\x9f\x98\x80"sv.bytes();EXPECT(!decoder.to_utf8(test_string, TextCodec::ErrorMode::Fatal).is_error());@@ -43,22 +45,22 @@ TEST_CASE(test_utf8_decode)EXPECT(processed_code_points.size() == 1);EXPECT(processed_code_points[0] == 0x1F600);- EXPECT(MUST(decoder.to_utf8(test_string)) == test_string);+ EXPECT_EQ(MUST(decoder.to_utf8(test_string)), StringView { test_string });}TEST_CASE(test_utf8_process_code_points){- auto& decoder = decoder_for("UTF-8"sv);- auto test_string = "A\xf0\x9f\x98\x80"sv;+ auto decoder = decoder_for("UTF-8"sv);+ auto test_string = "A\xf0\x9f\x98\x80"sv.bytes();EXPECT_EQ(process_code_points(decoder, test_string), (Vector<u32> { 0x41, 0x1F600 }));}TEST_CASE(test_utf8_process_code_points_replaces_surrogates){- auto& decoder = decoder_for("UTF-8"sv);+ auto decoder = decoder_for("UTF-8"sv);auto utf8_encoded_surrogate_bytes = Vector<u8> { 0xed, 0xa0, 0x80 };- auto utf8_encoded_surrogate = StringView(bytes(utf8_encoded_surrogate_bytes));+ auto utf8_encoded_surrogate = bytes(utf8_encoded_surrogate_bytes);EXPECT(decoder.to_utf8(utf8_encoded_surrogate, TextCodec::ErrorMode::Fatal).is_error());EXPECT_EQ(MUST(decoder.to_utf8(utf8_encoded_surrogate)), "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd"sv);@@ -67,9 +69,9 @@ TEST_CASE(test_utf8_process_code_points_replaces_surrogates)TEST_CASE(test_utf8_process_code_points_replaces_truncated_tail_as_single_error){- auto& decoder = decoder_for("UTF-8"sv);+ auto decoder = decoder_for("UTF-8"sv);auto truncated_tail_bytes = Vector<u8> { 0xf0, 0x9f, 0x98 };- auto truncated_tail = StringView(bytes(truncated_tail_bytes));+ auto truncated_tail = bytes(truncated_tail_bytes);EXPECT(decoder.to_utf8(truncated_tail, TextCodec::ErrorMode::Fatal).is_error());EXPECT_EQ(MUST(decoder.to_utf8(truncated_tail)), "\xef\xbf\xbd"sv);@@ -78,9 +80,9 @@ TEST_CASE(test_utf8_process_code_points_replaces_truncated_tail_as_single_error)TEST_CASE(test_utf8_process_code_points_replaces_overlong_sequences){- auto& decoder = decoder_for("UTF-8"sv);+ auto decoder = decoder_for("UTF-8"sv);auto overlong_null_bytes = Vector<u8> { 0xc0, 0x80 };- auto overlong_null = StringView(bytes(overlong_null_bytes));+ auto overlong_null = bytes(overlong_null_bytes);EXPECT(decoder.to_utf8(overlong_null, TextCodec::ErrorMode::Fatal).is_error());EXPECT_EQ(MUST(decoder.to_utf8(overlong_null)), "\xef\xbf\xbd\xef\xbf\xbd"sv);@@ -89,11 +91,11 @@ TEST_CASE(test_utf8_process_code_points_replaces_overlong_sequences)TEST_CASE(test_utf8_process_code_points_restores_invalid_second_byte){- auto& decoder = decoder_for("UTF-8"sv);+ auto decoder = decoder_for("UTF-8"sv);auto overlong_three_byte_sequence_bytes = Vector<u8> { 0xe0, 0x80, 0x80 };- auto overlong_three_byte_sequence = StringView(bytes(overlong_three_byte_sequence_bytes));+ auto overlong_three_byte_sequence = bytes(overlong_three_byte_sequence_bytes);auto out_of_range_four_byte_sequence_bytes = Vector<u8> { 0xf4, 0x90, 0x80, 0x80 };- auto out_of_range_four_byte_sequence = StringView(bytes(out_of_range_four_byte_sequence_bytes));+ auto out_of_range_four_byte_sequence = bytes(out_of_range_four_byte_sequence_bytes);EXPECT(decoder.to_utf8(overlong_three_byte_sequence, TextCodec::ErrorMode::Fatal).is_error());EXPECT_EQ(MUST(decoder.to_utf8(overlong_three_byte_sequence)), "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd"sv);@@ -106,9 +108,9 @@ TEST_CASE(test_utf8_process_code_points_restores_invalid_second_byte)TEST_CASE(test_utf16be_decode){- auto& decoder = decoder_for("UTF-16BE"sv);+ auto decoder = decoder_for("UTF-16BE"sv);// This is the output of `python3 -c "print('säk😀'.encode('utf-16be'))"`.- auto test_string = "\x00s\x00\xe4\x00k\xd8=\xde\x00"sv;+ auto test_string = "\x00s\x00\xe4\x00k\xd8=\xde\x00"sv.bytes();auto utf8 = MUST(decoder.to_utf8(test_string, TextCodec::ErrorMode::Fatal));EXPECT_EQ(utf8, "säk😀"sv);@@ -116,12 +118,12 @@ TEST_CASE(test_utf16be_decode)TEST_CASE(test_utf16be_process_code_points){- auto& decoder = decoder_for("UTF-16BE"sv);+ auto decoder = decoder_for("UTF-16BE"sv);- EXPECT_EQ(process_code_points(decoder, StringView(bytes({ 0xfe, 0xff, 0x00, 'A', 0xd8, 0x3d, 0xde, 0x00 }))), (Vector<u32> { 0xfeff, 0x41, 0x1F600 }));- EXPECT_EQ(process_code_points(decoder, StringView(bytes({ 0xd8, 0x3d, 0x00, 'A', 0xde, 0x00 }))), (Vector<u32> { 0xfffd, 0x41, 0xfffd }));- EXPECT_EQ(process_code_points(decoder, StringView(bytes({ 0x00, 'A', 0xff }))), (Vector<u32> { 0x41, 0xfffd }));- EXPECT_EQ(MUST(decoder.to_utf8(StringView(bytes({ 0x00, 'A', 0xff })))), "A\xef\xbf\xbd"sv);+ EXPECT_EQ(process_code_points(decoder, bytes({ 0xfe, 0xff, 0x00, 'A', 0xd8, 0x3d, 0xde, 0x00 })), (Vector<u32> { 0xfeff, 0x41, 0x1F600 }));+ EXPECT_EQ(process_code_points(decoder, bytes({ 0xd8, 0x3d, 0x00, 'A', 0xde, 0x00 })), (Vector<u32> { 0xfffd, 0x41, 0xfffd }));+ EXPECT_EQ(process_code_points(decoder, bytes({ 0x00, 'A', 0xff })), (Vector<u32> { 0x41, 0xfffd }));+ EXPECT_EQ(MUST(decoder.to_utf8(bytes({ 0x00, 'A', 0xff }))), "A\xef\xbf\xbd"sv);}TEST_CASE(test_streaming_decoder_utf8_mid_sequence)@@ -135,12 +137,12 @@ TEST_CASE(test_streaming_decoder_utf8_mid_sequence)TEST_CASE(test_streaming_decoder_finishes_incomplete_sequence){- auto& decoder = decoder_for("UTF-8"sv);+ auto decoder = decoder_for("UTF-8"sv);auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };auto incomplete_sequence = Vector<u8> { 0xc3 };EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes(incomplete_sequence))), ""sv);- EXPECT_EQ(MUST(streaming_decoder.finish()), MUST(decoder.to_utf8(StringView(bytes(incomplete_sequence)))));+ EXPECT_EQ(MUST(streaming_decoder.finish()), MUST(decoder.to_utf8(bytes(incomplete_sequence))));}TEST_CASE(test_streaming_decoder_utf8_invalid_second_byte_tail)@@ -232,57 +234,57 @@ TEST_CASE(test_streaming_decoder_utf16_surrogate_pair_split)TEST_CASE(test_streaming_decoder_gb18030_four_byte_tail){- auto& decoder = decoder_for("gb18030"sv);+ auto decoder = decoder_for("gb18030"sv);auto streaming_decoder = TextCodec::StreamingDecoder { "gb18030"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };auto gb18030_sequence = Vector<u8> { 0x81, 0x30, 0x81, 0x30 };EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 'a', 0x81, 0x30, 0x81 }))), "a"sv);- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x30 }))), MUST(decoder.to_utf8(StringView(bytes(gb18030_sequence)))));+ EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x30 }))), MUST(decoder.to_utf8(bytes(gb18030_sequence))));EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);}TEST_CASE(test_streaming_decoder_big5_overlapping_trail){- auto& decoder = decoder_for("Big5"sv);+ auto decoder = decoder_for("Big5"sv);auto streaming_decoder = TextCodec::StreamingDecoder { "Big5"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };auto big5_sequence = Vector<u8> { 0xa4, 0xa4 };- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes(big5_sequence))), MUST(decoder.to_utf8(StringView(bytes(big5_sequence)))));+ EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes(big5_sequence))), MUST(decoder.to_utf8(bytes(big5_sequence))));EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);auto streaming_decoder_for_split_input = TextCodec::StreamingDecoder { "Big5"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };EXPECT_EQ(MUST(streaming_decoder_for_split_input.to_utf8(bytes({ 0xa4 }))), ""sv);- EXPECT_EQ(MUST(streaming_decoder_for_split_input.to_utf8(bytes({ 0xa4 }))), MUST(decoder.to_utf8(StringView(bytes(big5_sequence)))));+ EXPECT_EQ(MUST(streaming_decoder_for_split_input.to_utf8(bytes({ 0xa4 }))), MUST(decoder.to_utf8(bytes(big5_sequence))));EXPECT_EQ(MUST(streaming_decoder_for_split_input.finish()), ""sv);}TEST_CASE(test_streaming_decoder_euc_jp_three_byte_tail){- auto& decoder = decoder_for("EUC-JP"sv);+ auto decoder = decoder_for("EUC-JP"sv);auto streaming_decoder = TextCodec::StreamingDecoder { "EUC-JP"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };auto euc_jp_sequence = Vector<u8> { 0x8f, 0xa2, 0xaf };EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x8f, 0xa2 }))), ""sv);- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xaf }))), MUST(decoder.to_utf8(StringView(bytes(euc_jp_sequence)))));+ EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xaf }))), MUST(decoder.to_utf8(bytes(euc_jp_sequence))));EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);}TEST_CASE(test_streaming_decoder_shift_jis_tail){- auto& decoder = decoder_for("Shift_JIS"sv);+ auto decoder = decoder_for("Shift_JIS"sv);auto streaming_decoder = TextCodec::StreamingDecoder { "Shift_JIS"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };auto shift_jis_sequence = Vector<u8> { 0x82, 0xa0 };EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x82 }))), ""sv);- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xa0 }))), MUST(decoder.to_utf8(StringView(bytes(shift_jis_sequence)))));+ EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xa0 }))), MUST(decoder.to_utf8(bytes(shift_jis_sequence))));EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);}TEST_CASE(test_utf16le_decode){- auto& decoder = decoder_for("UTF-16LE"sv);+ auto decoder = decoder_for("UTF-16LE"sv);// This is the output of `python3 -c "print('säk😀'.encode('utf-16le'))"`.- auto test_string = "s\x00\xe4\x00k\x00=\xd8\x00\xde"sv;+ auto test_string = "s\x00\xe4\x00k\x00=\xd8\x00\xde"sv.bytes();auto utf8 = MUST(decoder.to_utf8(test_string, TextCodec::ErrorMode::Fatal));EXPECT_EQ(utf8, "säk😀"sv);@@ -290,17 +292,17 @@ TEST_CASE(test_utf16le_decode)TEST_CASE(test_utf16le_process_code_points){- auto& decoder = decoder_for("UTF-16LE"sv);+ auto decoder = decoder_for("UTF-16LE"sv);- EXPECT_EQ(process_code_points(decoder, StringView(bytes({ 0xff, 0xfe, 'A', 0x00, 0x3d, 0xd8, 0x00, 0xde }))), (Vector<u32> { 0xfeff, 0x41, 0x1F600 }));- EXPECT_EQ(process_code_points(decoder, StringView(bytes({ 0x3d, 0xd8, 'A', 0x00, 0x00, 0xde }))), (Vector<u32> { 0xfffd, 0x41, 0xfffd }));- EXPECT_EQ(process_code_points(decoder, StringView(bytes({ 'A', 0x00, 0xff }))), (Vector<u32> { 0x41, 0xfffd }));- EXPECT_EQ(MUST(decoder.to_utf8(StringView(bytes({ 'A', 0x00, 0xff })))), "A\xef\xbf\xbd"sv);+ EXPECT_EQ(process_code_points(decoder, bytes({ 0xff, 0xfe, 'A', 0x00, 0x3d, 0xd8, 0x00, 0xde })), (Vector<u32> { 0xfeff, 0x41, 0x1F600 }));+ EXPECT_EQ(process_code_points(decoder, bytes({ 0x3d, 0xd8, 'A', 0x00, 0x00, 0xde })), (Vector<u32> { 0xfffd, 0x41, 0xfffd }));+ EXPECT_EQ(process_code_points(decoder, bytes({ 'A', 0x00, 0xff })), (Vector<u32> { 0x41, 0xfffd }));+ EXPECT_EQ(MUST(decoder.to_utf8(bytes({ 'A', 0x00, 0xff }))), "A\xef\xbf\xbd"sv);}TEST_CASE(test_decode_removes_only_the_sniffed_byte_order_mark){- auto& fallback_decoder = decoder_for("windows-1252"sv);+ auto fallback_decoder = decoder_for("windows-1252"sv);auto inputs = Array {Vector<u8> { 0xef, 0xbb, 0xbf, 0xef, 0xbb, 0xbf, 'A' },@@ -309,7 +311,7 @@ TEST_CASE(test_decode_removes_only_the_sniffed_byte_order_mark)};for (auto const& input_bytes : inputs) {- auto input = StringView(bytes(input_bytes));+ auto input = bytes(input_bytes);EXPECT_EQ(MUST(TextCodec::decode_to_utf16(input, fallback_decoder)), u"\uFEFFA"sv);EXPECT_EQ(MUST(TextCodec::decode_to_utf8(input, fallback_decoder)), "\uFEFFA"sv);EXPECT_EQ(MUST(TextCodec::decoded_length_in_utf16_code_units(input, fallback_decoder)), 2u);