Skip to content

Truly independent web browser

Everywhere: Carry Latin-1 strings as one byte per code unit

Shannon Booth187af5d8ef0c
diff --git a/AK/Utf16String.cpp b/AK/Utf16String.cpp
index ef266339b85..02e0c27336b 100644
--- a/AK/Utf16String.cpp
+++ b/AK/Utf16String.cpp
@@ -110,22 +110,18 @@ Utf16String Utf16String::from_string_builder(Badge<Utf16StringBuilder>, Utf16Str
return Utf16String { Detail::Utf16StringData::from_string_builder(builder) };
}
-ErrorOr<Utf16String> Utf16String::from_ipc_stream(Stream& stream, size_t length_in_code_units, bool is_ascii)
+ErrorOr<Utf16String> Utf16String::from_ipc_stream(Stream& stream, size_t length_in_code_units, bool has_latin1_storage)
{
- if (is_ascii && length_in_code_units <= Detail::MAX_SHORT_STRING_BYTE_COUNT) {
- Utf16String string;
- string.m_value.short_ascii_string = Detail::ShortString::create_with_byte_count(length_in_code_units);
-
- Bytes bytes { string.m_value.short_ascii_string.storage, length_in_code_units };
+ if (has_latin1_storage && length_in_code_units <= Detail::MAX_SHORT_STRING_BYTE_COUNT) {
+ Array<u8, Detail::MAX_SHORT_STRING_BYTE_COUNT> buffer;
+ auto bytes = buffer.span().trim(length_in_code_units);
TRY(stream.read_until_filled(bytes));
- if (!StringView { bytes }.is_ascii())
- return Error::from_string_literal("Stream contains invalid ASCII data");
-
- return string;
+ // NB: Only ASCII is stored in a short string.
+ return from_utf16(Utf16View::from_latin1(bytes, false));
}
- return Utf16String { TRY(Detail::Utf16StringData::from_ipc_stream(stream, length_in_code_units, is_ascii)) };
+ return Utf16String { TRY(Detail::Utf16StringData::from_ipc_stream(stream, length_in_code_units, has_latin1_storage)) };
}
Utf16String Utf16String::repeated(u32 code_point, size_t count)
diff --git a/AK/Utf16String.h b/AK/Utf16String.h
index 23a3e355c0f..8d5e939d11e 100644
--- a/AK/Utf16String.h
+++ b/AK/Utf16String.h
@@ -285,7 +285,7 @@ public:
ALWAYS_INLINE Utf16String escape_html_entities() const { return utf16_view().escape_html_entities(); }
static Utf16String from_string_builder(Badge<Utf16StringBuilder>, Utf16StringBuilder& builder);
- static ErrorOr<Utf16String> from_ipc_stream(Stream&, size_t length_in_code_units, bool is_ascii);
+ static ErrorOr<Utf16String> from_ipc_stream(Stream&, size_t length_in_code_units, bool has_latin1_storage);
template<typename Callback>
static Utf16String create_uninitialized_ascii(size_t length_in_code_units, Callback callback)
diff --git a/AK/Utf16StringData.cpp b/AK/Utf16StringData.cpp
index bdaa132eca7..e1bdf24951e 100644
--- a/AK/Utf16StringData.cpp
+++ b/AK/Utf16StringData.cpp
@@ -154,18 +154,18 @@ NonnullRefPtr<Utf16StringData> Utf16StringData::from_string_builder(Utf16StringB
return string.release_nonnull();
}
-ErrorOr<NonnullRefPtr<Utf16StringData>> Utf16StringData::from_ipc_stream(Stream& stream, size_t length_in_code_units, bool is_ascii)
+ErrorOr<NonnullRefPtr<Utf16StringData>> Utf16StringData::from_ipc_stream(Stream& stream, size_t length_in_code_units, bool has_latin1_storage)
{
RefPtr<Utf16StringData> string;
- if (is_ascii) {
+ if (has_latin1_storage) {
string = create_uninitialized(StorageType::Latin1, length_in_code_units);
Bytes bytes { string->latin1_data(), length_in_code_units };
TRY(stream.read_until_filled(bytes));
- if (!string->ascii_view().is_ascii())
- return Error::from_string_literal("Stream contains invalid ASCII data");
+ if (!simdutf::validate_ascii(reinterpret_cast<char const*>(bytes.data()), bytes.size()))
+ string->m_header.flags |= ContainsNonAscii;
} else {
string = create_uninitialized(StorageType::UTF16, length_in_code_units);
diff --git a/AK/Utf16StringData.h b/AK/Utf16StringData.h
index 9dd99ba6fe5..916a0e5d81b 100644
--- a/AK/Utf16StringData.h
+++ b/AK/Utf16StringData.h
@@ -81,7 +81,7 @@ public:
static NonnullRefPtr<Utf16StringData> from_ascii(ReadonlyBytes);
static NonnullRefPtr<Utf16StringData> from_utf16(Utf16View const&);
static NonnullRefPtr<Utf16StringData> from_string_builder(Utf16StringBuilder&);
- static ErrorOr<NonnullRefPtr<Utf16StringData>> from_ipc_stream(Stream&, size_t length_in_code_units, bool is_ascii);
+ static ErrorOr<NonnullRefPtr<Utf16StringData>> from_ipc_stream(Stream&, size_t length_in_code_units, bool has_latin1_storage);
// Creates the stable shared header and reserves trailing character storage for an FFI caller
// to initialize before publishing the resulting string.
diff --git a/Libraries/LibIPC/Decoder.cpp b/Libraries/LibIPC/Decoder.cpp
index 99676ce75ae..796859088c0 100644
--- a/Libraries/LibIPC/Decoder.cpp
+++ b/Libraries/LibIPC/Decoder.cpp
@@ -43,10 +43,10 @@ ErrorOr<String> decode(Decoder& decoder)
template<>
ErrorOr<Utf16String> decode(Decoder& decoder)
{
- auto is_ascii = TRY(decoder.decode<bool>());
+ auto has_latin1_storage = TRY(decoder.decode<bool>());
auto length_in_code_units = TRY(decoder.decode_size());
- return Utf16String::from_ipc_stream(decoder.stream(), length_in_code_units, is_ascii);
+ return Utf16String::from_ipc_stream(decoder.stream(), length_in_code_units, has_latin1_storage);
}
template<>
diff --git a/Libraries/LibIPC/Encoder.cpp b/Libraries/LibIPC/Encoder.cpp
index 2dfbdb69a97..1760e5a1fe5 100644
--- a/Libraries/LibIPC/Encoder.cpp
+++ b/Libraries/LibIPC/Encoder.cpp
@@ -73,15 +73,11 @@ ErrorOr<void> encode(Encoder& encoder, Utf16FlyString const& value)
template<>
ErrorOr<void> encode(Encoder& encoder, Utf16View const& value)
{
- TRY(encoder.encode(value.has_ascii_storage()));
+ TRY(encoder.encode(value.has_latin1_storage()));
TRY(encoder.encode_size(value.length_in_code_units()));
- if (value.has_ascii_storage()) {
- TRY(encoder.append(value.ascii_bytes().data(), value.length_in_code_units()));
- } else if (value.has_latin1_storage()) {
- // FIXME: Send Latin-1 as one byte per code unit.
- for (char16_t code_unit : value.latin1_span())
- TRY(encoder.append(reinterpret_cast<u8 const*>(&code_unit), sizeof(code_unit)));
+ if (value.has_latin1_storage()) {
+ TRY(encoder.append(value.latin1_span().data(), value.length_in_code_units()));
} else {
VERIFY(!Checked<size_t>::multiplication_would_overflow(value.length_in_code_units(), sizeof(char16_t)));
TRY(encoder.append(reinterpret_cast<u8 const*>(value.utf16_span().data()), value.length_in_code_units() * sizeof(char16_t)));
diff --git a/Libraries/LibIPC/Rust/src/wire.rs b/Libraries/LibIPC/Rust/src/wire.rs
index 6b35ea19a23..1be79e1512c 100644
--- a/Libraries/LibIPC/Rust/src/wire.rs
+++ b/Libraries/LibIPC/Rust/src/wire.rs
@@ -423,7 +423,7 @@ pub fn validate_utf8(mut bytes: &[u8]) -> Result<(), DecodeError> {
Ok(())
}
-/// `Utf16String`: whether its code units are stored as ASCII bytes, their count, then the code units.
+/// `Utf16String`: whether its code units are stored as Latin-1 bytes, their count, then the code units.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Utf16String(pub Vec<u16>);
@@ -441,10 +441,10 @@ impl Utf16String {
impl Encode for Utf16String {
fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
- let is_ascii = self.0.iter().all(|&code_unit| code_unit < 0x80);
- is_ascii.encode(encoder)?;
+ let is_latin1 = self.0.iter().all(|&code_unit| code_unit <= 0xFF);
+ is_latin1.encode(encoder)?;
encoder.encode_size(self.0.len())?;
- if is_ascii {
+ if is_latin1 {
encoder.bytes.reserve(self.0.len());
encoder.bytes.extend(self.0.iter().map(|&code_unit| code_unit as u8));
} else {
@@ -458,13 +458,10 @@ impl Decode for Utf16String {
const MIN_ENCODED_SIZE: usize = 5;
fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
- let is_ascii = decoder.decode::<bool>()?;
+ let is_latin1 = decoder.decode::<bool>()?;
let length = decoder.decode_size()?;
- if is_ascii {
+ if is_latin1 {
let bytes = decoder.read_bytes(length)?;
- if !bytes.is_ascii() {
- return Err(DecodeError::InvalidValue("Utf16String with ASCII storage"));
- }
return Ok(Self(bytes.iter().map(|&byte| u16::from(byte)).collect()));
}
let byte_count = length.checked_mul(2).ok_or(DecodeError::SizeTooLarge(length))?;
@@ -763,20 +760,20 @@ mod tests {
}
#[test]
- fn utf16_strings_go_as_ascii_bytes_when_they_can() {
+ fn utf16_strings_go_as_latin1_bytes_when_they_can() {
let (value, bytes) = round_trip(&Utf16String::from("ab"));
assert_eq!(value.to_string_lossy(), "ab");
assert_eq!(bytes, [1, 2, 0, 0, 0, b'a', b'b']);
- for units in [vec![], vec![0x7f], vec![0x80, 0xd800, 0xffff]] {
+ for units in [vec![], vec![0x7f], vec![0x80, 0xe9, 0xff], vec![0x100, 0xd800, 0xffff]] {
let value = Utf16String(units.clone());
let (decoded, bytes) = round_trip(&value);
assert_eq!(decoded, value);
- let is_ascii = units.iter().all(|&unit| unit < 0x80);
- let mut expected = vec![u8::from(is_ascii)];
+ let is_latin1 = units.iter().all(|&unit| unit <= 0xff);
+ let mut expected = vec![u8::from(is_latin1)];
expected.extend_from_slice(&(units.len() as u32).to_ne_bytes());
for unit in units {
- if is_ascii {
+ if is_latin1 {
expected.push(unit as u8);
} else {
expected.extend_from_slice(&unit.to_ne_bytes());
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
index 284b875910f..9e618e92a4f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
@@ -130,7 +130,12 @@ impl<'a> StructuredSerializeReader<'a> {
pub(crate) fn decode_utf16_string(&self) -> WebIdlResult<Utf16String> {
Ok(match self.decoded(self.decoder.decode_utf16_string())? {
- DecodedString::Ascii(characters) => Utf16String::from_ascii(characters),
+ DecodedString::Latin1(characters) => Utf16String::from_utf16(
+ &characters
+ .iter()
+ .map(|&character| u16::from(character))
+ .collect::<Vec<_>>(),
+ ),
DecodedString::Utf16(code_units) => Utf16String::from_utf16(&code_units),
})
}
diff --git a/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
index 1763bb05b9d..de9e50bee1d 100644
--- a/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
+++ b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
@@ -151,46 +151,37 @@ impl RecordEncoder {
self.data.extend_from_slice(&size.to_ne_bytes());
}
- /// A string, whose ASCII storage the record keeps: an IPC record holds whether the string has it and the length of
+ /// A string, whose Latin-1 storage the record keeps: an IPC record holds whether the string has it and the length of
/// the string, and a storage record holds both in one varint, the length shifted left by one.
pub fn encode_utf16_string(&mut self, string: Utf16StringUnits<'_>) {
- let (has_ascii_storage, length) = match string {
- Utf16StringUnits::Ascii(characters) => (true, characters.len()),
- Utf16StringUnits::Latin1(characters) => (false, characters.len()),
+ let (has_latin1_storage, length) = match string {
+ Utf16StringUnits::Ascii(characters) | Utf16StringUnits::Latin1(characters) => (true, characters.len()),
Utf16StringUnits::Utf16(code_units) => (false, code_units.len()),
};
match self.serialization_type {
SerializationType::Ipc => {
- self.encode_bool(has_ascii_storage);
+ self.encode_bool(has_latin1_storage);
self.encode_ipc_size(length);
}
SerializationType::Storage => {
- append_unsigned_leb128(&mut self.data, ((length as u64) << 1) | u64::from(has_ascii_storage));
+ append_unsigned_leb128(&mut self.data, ((length as u64) << 1) | u64::from(has_latin1_storage));
}
}
match string {
- Utf16StringUnits::Ascii(characters) => self.data.extend_from_slice(characters),
- // FIXME: Serialize Latin-1 as one byte per code unit.
- Utf16StringUnits::Latin1(characters) => {
- for &character in characters {
- self.encode_utf16_code_unit(u16::from(character));
- }
+ Utf16StringUnits::Ascii(characters) | Utf16StringUnits::Latin1(characters) => {
+ self.data.extend_from_slice(characters);
}
Utf16StringUnits::Utf16(code_units) => {
for &code_unit in code_units {
- self.encode_utf16_code_unit(code_unit);
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&code_unit.to_ne_bytes()),
+ SerializationType::Storage => self.data.extend_from_slice(&code_unit.to_le_bytes()),
+ }
}
}
}
}
- fn encode_utf16_code_unit(&mut self, code_unit: u16) {
- match self.serialization_type {
- SerializationType::Ipc => self.data.extend_from_slice(&code_unit.to_ne_bytes()),
- SerializationType::Storage => self.data.extend_from_slice(&code_unit.to_le_bytes()),
- }
- }
-
pub fn encode_bytes(&mut self, bytes: &[u8]) {
match self.serialization_type {
SerializationType::Ipc => self.encode_ipc_size(bytes.len()),
@@ -217,10 +208,10 @@ fn storage_size(size: u64) -> Result<usize, DecodeError> {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DecodeError(pub &'static str);
-/// A string that a record holds: the characters of a string with ASCII storage, or the code units of any other.
+/// A string that a record holds: the characters of a string with Latin-1 storage, or the code units of any other.
#[derive(Debug, PartialEq, Eq)]
pub enum DecodedString<'a> {
- Ascii(&'a [u8]),
+ Latin1(&'a [u8]),
Utf16(Vec<u16>),
}
@@ -399,19 +390,15 @@ impl<'a> RecordDecoder<'a> {
}
pub fn decode_utf16_string(&self) -> Result<DecodedString<'a>, DecodeError> {
- let (has_ascii_storage, length) = match self.serialization_type {
+ let (has_latin1_storage, length) = match self.serialization_type {
SerializationType::Ipc => (self.decode_bool()?, self.decode_size()?),
SerializationType::Storage => {
let header = self.decode_u64()?;
(header & 1 != 0, storage_size(header >> 1)?)
}
};
- if has_ascii_storage {
- let characters = self.read_bytes(length)?;
- if !characters.is_ascii() {
- return Err(DecodeError("Invalid ASCII in structured serialization record"));
- }
- return Ok(DecodedString::Ascii(characters));
+ if has_latin1_storage {
+ return Ok(DecodedString::Latin1(self.read_bytes(length)?));
}
let byte_count = length
.checked_mul(2)
@@ -525,11 +512,15 @@ mod tests {
}
#[test]
- fn a_storage_record_holds_an_ascii_string_as_one_byte_per_code_unit() {
+ fn a_storage_record_holds_a_latin1_string_as_one_byte_per_code_unit() {
assert_eq!(
storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Ascii(b"AB"))),
[0x05, b'A', b'B']
);
+ assert_eq!(
+ storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Latin1(&[b'A', 0xe9]))),
+ [0x05, b'A', 0xe9]
+ );
assert_eq!(
storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Ascii(b""))),
[0x01]
@@ -669,13 +660,13 @@ mod tests {
);
assert_eq!(
decoder.decode_utf16_string(),
- Ok(DecodedString::Ascii(b"stored string"))
+ Ok(DecodedString::Latin1(b"stored string"))
);
assert_eq!(
decoder.decode_utf16_string(),
Ok(DecodedString::Utf16(vec![0x68, 0xe9, 0xd83e, 0xdeac]))
);
- assert_eq!(decoder.decode_utf16_string(), Ok(DecodedString::Ascii(b"")));
+ assert_eq!(decoder.decode_utf16_string(), Ok(DecodedString::Latin1(b"")));
assert_eq!(decoder.decode_bytes(), Ok(&[0xde, 0xad, 0xbe, 0xef][..]));
assert_eq!(decoder.decode_big_int(), Ok((true, &[0x01, 0x00][..])));
},
@@ -749,9 +740,12 @@ mod tests {
#[test]
fn a_string_holds_the_characters_its_header_claims() {
- // ASCII storage that holds a byte that is not ASCII.
+ // Latin-1 storage that holds a byte that is not ASCII.
let record = storage_record(&[0x03, 0xe9]);
- assert!(storage_decoder(&record).decode_utf16_string().is_err());
+ assert_eq!(
+ storage_decoder(&record).decode_utf16_string(),
+ Ok(DecodedString::Latin1(&[0xe9]))
+ );
// Fewer bytes than the length claims.
let record = storage_record(&[0x07, b'a', b'b']);
@@ -765,13 +759,13 @@ mod tests {
let record = storage_record(&[0x85, 0x00, b'a', b'b']);
assert_eq!(
storage_decoder(&record).decode_utf16_string(),
- Ok(DecodedString::Ascii(b"ab"))
+ Ok(DecodedString::Latin1(b"ab"))
);
// A string ends at its length, not at the end of the record.
let record = storage_record(&[0x03, b'a', b'b']);
let decoder = storage_decoder(&record);
- assert_eq!(decoder.decode_utf16_string(), Ok(DecodedString::Ascii(b"a")));
+ assert_eq!(decoder.decode_utf16_string(), Ok(DecodedString::Latin1(b"a")));
assert!(!decoder.is_at_end());
}
diff --git a/Tests/AK/TestUtf16String.cpp b/Tests/AK/TestUtf16String.cpp
index fc74e9cc367..0fcee1e567b 100644
--- a/Tests/AK/TestUtf16String.cpp
+++ b/Tests/AK/TestUtf16String.cpp
@@ -482,22 +482,15 @@ TEST_CASE(from_ipc_stream)
EXPECT(result.is_error());
}
{
- auto data = u"😀"sv;
+ // One-byte storage is Latin-1, so each byte is the code unit of its value.
+ static constexpr u8 data[] = { 'c', 'r', 0xE8, 'm', 'e', ' ', 'b', 'r', 0xFB, 'l', 0xE9, 'e' };
+ FixedMemoryStream stream { ReadonlyBytes { data } };
- auto buffer = MUST(ByteBuffer::copy({ reinterpret_cast<u8 const*>(data.utf16_span().data()), data.length_in_code_units() * sizeof(char16_t) }));
- FixedMemoryStream stream { buffer.bytes() };
-
- auto result = Utf16String::from_ipc_stream(stream, data.length_in_code_units(), true);
- EXPECT(result.is_error());
- }
- {
- auto data = u"hello 😀 there!"sv;
-
- auto buffer = MUST(ByteBuffer::copy({ reinterpret_cast<u8 const*>(data.utf16_span().data()), data.length_in_code_units() * sizeof(char16_t) }));
- FixedMemoryStream stream { buffer.bytes() };
-
- auto result = Utf16String::from_ipc_stream(stream, data.length_in_code_units(), true);
- EXPECT(result.is_error());
+ auto string = TRY_OR_FAIL(Utf16String::from_ipc_stream(stream, sizeof(data), true));
+ EXPECT(!string.is_ascii());
+ EXPECT(!string.has_long_ascii_storage());
+ EXPECT(string.utf16_view().has_latin1_storage());
+ EXPECT_EQ(string, u"crème brûlée"sv);
}
}
diff --git a/Tests/LibIPC/TestDecoder.cpp b/Tests/LibIPC/TestDecoder.cpp
index 6d6dc518096..4d0df727736 100644
--- a/Tests/LibIPC/TestDecoder.cpp
+++ b/Tests/LibIPC/TestDecoder.cpp
@@ -10,6 +10,7 @@
#include <AK/Optional.h>
#include <AK/Queue.h>
#include <AK/String.h>
+#include <AK/Utf16String.h>
#include <AK/Vector.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibCore/System.h>
@@ -166,3 +167,28 @@ TEST_CASE(sizes_are_bounded_before_contents_and_only_within_the_value)
EXPECT(!MUST(decoder.decode_with_max_size<Optional<String>>(4)).has_value());
EXPECT_EQ(MUST(decoder.decode<String>()), "123456789"sv);
}
+
+TEST_CASE(decode_utf16_string_with_latin1_storage)
+{
+ auto latin1_string = [](ReadonlyBytes code_units) {
+ Vector<u8> bytes;
+ bytes.append(1);
+ bytes.extend(bytes_with_size_prefix(code_units.size(), code_units));
+ return MUST(decode_bytes<Utf16String>(bytes));
+ };
+
+ // "café crème", with each code unit as one byte.
+ static constexpr u8 long_code_units[] = { 'c', 'a', 'f', 0xE9, ' ', 'c', 'r', 0xE8, 'm', 'e' };
+ auto string = latin1_string(long_code_units);
+ EXPECT_EQ(string, Utf16String::from_utf8("café crème"sv));
+ EXPECT(string.utf16_view().has_latin1_storage());
+ EXPECT(!string.has_ascii_storage());
+
+ static constexpr u8 short_code_units[] = { 0xE9 };
+ auto short_string = latin1_string(short_code_units);
+ EXPECT_EQ(short_string, Utf16String::from_utf8("é"sv));
+ EXPECT(!short_string.has_short_ascii_storage());
+
+ static constexpr u8 ascii_code_units[] = { 'c', 'a', 'f', 'e' };
+ EXPECT(latin1_string(ascii_code_units).has_short_ascii_storage());
+}
diff --git a/Tests/LibIPC/TestRustEchoServer.cpp b/Tests/LibIPC/TestRustEchoServer.cpp
index 96107db454f..5be9ac5fc21 100644
--- a/Tests/LibIPC/TestRustEchoServer.cpp
+++ b/Tests/LibIPC/TestRustEchoServer.cpp
@@ -87,6 +87,19 @@ TEST_CASE(values_make_a_round_trip_through_rust)
EXPECT_EQ(response->bytes(), bytes);
}
+TEST_CASE(latin1_strings_make_a_round_trip_through_rust)
+{
+ auto transport = start_server();
+ // "crème brûlée", with each code unit as one byte.
+ static constexpr u8 code_units[] = { 'c', 'r', 0xE8, 'm', 'e', ' ', 'b', 'r', 0xFB, 'l', 0xE9, 'e' };
+ auto latin1_text = Utf16String::from_utf16(Utf16View::from_latin1(code_units, false));
+ send(*transport, Messages::RustEchoServer::Echo::static_encode(1, ""sv, latin1_text.utf16_view(), {}, {}));
+
+ auto response = receive<Messages::RustEchoServer::EchoResponse>(*transport);
+ EXPECT_EQ(response->utf16_text(), latin1_text);
+ EXPECT(response->utf16_text().utf16_view().has_latin1_storage());
+}
+
TEST_CASE(strings_with_lone_surrogates_make_a_round_trip_through_rust)
{
auto transport = start_server();
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index 12f93b5b471..f0864c7cdaf 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -96,9 +96,9 @@ inline void append_storage_record_header(Vector<u8>& bytes)
}
// The folded string header: (length << 1) | is_ascii, matching the production encoder.
-inline void append_storage_string_header(Vector<u8>& bytes, bool is_ascii, size_t length)
+inline void append_storage_string_header(Vector<u8>& bytes, bool is_latin1, size_t length)
{
- append_storage_leb128(bytes, (static_cast<u64>(length) << 1) | (is_ascii ? 1u : 0u));
+ append_storage_leb128(bytes, (static_cast<u64>(length) << 1) | (is_latin1 ? 1u : 0u));
}
inline void append_storage_ascii_utf16(Vector<u8>& bytes, StringView ascii)
diff --git a/Tests/LibWeb/TestStructuredSerializeHardening.cpp b/Tests/LibWeb/TestStructuredSerializeHardening.cpp
index ae5b81ac3df..f0f9dd4dae1 100644
--- a/Tests/LibWeb/TestStructuredSerializeHardening.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeHardening.cpp
@@ -266,12 +266,14 @@ TEST_CASE(storage_reader_rejects_trailing_bytes)
EXPECT(!storage_deserialize(storage_record_with_value(clean)).is_error());
}
-TEST_CASE(storage_reader_rejects_ascii_flagged_string_with_non_ascii_bytes)
+TEST_CASE(storage_reader_decodes_latin1_flagged_string_with_non_ascii_bytes)
{
Vector<u8> value { to_underlying(ValueTag::StringPrimitive) };
- append_storage_string_header(value, /*is_ascii=*/true, 1);
- value.append(0x80); // not ASCII
- EXPECT(storage_deserialize(storage_record_with_value(value)).is_error());
+ append_storage_string_header(value, /*is_latin1=*/true, 1);
+ value.append(0xE9); // U+00E9
+ auto decoded = MUST(storage_deserialize(storage_record_with_value(value)));
+ EXPECT(decoded.is_string());
+ expect_utf16_equals(decoded.as_string().utf16_string(), Utf16String::from_utf8("é"sv));
}
TEST_CASE(storage_reader_decodes_ascii_content_flagged_as_utf16)
@@ -303,18 +305,18 @@ TEST_CASE(storage_reader_rejects_a_string_with_fewer_bytes_than_its_length_claim
return storage_record_with_value(value);
};
- // ASCII: one byte per code unit, so two code units need two bytes — only one is present.
+ // Latin-1: one byte per code unit, so two code units need two bytes — only one is present.
{
Vector<u8> body;
- append_storage_string_header(body, /*is_ascii=*/true, 2);
+ append_storage_string_header(body, /*is_latin1=*/true, 2);
body.append('h'); // one byte, not two
EXPECT(storage_deserialize(string_record(body)).is_error());
}
- // Non-ASCII: two bytes per code unit, so two code units need four bytes — only two are present.
+ // UTF-16: two bytes per code unit, so two code units need four bytes — only two are present.
{
Vector<u8> body;
- append_storage_string_header(body, /*is_ascii=*/false, 2);
+ append_storage_string_header(body, /*is_latin1=*/false, 2);
append_little_endian_u16(body, u'h'); // one code unit (two bytes), not two
EXPECT(storage_deserialize(string_record(body)).is_error());
}