Skip to content

Truly independent web browser

LibTextCodec: Encode through a fixed-size output buffer

Shannon Boothe0599021f21e
diff --git a/Libraries/LibTextCodec/Rust/src/lib.rs b/Libraries/LibTextCodec/Rust/src/lib.rs
index 2a6bedba483..fba288b8a1f 100644
--- a/Libraries/LibTextCodec/Rust/src/lib.rs
+++ b/Libraries/LibTextCodec/Rust/src/lib.rs
@@ -293,24 +293,23 @@ pub unsafe extern "C" fn textcodec_rust_encode_from_utf8(
let mut encoder = encoding.new_encoder();
let mut total_read = 0usize;
- let Some(output_capacity) = encoder.max_buffer_length_from_utf8_without_replacement(input.len()) else {
- return false;
- };
- let mut output = Vec::with_capacity(output_capacity);
+
+ // NB: A fixed-size buffer keeps the work per call proportional to the input it consumes. Sizing the
+ // buffer for the whole input would cost that much again after every unmappable code point.
+ let mut output = [0u8; 4096];
loop {
- let (result, read) =
- encoder.encode_from_utf8_to_vec_without_replacement(&input[total_read..], &mut output, true);
+ let (result, read, written) =
+ encoder.encode_from_utf8_without_replacement(&input[total_read..], &mut output, true);
total_read += read;
- if !output.is_empty() {
- on_bytes(ctx, output.as_ptr(), output.len());
- output.clear();
+ if written > 0 {
+ on_bytes(ctx, output.as_ptr(), written);
}
match result {
EncoderResult::InputEmpty => return true,
- EncoderResult::OutputFull => return false,
+ EncoderResult::OutputFull => {}
EncoderResult::Unmappable(unmappable) => {
on_error(ctx, unmappable as u32);
}
diff --git a/Tests/LibTextCodec/TestTextEncoders.cpp b/Tests/LibTextCodec/TestTextEncoders.cpp
index 27a67e10f98..a210d51bfba 100644
--- a/Tests/LibTextCodec/TestTextEncoders.cpp
+++ b/Tests/LibTextCodec/TestTextEncoders.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/StringBuilder.h>
#include <LibTest/TestCase.h>
#include <LibTextCodec/Encoder.h>
@@ -186,3 +187,22 @@ TEST_CASE(test_x_user_defined_encoder)
EXPECT_EQ(processed_bytes, (Vector<u8> { 0x61, 0x80, 0xFF }));
EXPECT_EQ(unmappable_code_points, (Vector<u32> { 0x100 }));
}
+
+TEST_CASE(test_encoder_output_larger_than_buffer)
+{
+ auto& encoder = TextCodec::encoder_for_exact_name("windows-1252"sv).value();
+ StringBuilder builder;
+ builder.append_repeated('a', 10000);
+ builder.append("\u0100"sv);
+ builder.append_repeated('b', 10000);
+ auto test_string = builder.to_byte_string();
+
+ StringBuilder processed_bytes;
+ Vector<u32> unmappable_code_points;
+ MUST(encoder.process(
+ Utf8View(test_string),
+ [&](u8 byte) { return processed_bytes.try_append(byte); },
+ [&](u32 code_point) { return unmappable_code_points.try_append(code_point); }));
+ EXPECT_EQ(processed_bytes.string_view(), test_string.view().replace("\u0100"sv, ""sv, ReplaceMode::FirstOnly));
+ EXPECT_EQ(unmappable_code_points, (Vector<u32> { 0x100 }));
+}