Skip to content

Truly independent web browser

LibTextCodec: Decode streams to UTF-16 only

Shannon Boothc8fcddcdb83a
diff --git a/Libraries/LibTextCodec/Decoder.cpp b/Libraries/LibTextCodec/Decoder.cpp
index cfd7a109ca3..8358f6ef19d 100644
--- a/Libraries/LibTextCodec/Decoder.cpp
+++ b/Libraries/LibTextCodec/Decoder.cpp
@@ -55,22 +55,6 @@ ErrorOr<Utf16String> rust_streaming_decode_to_utf16(FFI::TextCodecRustStreamingD
return context.builder.to_string();
}
-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(
- decoder,
- input.data(),
- input.size(),
- last,
- &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();
-}
-
}
Optional<Decoder> decoder_for(StringView label)
@@ -272,26 +256,11 @@ StreamingDecoder::~StreamingDecoder()
FFI::textcodec_rust_streaming_decoder_free(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder));
}
-ErrorOr<String> StreamingDecoder::to_utf8(ReadonlyBytes input)
-{
- return rust_streaming_decode_to_utf8(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), input, false);
-}
-
-ErrorOr<Utf16String> StreamingDecoder::to_utf16(ReadonlyBytes input, Flush flush)
+ErrorOr<Utf16String> StreamingDecoder::decode(ReadonlyBytes input, Flush flush)
{
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);
-}
-
-ErrorOr<Utf16String> StreamingDecoder::finish_to_utf16()
-{
- return rust_streaming_decode_to_utf16(static_cast<FFI::TextCodecRustStreamingDecoder*>(m_decoder), {}, true);
-}
-
// https://infra.spec.whatwg.org/#isomorphic-decode
String isomorphic_decode(StringView input)
{
diff --git a/Libraries/LibTextCodec/Decoder.h b/Libraries/LibTextCodec/Decoder.h
index 6a737929a87..e6ff9ed6000 100644
--- a/Libraries/LibTextCodec/Decoder.h
+++ b/Libraries/LibTextCodec/Decoder.h
@@ -68,10 +68,7 @@ public:
StreamingDecoder(StringView encoding, IgnoreBOM, ErrorMode);
~StreamingDecoder();
- ErrorOr<String> to_utf8(ReadonlyBytes);
- ErrorOr<Utf16String> to_utf16(ReadonlyBytes, Flush = Flush::No);
- ErrorOr<String> finish();
- ErrorOr<Utf16String> finish_to_utf16();
+ ErrorOr<Utf16String> decode(ReadonlyBytes, Flush = Flush::No);
private:
void* m_decoder { nullptr };
diff --git a/Libraries/LibTextCodec/Rust/src/lib.rs b/Libraries/LibTextCodec/Rust/src/lib.rs
index 02bce6b8fef..992e41feaf5 100644
--- a/Libraries/LibTextCodec/Rust/src/lib.rs
+++ b/Libraries/LibTextCodec/Rust/src/lib.rs
@@ -150,7 +150,7 @@ pub unsafe extern "C" fn textcodec_rust_decode_to_utf16(
let Some(encoding) = Encoding::for_label(label) else {
return false;
};
- let Ok(output) = StreamingDecoder::new(encoding, false, true).decode_to_utf16(input, false) else {
+ let Ok(output) = StreamingDecoder::new(encoding, false, true).decode(input, false) else {
return false;
};
on_utf16(ctx, output.as_ptr(), output.len());
@@ -240,39 +240,6 @@ pub unsafe extern "C" fn textcodec_rust_streaming_decoder_free(decoder: *mut Tex
}
}
-/// # Safety
-/// - `decoder` must be a valid pointer returned by `textcodec_rust_streaming_decoder_new`.
-/// - `input`/`input_len` must be a valid byte slice.
-/// - `on_bytes` must not retain `data` beyond the duration of the callback.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn textcodec_rust_streaming_decoder_decode_to_utf8(
- decoder: *mut TextCodecRustStreamingDecoder,
- input: *const u8,
- input_len: usize,
- last: bool,
- ctx: *mut c_void,
- on_bytes: FfiBytesFn,
-) -> bool {
- unsafe {
- abort_on_panic(|| {
- if decoder.is_null() {
- eprintln!("textcodec_rust_streaming_decoder_decode_to_utf8: null decoder pointer");
- return false;
- }
- let Some(input) = bytes_from_raw(input, input_len) else {
- return false;
- };
- 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());
- }
- true
- })
- }
-}
-
/// # Safety
/// - `decoder` must be a valid pointer returned by `textcodec_rust_streaming_decoder_new`.
/// - `input`/`input_len` must be a valid byte slice.
@@ -295,7 +262,7 @@ 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 Ok(output) = (*decoder).decoder.decode_to_utf16(input, !last) else {
+ let Ok(output) = (*decoder).decoder.decode(input, !last) else {
return false;
};
if !output.is_empty() {
diff --git a/Libraries/LibTextCodec/Rust/src/streaming_decoder.rs b/Libraries/LibTextCodec/Rust/src/streaming_decoder.rs
index d3d37b2da1b..f972cefc71b 100644
--- a/Libraries/LibTextCodec/Rust/src/streaming_decoder.rs
+++ b/Libraries/LibTextCodec/Rust/src/streaming_decoder.rs
@@ -48,31 +48,10 @@ impl StreamingDecoder {
/// 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.
/// A failure discards the rest of the bytes, and with them whatever the decoder kept of them.
- pub fn decode_to_utf16(&mut self, input: &[u8], more_input_follows: bool) -> Result<Vec<u16>, DecodingFailed> {
- let mut decoded = self.decode_to_utf16_with_current_decoder(input, !more_input_follows);
+ pub fn decode(&mut self, input: &[u8], more_input_follows: bool) -> Result<Vec<u16>, DecodingFailed> {
+ let mut decoded = self.decode_with_current_decoder(input, !more_input_follows);
match &mut decoded {
- Ok(output) => {
- if self.removes_bom_from_output(output.is_empty(), output.first() == Some(&0xFEFF)) {
- output.remove(0);
- }
- }
- Err(DecodingFailed) => self.forget_rest_of_input(),
- }
- if !more_input_follows {
- self.start_over();
- }
- 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 mut decoded = self.decode_to_utf8_with_current_decoder(input, !more_input_follows);
- match &mut decoded {
- Ok(output) => {
- if self.removes_bom_from_output(output.is_empty(), output.starts_with('\u{FEFF}')) {
- output.drain(..'\u{FEFF}'.len_utf8());
- }
- }
+ Ok(output) => self.remove_bom_from_output(output),
Err(DecodingFailed) => self.forget_rest_of_input(),
}
if !more_input_follows {
@@ -82,17 +61,19 @@ impl StreamingDecoder {
}
// https://encoding.spec.whatwg.org/#concept-td-serialize
- fn removes_bom_from_output(&mut self, output_is_empty: bool, output_starts_with_bom: bool) -> bool {
+ fn remove_bom_from_output(&mut self, output: &mut Vec<u16>) {
// NB: The BOM is removed from the output of a call that succeeded, rather than from the input, so that a call
// that fails does not consume it.
- if self.bom_seen || output_is_empty {
- return false;
+ if self.bom_seen || output.is_empty() {
+ return;
}
self.bom_seen = true;
let is_unicode_encoding = self.encoding == encoding_rs::UTF_8
|| self.encoding == encoding_rs::UTF_16BE
|| self.encoding == encoding_rs::UTF_16LE;
- !self.ignore_bom && is_unicode_encoding && output_starts_with_bom
+ if !self.ignore_bom && is_unicode_encoding && output[0] == 0xFEFF {
+ output.remove(0);
+ }
}
fn start_over(&mut self) {
@@ -109,7 +90,7 @@ impl StreamingDecoder {
}
}
- fn decode_to_utf16_with_current_decoder(&mut self, input: &[u8], last: bool) -> Result<Vec<u16>, DecodingFailed> {
+ 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())
@@ -131,29 +112,6 @@ impl StreamingDecoder {
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)]
@@ -171,92 +129,61 @@ mod tests {
#[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()));
+ 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_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()));
+ 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_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"))
- );
+ 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_to_utf16(&[0xEF, 0xBB, 0xBF, 0x61], false),
- Ok(utf16("\u{FEFF}a"))
- );
+ 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_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));
+ 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_discards_the_rest_of_its_bytes() {
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")));
+ 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")));
let mut gb18030 = StreamingDecoder::new(encoding_rs::GB18030, true, false);
- assert_eq!(gb18030.decode_to_utf16(&[0x81, 0x30, 0xFF], true), Err(DecodingFailed));
- assert_eq!(gb18030.decode_to_utf16(&[], false), Ok(Vec::new()));
-
- let mut gb18030 = StreamingDecoder::new(encoding_rs::GB18030, true, false);
- assert_eq!(gb18030.decode_to_utf8(&[0x81, 0x30, 0xFF], true), Err(DecodingFailed));
- assert_eq!(gb18030.decode_to_utf8(&[], false), Ok(String::new()));
+ assert_eq!(gb18030.decode(&[0x81, 0x30, 0xFF], true), Err(DecodingFailed));
+ assert_eq!(gb18030.decode(&[], false), Ok(Vec::new()));
}
#[test]
fn a_failure_keeps_the_byte_order_mark_unseen() {
let mut decoder = utf8_decoder(true, false);
- assert_eq!(decoder.decode_to_utf16(&[0x61, 0xFF], true), Err(DecodingFailed));
- assert_eq!(decoder.decode_to_utf16(&[0xEF, 0xBB, 0xBF, 0x62], true), Ok(utf16("b")));
-
- let mut decoder = utf8_decoder(true, false);
- assert_eq!(decoder.decode_to_utf8(&[0xFF], true), Err(DecodingFailed));
- assert_eq!(
- decoder.decode_to_utf8(&[0xEF, 0xBB, 0xBF, 0x62], true),
- Ok("b".to_string())
- );
+ assert_eq!(decoder.decode(&[0x61, 0xFF], true), Err(DecodingFailed));
+ assert_eq!(decoder.decode(&[0xEF, 0xBB, 0xBF, 0x62], true), Ok(utf16("b")));
}
#[test]
fn a_byte_order_mark_split_over_chunks_is_removed() {
let mut decoder = utf8_decoder(false, false);
- assert_eq!(decoder.decode_to_utf16(&[0xEF, 0xBB], true), Ok(Vec::new()));
- assert_eq!(decoder.decode_to_utf16(&[0xBF, 0x61], true), Ok(utf16("a")));
- assert_eq!(
- decoder.decode_to_utf16(&[0xEF, 0xBB, 0xBF], false),
- Ok(utf16("\u{FEFF}"))
- );
+ assert_eq!(decoder.decode(&[0xEF, 0xBB], true), Ok(Vec::new()));
+ assert_eq!(decoder.decode(&[0xBF, 0x61], true), Ok(utf16("a")));
+ assert_eq!(decoder.decode(&[0xEF, 0xBB, 0xBF], false), Ok(utf16("\u{FEFF}")));
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs
index c1b0545ed96..046f714fc8b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs
@@ -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_to_utf16(bytes, options.stream)) },
- None => decoder.decode_to_utf16(&[], options.stream),
+ Some(input) => unsafe { input.with_bytes(|bytes| decoder.decode(bytes, options.stream)) },
+ None => decoder.decode(&[], options.stream),
};
let decoded =
decoded.map_err(|DecodingFailed| Exception::TypeError(Utf16String::from_ascii(b"Decoding failed")))?;
diff --git a/Libraries/LibWeb/Encoding/TextDecoderCommon.cpp b/Libraries/LibWeb/Encoding/TextDecoderCommon.cpp
index c231243ec62..fc65bc18eb3 100644
--- a/Libraries/LibWeb/Encoding/TextDecoderCommon.cpp
+++ b/Libraries/LibWeb/Encoding/TextDecoderCommon.cpp
@@ -9,32 +9,33 @@
namespace Web::Encoding {
-ErrorOr<void> TextDecoderOutputQueue::push(String output)
+void TextDecoderOutputQueue::push(Utf16String output)
{
if (output.is_empty())
- return {};
+ return;
- if (m_has_builder)
- return m_builder.try_append(output.bytes_as_string_view());
+ if (m_has_builder) {
+ m_builder.append(output);
+ return;
+ }
if (!m_single_output.has_value()) {
m_single_output = move(output);
- return {};
+ return;
}
m_has_builder = true;
- TRY(m_builder.try_append(m_single_output->bytes_as_string_view()));
- m_single_output.clear();
- return m_builder.try_append(output.bytes_as_string_view());
+ m_builder.append(m_single_output.release_value());
+ m_builder.append(output);
}
-ErrorOr<Utf16String> TextDecoderOutputQueue::serialize()
+Utf16String TextDecoderOutputQueue::serialize()
{
if (m_has_builder)
- return Utf16String::from_utf8(TRY(m_builder.to_string()));
+ return m_builder.to_string();
if (m_single_output.has_value())
- return Utf16String::from_utf8(m_single_output.release_value());
- return Utf16String {};
+ return m_single_output.release_value();
+ return {};
}
TextDecoderCommonMixin::TextDecoderCommonMixin(FlyString encoding, TextCodec::ErrorMode error_mode, bool ignore_bom)
@@ -50,31 +51,30 @@ void TextDecoderCommonMixin::set_decoder_to_new_instance_of_encoding_decoder() c
m_decoder = make<TextCodec::StreamingDecoder>(m_encoding, m_ignore_bom ? TextCodec::IgnoreBOM::Yes : TextCodec::IgnoreBOM::No, m_error_mode);
}
-static WebIDL::ExceptionOr<void> append_decoded_output(JS::VM& vm, TextDecoderOutputQueue& output, ErrorOr<String> decoded_or_error)
+static WebIDL::ExceptionOr<void> append_decoded_output(TextDecoderOutputQueue& output, ErrorOr<Utf16String> decoded_or_error)
{
- if (decoded_or_error.is_error() && decoded_or_error.error().code() != ENOMEM)
+ if (decoded_or_error.is_error())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Decoding failed"_utf16 };
- auto decoded = TRY_OR_THROW_OOM(vm, move(decoded_or_error));
- TRY_OR_THROW_OOM(vm, output.push(move(decoded)));
+ output.push(decoded_or_error.release_value());
return {};
}
-WebIDL::ExceptionOr<void> TextDecoderCommonMixin::process_an_item(JS::VM& vm, ReadonlyBytes item, TextDecoderOutputQueue& output)
+WebIDL::ExceptionOr<void> TextDecoderCommonMixin::process_an_item(ReadonlyBytes item, TextDecoderOutputQueue& output)
{
VERIFY(m_decoder);
- return append_decoded_output(vm, output, m_decoder->to_utf8(item));
+ return append_decoded_output(output, m_decoder->decode(item));
}
-WebIDL::ExceptionOr<void> TextDecoderCommonMixin::process_an_item(JS::VM& vm, EndOfQueue, TextDecoderOutputQueue& output)
+WebIDL::ExceptionOr<void> TextDecoderCommonMixin::process_an_item(EndOfQueue, TextDecoderOutputQueue& output)
{
VERIFY(m_decoder);
- return append_decoded_output(vm, output, m_decoder->finish());
+ return append_decoded_output(output, m_decoder->decode({}, TextCodec::Flush::Yes));
}
-WebIDL::ExceptionOr<Utf16String> TextDecoderCommonMixin::serialize_io_queue(JS::VM& vm, TextDecoderOutputQueue& output)
+Utf16String TextDecoderCommonMixin::serialize_io_queue(TextDecoderOutputQueue& output)
{
- return TRY_OR_THROW_OOM(vm, output.serialize());
+ return output.serialize();
}
}
diff --git a/Libraries/LibWeb/Encoding/TextDecoderCommon.h b/Libraries/LibWeb/Encoding/TextDecoderCommon.h
index 79d3bcc19c1..c2f568e50c8 100644
--- a/Libraries/LibWeb/Encoding/TextDecoderCommon.h
+++ b/Libraries/LibWeb/Encoding/TextDecoderCommon.h
@@ -8,8 +8,8 @@
#include <AK/FlyString.h>
#include <AK/OwnPtr.h>
-#include <AK/StringBuilder.h>
#include <AK/Utf16FlyString.h>
+#include <AK/Utf16StringBuilder.h>
#include <LibJS/Forward.h>
#include <LibTextCodec/Decoder.h>
#include <LibWeb/Bindings/TextDecoder.h>
@@ -24,12 +24,12 @@ struct EndOfQueue {
class TextDecoderOutputQueue {
public:
- ErrorOr<void> push(String);
- ErrorOr<Utf16String> serialize();
+ void push(Utf16String);
+ Utf16String serialize();
private:
- Optional<String> m_single_output;
- StringBuilder m_builder;
+ Optional<Utf16String> m_single_output;
+ Utf16StringBuilder m_builder;
bool m_has_builder { false };
};
@@ -49,9 +49,9 @@ protected:
TextDecoderCommonMixin(FlyString encoding, TextCodec::ErrorMode error_mode, bool ignore_bom);
void set_decoder_to_new_instance_of_encoding_decoder() const;
- WebIDL::ExceptionOr<void> process_an_item(JS::VM&, ReadonlyBytes item, TextDecoderOutputQueue& output);
- WebIDL::ExceptionOr<void> process_an_item(JS::VM&, EndOfQueue, TextDecoderOutputQueue& output);
- WebIDL::ExceptionOr<Utf16String> serialize_io_queue(JS::VM&, TextDecoderOutputQueue& output);
+ WebIDL::ExceptionOr<void> process_an_item(ReadonlyBytes item, TextDecoderOutputQueue& output);
+ WebIDL::ExceptionOr<void> process_an_item(EndOfQueue, TextDecoderOutputQueue& output);
+ Utf16String serialize_io_queue(TextDecoderOutputQueue& output);
// https://encoding.spec.whatwg.org/#textdecodercommon-decoder
mutable OwnPtr<TextCodec::StreamingDecoder> m_decoder;
diff --git a/Libraries/LibWeb/Encoding/TextDecoderStream.cpp b/Libraries/LibWeb/Encoding/TextDecoderStream.cpp
index fad6aa4a895..5fa1e1e8df4 100644
--- a/Libraries/LibWeb/Encoding/TextDecoderStream.cpp
+++ b/Libraries/LibWeb/Encoding/TextDecoderStream.cpp
@@ -107,8 +107,8 @@ WebIDL::ExceptionOr<void> TextDecoderStream::decode_and_enqueue_chunk(JS::VM& vm
// Decode this chunk while preserving the streaming decoder's pending state.
TextDecoderOutputQueue output;
- TRY(process_an_item(vm, input_copy.bytes(), output));
- auto decoded = TRY(serialize_io_queue(vm, output));
+ TRY(process_an_item(input_copy.bytes(), output));
+ auto decoded = serialize_io_queue(output);
return enqueue_decoded_output(vm, decoded);
}
@@ -127,14 +127,14 @@ WebIDL::ExceptionOr<void> TextDecoderStream::flush_and_enqueue(JS::VM& vm)
// 2. Let result be the result of processing an item with item, this’s decoder, decoder’s I/O queue, output, and decoder’s
// error mode.
- auto result = process_an_item(vm, item, output);
+ auto result = process_an_item(item, output);
// 3. If result is finished:
// 1. Let outputChunk be the result of running serialize I/O queue with decoder and output.
// 2. If outputChunk is not the empty string, then enqueue outputChunk in decoder’s transform.
// 3. Return.
if (!result.is_error()) {
- auto output_chunk = TRY(serialize_io_queue(vm, output));
+ auto output_chunk = serialize_io_queue(output);
TRY(enqueue_decoded_output(vm, output_chunk));
return {};
}
diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
index dc9ed033773..aa55d4b5096 100644
--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
@@ -274,7 +274,7 @@ void IncrementalDocumentParser::finish_body()
VERIFY(m_body_is_exhausted);
VERIFY(undecoded_input_bytes().is_empty());
- auto decoded = m_decoder->finish_to_utf16().release_value_but_fixme_should_propagate_errors();
+ auto decoded = m_decoder->decode({}, TextCodec::Flush::Yes).release_value_but_fixme_should_propagate_errors();
append_decoded(decoded);
// https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-html
@@ -296,9 +296,9 @@ ErrorOr<bool> IncrementalDocumentParser::change_encoding(StringView new_encoding
auto decoder = make<TextCodec::StreamingDecoder>(new_encoding, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement);
Utf16StringBuilder builder;
- builder.append(TRY(decoder->to_utf16(decoded_input_bytes())));
+ builder.append(TRY(decoder->decode(decoded_input_bytes())));
if (m_processed_implied_eof)
- builder.append(TRY(decoder->finish_to_utf16()));
+ builder.append(TRY(decoder->decode({}, TextCodec::Flush::Yes)));
auto redecoded_source = builder.to_string();
auto current_source = m_processed_implied_eof ? m_document->source().utf16_view() : m_source.view();
@@ -326,7 +326,7 @@ void IncrementalDocumentParser::decode_and_process(size_t length)
auto undecoded_bytes = undecoded_input_bytes();
VERIFY(length <= undecoded_bytes.size());
- auto decoded = m_decoder->to_utf16(undecoded_bytes.trim(length)).release_value_but_fixme_should_propagate_errors();
+ auto decoded = m_decoder->decode(undecoded_bytes.trim(length)).release_value_but_fixme_should_propagate_errors();
// Count the bytes as converted before running the parser: a script it runs can deliver another body chunk, and
// feed_parser() would otherwise convert these a second time.
diff --git a/Tests/LibTextCodec/TestTextDecoders.cpp b/Tests/LibTextCodec/TestTextDecoders.cpp
index 0928a935e3c..293f08f9f3d 100644
--- a/Tests/LibTextCodec/TestTextDecoders.cpp
+++ b/Tests/LibTextCodec/TestTextDecoders.cpp
@@ -33,6 +33,11 @@ static Vector<u32> process_code_points(TextCodec::Decoder decoder, ReadonlyBytes
return code_points;
}
+static ErrorOr<String> decode_to_utf8(TextCodec::StreamingDecoder& decoder, ReadonlyBytes input, TextCodec::Flush flush = TextCodec::Flush::No)
+{
+ return TRY(decoder.decode(input, flush)).to_utf8();
+}
+
TEST_CASE(test_utf8_decode)
{
auto decoder = decoder_for("UTF-8"sv);
@@ -130,9 +135,9 @@ TEST_CASE(test_streaming_decoder_utf8_mid_sequence)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 'a', 0xc3 }))), "a"sv);
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xa9, 'b' }))), "éb"sv);
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 'a', 0xc3 }))), "a"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0xa9, 'b' }))), "éb"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_finishes_incomplete_sequence)
@@ -141,95 +146,84 @@ TEST_CASE(test_streaming_decoder_finishes_incomplete_sequence)
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(bytes(incomplete_sequence))));
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes(incomplete_sequence))), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), MUST(decoder.to_utf8(bytes(incomplete_sequence))));
}
TEST_CASE(test_streaming_decoder_utf8_invalid_second_byte_tail)
{
auto streaming_decoder_for_overlong_three_byte_sequence = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder_for_overlong_three_byte_sequence.to_utf8(bytes({ 0xe0, 0x80 }))), "\xef\xbf\xbd\xef\xbf\xbd"sv);
- EXPECT_EQ(MUST(streaming_decoder_for_overlong_three_byte_sequence.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_for_overlong_three_byte_sequence, bytes({ 0xe0, 0x80 }))), "\xef\xbf\xbd\xef\xbf\xbd"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_for_overlong_three_byte_sequence, {}, TextCodec::Flush::Yes)), ""sv);
auto streaming_decoder_for_out_of_range_four_byte_sequence = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder_for_out_of_range_four_byte_sequence.to_utf8(bytes({ 0xf4, 0x90 }))), "\xef\xbf\xbd\xef\xbf\xbd"sv);
- EXPECT_EQ(MUST(streaming_decoder_for_out_of_range_four_byte_sequence.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_for_out_of_range_four_byte_sequence, bytes({ 0xf4, 0x90 }))), "\xef\xbf\xbd\xef\xbf\xbd"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_for_out_of_range_four_byte_sequence, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_utf8_valid_second_byte_tail)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xe0, 0xa0 }))), ""sv);
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x80 }))), "\xe0\xa0\x80"sv);
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0xe0, 0xa0 }))), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0x80 }))), "\xe0\xa0\x80"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_utf8_fatal_error_does_not_buffer_later_bytes)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Fatal };
- EXPECT(streaming_decoder.to_utf8(bytes({ 0xfd, 0xef })).is_error());
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT(decode_to_utf8(streaming_decoder, bytes({ 0xfd, 0xef })).is_error());
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_fatal_error_discards_bytes_kept_by_the_decoder)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "gb18030"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Fatal };
- EXPECT(streaming_decoder.to_utf8(bytes({ 0x81, 0x30, 0xff })).is_error());
- EXPECT_EQ(MUST(streaming_decoder.to_utf8({})), ""sv);
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
-
- auto utf16_streaming_decoder = TextCodec::StreamingDecoder { "gb18030"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Fatal };
-
- EXPECT(utf16_streaming_decoder.to_utf16(bytes({ 0x81, 0x30, 0xff })).is_error());
- EXPECT_EQ(MUST(utf16_streaming_decoder.to_utf16({})), u""sv);
- EXPECT_EQ(MUST(utf16_streaming_decoder.finish_to_utf16()), u""sv);
+ EXPECT(decode_to_utf8(streaming_decoder, bytes({ 0x81, 0x30, 0xff })).is_error());
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {})), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_fatal_error_keeps_bom_removal)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Fatal };
- EXPECT(streaming_decoder.to_utf8(bytes({ 0xff })).is_error());
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xef, 0xbb, 0xbf, 'A' }))), "A"sv);
-
- auto utf16_streaming_decoder = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Fatal };
-
- EXPECT(utf16_streaming_decoder.to_utf16(bytes({ 'A', 0xff })).is_error());
- EXPECT_EQ(MUST(utf16_streaming_decoder.to_utf16(bytes({ 0xef, 0xbb, 0xbf, 'A' }))), u"A"sv);
+ EXPECT(decode_to_utf8(streaming_decoder, bytes({ 0xff })).is_error());
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0xef, 0xbb, 0xbf, 'A' }))), "A"sv);
}
TEST_CASE(test_streaming_decoder_removes_only_a_leading_bom)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-8"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder.to_utf16(bytes({ 0xef, 0xbb }))), u""sv);
- EXPECT_EQ(MUST(streaming_decoder.to_utf16(bytes({ 0xbf, 'A' }))), u"A"sv);
- EXPECT_EQ(MUST(streaming_decoder.to_utf16(bytes({ 0xef, 0xbb, 0xbf }))), u"\uFEFF"sv);
+ EXPECT_EQ(MUST(streaming_decoder.decode(bytes({ 0xef, 0xbb }))), u""sv);
+ EXPECT_EQ(MUST(streaming_decoder.decode(bytes({ 0xbf, 'A' }))), u"A"sv);
+ EXPECT_EQ(MUST(streaming_decoder.decode(bytes({ 0xef, 0xbb, 0xbf }))), u"\uFEFF"sv);
auto streaming_decoder_ignoring_bom = TextCodec::StreamingDecoder { "UTF-16LE"sv, TextCodec::IgnoreBOM::Yes, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder_ignoring_bom.to_utf8(bytes({ 0xff, 0xfe, 'A', 0x00 }))), "\uFEFFA"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_ignoring_bom, bytes({ 0xff, 0xfe, 'A', 0x00 }))), "\uFEFFA"sv);
}
TEST_CASE(test_streaming_decoder_utf16_odd_byte)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-16LE"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x41, 0x00, 0x42 }))), "A"sv);
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x00 }))), "B"sv);
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0x41, 0x00, 0x42 }))), "A"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0x00 }))), "B"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_utf16_surrogate_pair_split)
{
auto streaming_decoder = TextCodec::StreamingDecoder { "UTF-16BE"sv, TextCodec::IgnoreBOM::No, TextCodec::ErrorMode::Replacement };
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0x00, 0x41, 0xd8, 0x3d }))), "A"sv);
- EXPECT_EQ(MUST(streaming_decoder.to_utf8(bytes({ 0xde, 0x00 }))), "😀"sv);
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0x00, 0x41, 0xd8, 0x3d }))), "A"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0xde, 0x00 }))), "😀"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_gb18030_four_byte_tail)
@@ -238,9 +232,9 @@ TEST_CASE(test_streaming_decoder_gb18030_four_byte_tail)
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(bytes(gb18030_sequence))));
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 'a', 0x81, 0x30, 0x81 }))), "a"sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0x30 }))), MUST(decoder.to_utf8(bytes(gb18030_sequence))));
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_big5_overlapping_trail)
@@ -249,13 +243,13 @@ TEST_CASE(test_streaming_decoder_big5_overlapping_trail)
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(bytes(big5_sequence))));
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes(big5_sequence))), MUST(decoder.to_utf8(bytes(big5_sequence))));
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""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(bytes(big5_sequence))));
- EXPECT_EQ(MUST(streaming_decoder_for_split_input.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_for_split_input, bytes({ 0xa4 }))), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_for_split_input, bytes({ 0xa4 }))), MUST(decoder.to_utf8(bytes(big5_sequence))));
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder_for_split_input, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_euc_jp_three_byte_tail)
@@ -264,9 +258,9 @@ TEST_CASE(test_streaming_decoder_euc_jp_three_byte_tail)
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(bytes(euc_jp_sequence))));
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0x8f, 0xa2 }))), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0xaf }))), MUST(decoder.to_utf8(bytes(euc_jp_sequence))));
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_streaming_decoder_shift_jis_tail)
@@ -275,9 +269,9 @@ TEST_CASE(test_streaming_decoder_shift_jis_tail)
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(bytes(shift_jis_sequence))));
- EXPECT_EQ(MUST(streaming_decoder.finish()), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0x82 }))), ""sv);
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, bytes({ 0xa0 }))), MUST(decoder.to_utf8(bytes(shift_jis_sequence))));
+ EXPECT_EQ(MUST(decode_to_utf8(streaming_decoder, {}, TextCodec::Flush::Yes)), ""sv);
}
TEST_CASE(test_utf16le_decode)