Skip to content

Truly independent web browser

Everywhere: Store text up to U+00FF as Latin-1 in Utf16String

Shannon Booth02e5f759464f
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index 81498d122b1..0850a280c9d 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -55,6 +55,20 @@ pub enum Utf16StringUnits<'a> {
Utf16(&'a [u16]),
}
+/// The storage of a long string: one byte per code unit, all of them ASCII or not, or two bytes per code unit.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum StorageKind {
+ Ascii,
+ Latin1,
+ Utf16,
+}
+
+impl StorageKind {
+ fn one_byte(is_ascii: bool) -> Self {
+ if is_ascii { Self::Ascii } else { Self::Latin1 }
+ }
+}
+
unsafe extern "C" {
fn ladybird_utf16_string_create_uninitialized(length: usize, has_latin1_storage: bool) -> usize;
fn ladybird_utf16_fly_string_from_utf8(data: *const u8, length: usize) -> usize;
@@ -274,10 +288,12 @@ impl Utf16String {
unsafe { Self::from_raw_owned(raw) }
}
- /// Creates a string in AK's native representation and initializes its storage from UTF-16.
+ /// Creates a string in AK's native representation and initializes its storage from UTF-16, with one byte per
+ /// code unit if none is above U+00FF.
pub fn from_utf16(string: &[u16]) -> Self {
- if string.iter().all(|code_unit| *code_unit <= 0x7f) {
- if string.len() < size_of::<usize>() {
+ let is_ascii = string.iter().all(|code_unit| *code_unit <= 0x7f);
+ if is_ascii || string.iter().all(|code_unit| *code_unit <= 0xff) {
+ if is_ascii && string.len() < size_of::<usize>() {
let mut bytes = [0; size_of::<usize>() - 1];
for (index, code_unit) in string.iter().enumerate() {
bytes[index] = *code_unit as u8;
@@ -285,16 +301,16 @@ impl Utf16String {
return Self::from_short_ascii(&bytes[..string.len()]);
}
- let result = Self::create_uninitialized(string.len(), true);
+ let result = Self::create_uninitialized(string.len(), StorageKind::one_byte(is_ascii));
let storage = result.long_storage();
for (index, code_unit) in string.iter().enumerate() {
- // SAFETY: The allocation has space for exactly `string.len()` ASCII bytes.
+ // SAFETY: The allocation has space for exactly `string.len()` Latin-1 bytes.
unsafe { storage.add(index).write(*code_unit as u8) };
}
return result;
}
- let result = Self::create_uninitialized(string.len(), false);
+ let result = Self::create_uninitialized(string.len(), StorageKind::Utf16);
// SAFETY: The source and destination are non-overlapping and the allocation has space for
// exactly `string.len()` UTF-16 code units.
unsafe { std::ptr::copy_nonoverlapping(string.as_ptr(), result.long_storage().cast(), string.len()) };
@@ -308,10 +324,28 @@ impl Utf16String {
Self::from_ascii_without_validation(string)
}
- /// Creates a string in AK's native representation from the ASCII bytes of `pieces` one after the other, which
- /// add up to `length` bytes, copying each piece into the string's storage directly.
- pub fn from_ascii_concatenation<'a>(length: usize, pieces: impl IntoIterator<Item = &'a [u8]>) -> Self {
- if length < size_of::<usize>() {
+ /// Creates a string in AK's native representation from Latin-1 bytes, one per code unit.
+ pub fn from_latin1(string: &[u8]) -> Self {
+ if string.is_ascii() {
+ return Self::from_ascii_without_validation(string);
+ }
+
+ let result = Self::create_uninitialized(string.len(), StorageKind::Latin1);
+ // SAFETY: The source and destination are non-overlapping and the allocation has space for
+ // exactly `string.len()` Latin-1 bytes.
+ unsafe { std::ptr::copy_nonoverlapping(string.as_ptr(), result.long_storage(), string.len()) };
+ result
+ }
+
+ /// Creates a string in AK's native representation from the Latin-1 bytes of `pieces` one after the other, which
+ /// add up to `length` bytes, copying each piece into the string's storage directly. `is_ascii` tells whether
+ /// every byte is ASCII.
+ pub fn from_latin1_concatenation<'a>(
+ length: usize,
+ is_ascii: bool,
+ pieces: impl IntoIterator<Item = &'a [u8]>,
+ ) -> Self {
+ if is_ascii && length < size_of::<usize>() {
let mut bytes = [0; size_of::<usize>() - 1];
let mut byte_count = 0;
for piece in pieces {
@@ -322,7 +356,7 @@ impl Utf16String {
return Self::from_ascii(&bytes[..length]);
}
- let result = Self::create_uninitialized(length, true);
+ let result = Self::create_uninitialized(length, StorageKind::one_byte(is_ascii));
let storage = result.long_storage();
let mut byte_count = 0;
for piece in pieces {
@@ -330,13 +364,15 @@ impl Utf16String {
piece.len() <= length - byte_count,
"the pieces add up to the length of the string"
);
- assert!(piece.is_ascii(), "an ASCII string holds ASCII bytes");
- // SAFETY: The allocation has space for `length` ASCII bytes, of which `byte_count` are written, and the
+ // SAFETY: The allocation has space for `length` Latin-1 bytes, of which `byte_count` are written, and the
// piece fits in the rest.
unsafe { std::ptr::copy_nonoverlapping(piece.as_ptr(), storage.add(byte_count), piece.len()) };
byte_count += piece.len();
}
assert_eq!(byte_count, length, "the pieces add up to the length of the string");
+ // SAFETY: Every byte of the allocation is written.
+ let bytes = unsafe { crate::slice_from_raw_parts(storage.cast_const(), length) };
+ assert_eq!(bytes.is_ascii(), is_ascii, "an ASCII string holds ASCII bytes");
result
}
@@ -349,7 +385,7 @@ impl Utf16String {
return Self::from_ascii(&bytes[..length]);
}
- let result = Self::create_uninitialized(length, true);
+ let result = Self::create_uninitialized(length, StorageKind::Ascii);
// SAFETY: The allocation has space for exactly `length` ASCII bytes, which are zeroed before they are lent out.
let storage = unsafe {
std::ptr::write_bytes(result.long_storage(), 0, length);
@@ -366,7 +402,7 @@ impl Utf16String {
return Self::from_short_ascii(string);
}
- let result = Self::create_uninitialized(string.len(), true);
+ let result = Self::create_uninitialized(string.len(), StorageKind::Ascii);
// SAFETY: The source and destination are non-overlapping and the allocation has space for
// exactly `string.len()` ASCII bytes.
unsafe { std::ptr::copy_nonoverlapping(string.as_ptr(), result.long_storage(), string.len()) };
@@ -392,8 +428,9 @@ impl Utf16String {
unsafe { Self::from_raw_owned(usize::from_ne_bytes(bytes)) }
}
- fn create_uninitialized(length: usize, has_latin1_storage: bool) -> Self {
+ fn create_uninitialized(length: usize, kind: StorageKind) -> Self {
assert!(length < UNKNOWN_CODE_POINT_LENGTH as usize);
+ let has_latin1_storage = kind != StorageKind::Utf16;
let unit_size = if has_latin1_storage { 1 } else { size_of::<u16>() };
assert!(
size_of::<Utf16StringDataHeader>()
@@ -407,6 +444,11 @@ impl Utf16String {
// SAFETY: C++ returns a fully initialized native string owner with trailing storage sized
// for `length` units. The caller initializes that storage before publishing the owner.
let raw = unsafe { ladybird_utf16_string_create_uninitialized(length, has_latin1_storage) };
+ if kind == StorageKind::Latin1 {
+ // SAFETY: The new string is the address of its data, which starts with this header and is not shared yet.
+ let header = unsafe { &*std::ptr::with_exposed_provenance::<Utf16StringDataHeader>(raw) };
+ header.flags.fetch_or(CONTAINS_NON_ASCII, Ordering::Relaxed);
+ }
// SAFETY: The allocator transfers one ownership reference.
unsafe { Self::from_raw_owned(raw) }
}
diff --git a/AK/StringBuilder.cpp b/AK/StringBuilder.cpp
index ddc16bb119e..abbb0782bdf 100644
--- a/AK/StringBuilder.cpp
+++ b/AK/StringBuilder.cpp
@@ -375,6 +375,9 @@ ErrorOr<void> StringBuilder::try_append_repeated(Utf16View const& string, size_t
if (string.has_ascii_storage()) {
TRY(will_append(string.length_in_code_units() * n));
+ } else if (string.has_latin1_storage()) {
+ auto utf8_length = simdutf::utf8_length_from_latin1(reinterpret_cast<char const*>(string.latin1_span().data()), string.length_in_code_units());
+ TRY(will_append(utf8_length * n));
} else {
auto utf8_length = simdutf::utf8_length_from_utf16(string.utf16_span().data(), string.length_in_code_units());
TRY(will_append(utf8_length * n));
diff --git a/AK/Utf16FlyString.h b/AK/Utf16FlyString.h
index 1f7bc10fbd8..1268e62109a 100644
--- a/AK/Utf16FlyString.h
+++ b/AK/Utf16FlyString.h
@@ -109,8 +109,8 @@ public:
{
auto view = m_data.utf16_view();
- if (view.has_ascii_storage()) {
- if (!any_of(view.ascii_span(), is_ascii_upper_alpha))
+ if (view.has_latin1_storage()) {
+ if (!any_of(view.latin1_span(), is_ascii_upper_alpha))
return *this;
} else {
if (!any_of(view.utf16_span(), is_ascii_upper_alpha))
@@ -124,8 +124,8 @@ public:
{
auto view = m_data.utf16_view();
- if (view.has_ascii_storage()) {
- if (!any_of(view.ascii_span(), is_ascii_lower_alpha))
+ if (view.has_latin1_storage()) {
+ if (!any_of(view.latin1_span(), is_ascii_lower_alpha))
return *this;
} else {
if (!any_of(view.utf16_span(), is_ascii_lower_alpha))
diff --git a/AK/Utf16String.cpp b/AK/Utf16String.cpp
index 02e0c27336b..8d5e1447207 100644
--- a/AK/Utf16String.cpp
+++ b/AK/Utf16String.cpp
@@ -70,7 +70,7 @@ Utf16String Utf16String::from_utf8_without_validation(StringView utf8_string)
return string;
}
- return Utf16String { Detail::Utf16StringData::from_utf8(utf8_string, Detail::Utf16StringData::AllowASCIIStorage::Yes) };
+ return Utf16String { Detail::Utf16StringData::from_utf8(utf8_string) };
}
Utf16String Utf16String::from_utf16(Utf16View const& utf16_string)
@@ -97,7 +97,7 @@ Utf16String Utf16String::from_string_builder(Badge<Utf16StringBuilder>, Utf16Str
{
auto view = builder.view();
- if (view.length_in_code_units() <= Detail::MAX_SHORT_STRING_BYTE_COUNT && view.has_ascii_storage()) {
+ if (view.length_in_code_units() <= Detail::MAX_SHORT_STRING_BYTE_COUNT && view.has_latin1_storage() && view.is_ascii()) {
Utf16String string;
string.m_value.short_ascii_string = Detail::ShortString::create_with_byte_count(view.length_in_code_units());
diff --git a/AK/Utf16String.h b/AK/Utf16String.h
index 8d5e939d11e..11896953a36 100644
--- a/AK/Utf16String.h
+++ b/AK/Utf16String.h
@@ -210,8 +210,8 @@ public:
{
auto view = utf16_view();
- if (view.has_ascii_storage()) {
- if (!any_of(view.ascii_span(), is_ascii_upper_alpha))
+ if (view.has_latin1_storage()) {
+ if (!any_of(view.latin1_span(), is_ascii_upper_alpha))
return *this;
} else {
if (!any_of(view.utf16_span(), is_ascii_upper_alpha))
@@ -225,8 +225,8 @@ public:
{
auto view = utf16_view();
- if (view.has_ascii_storage()) {
- if (!any_of(view.ascii_span(), is_ascii_lower_alpha))
+ if (view.has_latin1_storage()) {
+ if (!any_of(view.latin1_span(), is_ascii_lower_alpha))
return *this;
} else {
if (!any_of(view.utf16_span(), is_ascii_lower_alpha))
diff --git a/AK/Utf16StringBuilder.cpp b/AK/Utf16StringBuilder.cpp
index 491c0d3f87d..3adbdbb9fd0 100644
--- a/AK/Utf16StringBuilder.cpp
+++ b/AK/Utf16StringBuilder.cpp
@@ -12,6 +12,8 @@
#include <AK/Utf16StringData.h>
#include <AK/kmalloc.h>
+#include <simdutf.h>
+
namespace AK {
Utf16StringBuilder::Buffer::~Buffer()
@@ -200,20 +202,20 @@ void Utf16StringBuilder::will_append(size_t size_in_bytes)
void Utf16StringBuilder::ensure_storage_is_utf16()
{
- if (!m_is_ascii)
+ if (!m_has_latin1_storage)
return;
- auto ascii_length = length_in_bytes();
- m_is_ascii = false;
- if (ascii_length == 0)
+ auto latin1_length = length_in_bytes();
+ m_has_latin1_storage = false;
+ if (latin1_length == 0)
return;
- m_buffer.resize(m_buffer.size() + ascii_length);
+ m_buffer.resize(m_buffer.size() + latin1_length);
- Bytes source { data(), ascii_length };
- Span<char16_t> target { reinterpret_cast<char16_t*>(data()), ascii_length };
+ Bytes source { data(), latin1_length };
+ Span<char16_t> target { reinterpret_cast<char16_t*>(data()), latin1_length };
- for (size_t i = ascii_length; i > 0; --i) {
+ for (size_t i = latin1_length; i > 0; --i) {
auto index = i - 1;
auto code_unit = static_cast<char16_t>(source[index]);
@@ -226,21 +228,17 @@ void Utf16StringBuilder::append(Utf16View const& view)
if (view.is_empty())
return;
- if (m_is_ascii && (view.has_ascii_storage() || view.is_ascii())) {
+ if (m_has_latin1_storage && view.has_latin1_storage()) {
will_append(view.length_in_code_units());
-
- if (view.has_latin1_storage()) {
- m_buffer.append(view.latin1_span().data(), view.length_in_code_units());
- } else {
- for (auto code_unit : view.utf16_span()) {
- auto ascii_code_unit = static_cast<char>(code_unit);
- m_buffer.append(&ascii_code_unit, sizeof(ascii_code_unit));
- }
- }
-
+ m_buffer.append(view.latin1_span().data(), view.length_in_code_units());
+ if (!view.has_ascii_storage())
+ m_contains_non_ascii = true;
return;
}
+ if (m_has_latin1_storage && try_append_as_latin1(view.utf16_span()))
+ return;
+
ensure_storage_is_utf16();
will_append(utf16_byte_count(view.length_in_code_units()));
@@ -254,11 +252,29 @@ void Utf16StringBuilder::append(Utf16View const& view)
}
}
+bool Utf16StringBuilder::try_append_as_latin1(ReadonlySpan<char16_t> code_units)
+{
+ will_append(code_units.size());
+
+ auto original_size = m_buffer.size();
+ m_buffer.resize(original_size + code_units.size());
+
+ auto* destination = reinterpret_cast<char*>(m_buffer.data() + original_size);
+ if (simdutf::convert_utf16_to_latin1(code_units.data(), code_units.size(), destination) != code_units.size()) {
+ m_buffer.resize(original_size);
+ return false;
+ }
+
+ if (!m_contains_non_ascii && !simdutf::validate_ascii(destination, code_units.size()))
+ m_contains_non_ascii = true;
+ return true;
+}
+
void Utf16StringBuilder::append_ascii(char code_unit)
{
VERIFY(is_ascii(code_unit));
- if (m_is_ascii) {
+ if (m_has_latin1_storage) {
will_append(1);
m_buffer.append(&code_unit, sizeof(code_unit));
} else {
@@ -279,7 +295,7 @@ void Utf16StringBuilder::append_ascii_without_validation(ReadonlyBytes string)
if (string.is_empty())
return;
- if (m_is_ascii) {
+ if (m_has_latin1_storage) {
will_append(string.size());
m_buffer.append(string.data(), string.size());
return;
@@ -309,7 +325,7 @@ void Utf16StringBuilder::append_quoted_escaped_for_json(Utf16View const& string)
}
}
- if (!needs_escaping && m_is_ascii) {
+ if (!needs_escaping && m_has_latin1_storage) {
Checked<size_t> appended_size = bytes.size();
appended_size += 2;
VERIFY(!appended_size.has_overflow());
@@ -361,8 +377,12 @@ void Utf16StringBuilder::append_quoted_escaped_for_json(Utf16View const& string)
void Utf16StringBuilder::append_code_unit(char16_t code_unit)
{
- if (m_is_ascii && is_ascii(code_unit)) {
- append_ascii(static_cast<char>(code_unit));
+ if (m_has_latin1_storage && code_unit <= 0xFF) {
+ auto latin1_code_unit = static_cast<u8>(code_unit);
+ will_append(sizeof(latin1_code_unit));
+ m_buffer.append(&latin1_code_unit, sizeof(latin1_code_unit));
+ if (!is_ascii(code_unit))
+ m_contains_non_ascii = true;
return;
}
@@ -378,8 +398,8 @@ void Utf16StringBuilder::append_code_point(u32 code_point)
return;
}
- if (m_is_ascii && is_ascii(code_point)) {
- append_ascii(static_cast<char>(code_point));
+ if (m_has_latin1_storage && code_point <= 0xFF) {
+ append_code_unit(static_cast<char16_t>(code_point));
return;
}
@@ -395,7 +415,7 @@ void Utf16StringBuilder::append_repeated_ascii(char code_unit, size_t count)
{
VERIFY(is_ascii(code_unit));
- if (m_is_ascii) {
+ if (m_has_latin1_storage) {
will_append(count);
for (size_t i = 0; i < count; ++i)
m_buffer.append(&code_unit, sizeof(code_unit));
@@ -491,15 +511,15 @@ Utf16View Utf16StringBuilder::view() const
{
auto data = m_buffer.span().slice(string_builder_prefix_size());
- if (m_is_ascii)
- return { reinterpret_cast<char const*>(data.data()), data.size(), true };
+ if (m_has_latin1_storage)
+ return Utf16View::from_latin1(data, !m_contains_non_ascii);
return { reinterpret_cast<char16_t const*>(data.data()), data.size() / sizeof(char16_t) };
}
size_t Utf16StringBuilder::length_in_code_units() const
{
auto length = length_in_bytes();
- if (m_is_ascii)
+ if (m_has_latin1_storage)
return length;
return length / sizeof(char16_t);
}
@@ -507,7 +527,7 @@ size_t Utf16StringBuilder::length_in_code_units() const
void Utf16StringBuilder::trim(size_t count_in_code_units)
{
auto count_in_bytes = count_in_code_units;
- if (!m_is_ascii)
+ if (!m_has_latin1_storage)
count_in_bytes = utf16_byte_count(count_in_code_units);
auto decrease_count = min(length_in_bytes(), count_in_bytes);
@@ -517,7 +537,8 @@ void Utf16StringBuilder::trim(size_t count_in_code_units)
void Utf16StringBuilder::clear()
{
m_buffer.resize(string_builder_prefix_size());
- m_is_ascii = true;
+ m_has_latin1_storage = true;
+ m_contains_non_ascii = false;
}
auto Utf16StringBuilder::leak_buffer_for_string_construction() -> Optional<Buffer::OutlineBuffer>
diff --git a/AK/Utf16StringBuilder.h b/AK/Utf16StringBuilder.h
index 181ec2ec06e..be7a886c5b8 100644
--- a/AK/Utf16StringBuilder.h
+++ b/AK/Utf16StringBuilder.h
@@ -128,6 +128,7 @@ private:
void initialize_buffer(size_t capacity_in_code_units);
void will_append(size_t size_in_bytes);
void ensure_storage_is_utf16();
+ bool try_append_as_latin1(ReadonlySpan<char16_t>);
Optional<Buffer::OutlineBuffer> leak_buffer_for_string_construction();
@@ -136,7 +137,9 @@ private:
[[nodiscard]] size_t length_in_bytes() const;
Buffer m_buffer;
- bool m_is_ascii { true };
+ bool m_has_latin1_storage { true };
+ // Set once a byte above 0x7F is appended, even if trimming removes it later.
+ bool m_contains_non_ascii { false };
};
}
diff --git a/AK/Utf16StringData.cpp b/AK/Utf16StringData.cpp
index e1bdf24951e..be398a8fc17 100644
--- a/AK/Utf16StringData.cpp
+++ b/AK/Utf16StringData.cpp
@@ -72,16 +72,48 @@ NonnullRefPtr<Utf16StringData> Utf16StringData::create_uninitialized_ascii(size_
return string;
}
-NonnullRefPtr<Utf16StringData> Utf16StringData::from_utf8(StringView utf8_string, AllowASCIIStorage allow_ascii_storage)
+// Valid UTF-8 encodes nothing above U+00FF if no lead byte is above 0xC3, and then each 0xC2 or 0xC3 lead byte and its
+// continuation byte are one code unit.
+static Optional<size_t> latin1_length_of_valid_utf8(ReadonlyBytes utf8_string)
+{
+ size_t two_byte_sequences = 0;
+ for (auto byte : utf8_string) {
+ if (byte > 0xC3)
+ return {};
+ two_byte_sequences += byte >= 0xC2;
+ }
+ return utf8_string.size() - two_byte_sequences;
+}
+
+static bool fits_in_latin1(ReadonlySpan<char16_t> utf16_string)
+{
+ char16_t combined = 0;
+ for (auto code_unit : utf16_string)
+ combined |= code_unit;
+ return combined <= 0xFF;
+}
+
+NonnullRefPtr<Utf16StringData> Utf16StringData::from_utf8(StringView utf8_string)
{
RefPtr<Utf16StringData> string;
- if (allow_ascii_storage == AllowASCIIStorage::Yes && utf8_string.is_ascii()) {
+ if (utf8_string.is_ascii()) {
VERIFY_UTF16_LENGTH(utf8_string.length());
string = create_uninitialized(StorageType::Latin1, utf8_string.length());
TypedTransfer<u8>::copy(string->latin1_data(), utf8_string.bytes().data(), utf8_string.length());
} else if (Utf8View view { utf8_string }; view.validate(AllowLonelySurrogates::No)) {
+ if (auto latin1_length = latin1_length_of_valid_utf8(utf8_string.bytes()); latin1_length.has_value()) {
+ VERIFY_UTF16_LENGTH(*latin1_length);
+
+ string = create_uninitialized(StorageType::Latin1, *latin1_length);
+ string->m_header.flags |= ContainsNonAscii;
+
+ auto result = simdutf::convert_valid_utf8_to_latin1(utf8_string.characters_without_null_termination(), utf8_string.length(), reinterpret_cast<char*>(string->latin1_data()));
+ VERIFY(result == *latin1_length);
+ return string.release_nonnull();
+ }
+
auto code_unit_length = simdutf::utf16_length_from_utf8(utf8_string.characters_without_null_termination(), utf8_string.length());
VERIFY_UTF16_LENGTH(code_unit_length);
@@ -106,11 +138,14 @@ NonnullRefPtr<Utf16StringData> Utf16StringData::from_utf16(Utf16View const& utf1
TypedTransfer<u8>::copy(string->latin1_data(), utf16_string.latin1_span().data(), utf16_string.length_in_code_units());
if (!utf16_string.is_ascii())
string->m_header.flags |= ContainsNonAscii;
- } else if (utf16_string.is_ascii()) {
+ } else if (fits_in_latin1(utf16_string.utf16_span())) {
string = create_uninitialized(StorageType::Latin1, utf16_string.length_in_code_units());
- auto result = simdutf::convert_utf16_to_utf8(utf16_string.utf16_span().data(), utf16_string.length_in_code_units(), reinterpret_cast<char*>(string->latin1_data()));
+ auto* latin1_data = reinterpret_cast<char*>(string->latin1_data());
+ auto result = simdutf::convert_valid_utf16_to_latin1(utf16_string.utf16_span().data(), utf16_string.length_in_code_units(), latin1_data);
VERIFY(result == utf16_string.length_in_code_units());
+ if (!simdutf::validate_ascii(latin1_data, result))
+ string->m_header.flags |= ContainsNonAscii;
} else {
string = create_uninitialized(StorageType::UTF16, utf16_string.length_in_code_units());
TypedTransfer<char16_t>::copy(string->utf16_data(), utf16_string.utf16_span().data(), utf16_string.length_in_code_units());
diff --git a/AK/Utf16StringData.h b/AK/Utf16StringData.h
index 916a0e5d81b..76ebd1f759a 100644
--- a/AK/Utf16StringData.h
+++ b/AK/Utf16StringData.h
@@ -59,11 +59,6 @@ public:
UTF16,
};
- enum class AllowASCIIStorage : u8 {
- No,
- Yes,
- };
-
enum Flag : u32 {
HasUtf16Storage = 1 << 0,
HasHash = 1 << 1,
@@ -77,7 +72,7 @@ public:
static_assert(IsFlyString == 4);
static_assert(ContainsNonAscii == 8);
- static NonnullRefPtr<Utf16StringData> from_utf8(StringView, AllowASCIIStorage);
+ static NonnullRefPtr<Utf16StringData> from_utf8(StringView);
static NonnullRefPtr<Utf16StringData> from_ascii(ReadonlyBytes);
static NonnullRefPtr<Utf16StringData> from_utf16(Utf16View const&);
static NonnullRefPtr<Utf16StringData> from_string_builder(Utf16StringBuilder&);
diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rs
index 6952f0d4650..ee7dbe940ec 100644
--- a/Libraries/LibJS/Rust/src/test_host.rs
+++ b/Libraries/LibJS/Rust/src/test_host.rs
@@ -45,9 +45,9 @@ extern "C" fn unicode_code_point_has_identifier_continue_property(code_point: u3
static FLY_STRINGS: Mutex<Option<HashMap<Vec<u16>, usize>>> = Mutex::new(None);
/// Allocates a string with one reference and uninitialized storage, laid out the way AK lays it out.
-fn allocate_uninitialized_string(length: usize, has_ascii_storage: bool) -> usize {
+fn allocate_uninitialized_string(length: usize, has_latin1_storage: bool) -> usize {
let header_size = size_of::<ak::Utf16StringDataHeader>();
- let unit_size = if has_ascii_storage { 1 } else { size_of::<u16>() };
+ let unit_size = if has_latin1_storage { 1 } else { size_of::<u16>() };
let layout = Layout::from_size_align(
header_size + length * unit_size,
align_of::<ak::Utf16StringDataHeader>(),
@@ -64,7 +64,7 @@ fn allocate_uninitialized_string(length: usize, has_ascii_storage: bool) -> usiz
length_in_code_units: u32::try_from(length).expect("test strings fit in u32"),
length_in_code_points: AtomicU32::new(u32::MAX),
hash: AtomicU32::new(0),
- flags: AtomicU32::new(if has_ascii_storage { 0 } else { ak::HAS_UTF16_STORAGE }),
+ flags: AtomicU32::new(if has_latin1_storage { 0 } else { ak::HAS_UTF16_STORAGE }),
});
storage as usize
}
@@ -108,8 +108,8 @@ extern "C" fn ladybird_utf16_fly_string_from_utf8(data: *const u8, length: usize
}
#[unsafe(no_mangle)]
-extern "C" fn ladybird_utf16_string_create_uninitialized(length: usize, has_ascii_storage: bool) -> usize {
- allocate_uninitialized_string(length, has_ascii_storage)
+extern "C" fn ladybird_utf16_string_create_uninitialized(length: usize, has_latin1_storage: bool) -> usize {
+ allocate_uninitialized_string(length, has_latin1_storage)
}
#[unsafe(no_mangle)]
diff --git a/Libraries/LibJS/Rust/src/utf16.rs b/Libraries/LibJS/Rust/src/utf16.rs
index 84b0c639be8..c7349137099 100644
--- a/Libraries/LibJS/Rust/src/utf16.rs
+++ b/Libraries/LibJS/Rust/src/utf16.rs
@@ -145,7 +145,7 @@ impl<'a> Utf16View<'a> {
pub fn to_utf16_string(self) -> Utf16String {
match self {
Self::Ascii(units) => Utf16String::from_utf8(ascii_as_str(units)),
- Self::Latin1(_) => self.with_utf16_code_units(Utf16String::from_utf16),
+ Self::Latin1(units) => Utf16String::from_latin1(units),
Self::Utf16(units) => Utf16String::from_utf16(units),
}
}
@@ -404,14 +404,14 @@ pub fn decode_utf16_surrogate_pair(high_surrogate: u16, low_surrogate: u16) -> u
+ FIRST_SUPPLEMENTARY_PLANE_CODE_POINT
}
-/// Mirrors AK::Utf16StringBuilder: collects code units as ASCII bytes until one of them is not ASCII, and builds a string
-/// with ASCII storage when all of them are.
+/// Mirrors AK::Utf16StringBuilder: collects code units as Latin-1 bytes until one of them is above U+00FF, and builds a
+/// string with one byte per code unit when none of them is.
pub struct Utf16StringBuilder {
storage: BuilderStorage,
}
enum BuilderStorage {
- Ascii(Vec<u8>),
+ Latin1(Vec<u8>),
Utf16(Vec<u16>),
}
@@ -428,48 +428,51 @@ impl Utf16StringBuilder {
pub fn with_capacity(capacity: usize) -> Self {
Self {
- storage: BuilderStorage::Ascii(Vec::with_capacity(capacity)),
+ storage: BuilderStorage::Latin1(Vec::with_capacity(capacity)),
}
}
pub fn is_empty(&self) -> bool {
match &self.storage {
- BuilderStorage::Ascii(bytes) => bytes.is_empty(),
+ BuilderStorage::Latin1(bytes) => bytes.is_empty(),
BuilderStorage::Utf16(code_units) => code_units.is_empty(),
}
}
pub fn len(&self) -> usize {
match &self.storage {
- BuilderStorage::Ascii(bytes) => bytes.len(),
+ BuilderStorage::Latin1(bytes) => bytes.len(),
BuilderStorage::Utf16(code_units) => code_units.len(),
}
}
pub fn truncate(&mut self, length: usize) {
match &mut self.storage {
- BuilderStorage::Ascii(bytes) => bytes.truncate(length),
+ BuilderStorage::Latin1(bytes) => bytes.truncate(length),
BuilderStorage::Utf16(code_units) => code_units.truncate(length),
}
}
- /// The code units as UTF-16, widening the ASCII bytes collected so far the first time a code unit is not ASCII.
+ /// The code units as UTF-16, widening the Latin-1 bytes collected so far the first time a code unit is above
+ /// U+00FF.
fn utf16_code_units(&mut self, additional: usize) -> &mut Vec<u16> {
- if let BuilderStorage::Ascii(bytes) = &self.storage {
+ if let BuilderStorage::Latin1(bytes) = &self.storage {
let mut code_units = Vec::with_capacity((bytes.len() + additional).max(bytes.capacity()));
code_units.extend(bytes.iter().map(|&byte| u16::from(byte)));
self.storage = BuilderStorage::Utf16(code_units);
}
match &mut self.storage {
BuilderStorage::Utf16(code_units) => code_units,
- BuilderStorage::Ascii(_) => unreachable!("the storage was just widened"),
+ BuilderStorage::Latin1(_) => unreachable!("the storage was just widened"),
}
}
pub fn append(&mut self, view: Utf16View<'_>) {
match (&mut self.storage, view) {
- (BuilderStorage::Ascii(bytes), Utf16View::Ascii(units)) => bytes.extend_from_slice(units),
- (BuilderStorage::Ascii(bytes), Utf16View::Utf16(units)) if units.iter().all(|&unit| unit < 0x80) => {
+ (BuilderStorage::Latin1(bytes), Utf16View::Ascii(units) | Utf16View::Latin1(units)) => {
+ bytes.extend_from_slice(units);
+ }
+ (BuilderStorage::Latin1(bytes), Utf16View::Utf16(units)) if units.iter().all(|&unit| unit <= 0xff) => {
bytes.extend(units.iter().map(|&unit| unit as u8));
}
_ => {
@@ -486,7 +489,7 @@ impl Utf16StringBuilder {
pub fn append_ascii_bytes(&mut self, ascii: &[u8]) {
debug_assert!(ascii.is_ascii());
match &mut self.storage {
- BuilderStorage::Ascii(bytes) => bytes.extend_from_slice(ascii),
+ BuilderStorage::Latin1(bytes) => bytes.extend_from_slice(ascii),
BuilderStorage::Utf16(code_units) => code_units.extend(ascii.iter().map(|&byte| u16::from(byte))),
}
}
@@ -494,7 +497,7 @@ impl Utf16StringBuilder {
pub fn append_repeated_ascii(&mut self, ascii: u8, count: usize) {
debug_assert!(ascii.is_ascii());
match &mut self.storage {
- BuilderStorage::Ascii(bytes) => bytes.extend(core::iter::repeat_n(ascii, count)),
+ BuilderStorage::Latin1(bytes) => bytes.extend(core::iter::repeat_n(ascii, count)),
BuilderStorage::Utf16(code_units) => code_units.extend(core::iter::repeat_n(u16::from(ascii), count)),
}
}
@@ -502,7 +505,7 @@ impl Utf16StringBuilder {
/// Mirrors AK::Utf16StringBuilder::append_quoted_escaped_for_json(): the string as a JSON string literal, which
/// QuoteJSONString specifies.
pub fn append_quoted_escaped_for_json(&mut self, string: Utf16View<'_>) {
- if let (BuilderStorage::Ascii(bytes), Utf16View::Ascii(units)) = (&mut self.storage, string)
+ if let (BuilderStorage::Latin1(bytes), Utf16View::Ascii(units)) = (&mut self.storage, string)
&& ascii_json_special_code_unit_position(units).is_none()
{
bytes.reserve(units.len() + 2);
@@ -581,12 +584,18 @@ impl Utf16StringBuilder {
self.append_ascii(utf8);
return;
}
+ if let BuilderStorage::Latin1(bytes) = &mut self.storage
+ && utf8.chars().all(|code_point| u32::from(code_point) <= 0xff)
+ {
+ bytes.extend(utf8.chars().map(|code_point| code_point as u8));
+ return;
+ }
self.utf16_code_units(utf8.len()).extend(utf8.encode_utf16());
}
pub fn append_code_unit(&mut self, code_unit: u16) {
match &mut self.storage {
- BuilderStorage::Ascii(bytes) if code_unit < 0x80 => bytes.push(code_unit as u8),
+ BuilderStorage::Latin1(bytes) if code_unit <= 0xff => bytes.push(code_unit as u8),
_ => self.utf16_code_units(1).push(code_unit),
}
}
@@ -607,7 +616,7 @@ impl Utf16StringBuilder {
pub fn append_repeated(&mut self, view: Utf16View<'_>, count: usize) {
let additional = view.length_in_code_units().saturating_mul(count);
match &mut self.storage {
- BuilderStorage::Ascii(bytes) => bytes.reserve(additional),
+ BuilderStorage::Latin1(bytes) => bytes.reserve(additional),
BuilderStorage::Utf16(code_units) => code_units.reserve(additional),
}
for _ in 0..count {
@@ -617,7 +626,7 @@ impl Utf16StringBuilder {
pub fn to_utf16_string(&self) -> Utf16String {
match &self.storage {
- BuilderStorage::Ascii(bytes) => Utf16String::from_ascii(bytes),
+ BuilderStorage::Latin1(bytes) => Utf16String::from_latin1(bytes),
BuilderStorage::Utf16(code_units) => Utf16String::from_utf16(code_units),
}
}
@@ -829,15 +838,16 @@ pub fn to_utf16_fly_string(string: &Utf16String) -> Utf16FlyString {
Utf16FlyString::from_utf16_string(string)
}
-/// Concatenates views into a new string, ASCII when every view is.
+/// Concatenates views into a new string, with one byte per code unit when every view has it.
pub fn concatenate(views: &[Utf16View<'_>]) -> Utf16String {
let length = views.iter().map(|view| view.length_in_code_units()).sum();
- if views.iter().all(|view| view.has_ascii_storage()) {
- return Utf16String::from_ascii_concatenation(
+ if views.iter().all(|view| !matches!(view, Utf16View::Utf16(_))) {
+ return Utf16String::from_latin1_concatenation(
length,
+ views.iter().all(|view| view.is_ascii()),
views.iter().map(|view| match view {
- Utf16View::Ascii(units) => *units,
- Utf16View::Latin1(_) | Utf16View::Utf16(_) => unreachable!("every view has ASCII storage"),
+ Utf16View::Ascii(units) | Utf16View::Latin1(units) => *units,
+ Utf16View::Utf16(_) => unreachable!("every view has one byte per code unit"),
}),
);
}
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 9e618e92a4f..cb5cbf1edac 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
@@ -130,12 +130,7 @@ impl<'a> StructuredSerializeReader<'a> {
pub(crate) fn decode_utf16_string(&self) -> WebIdlResult<Utf16String> {
Ok(match self.decoded(self.decoder.decode_utf16_string())? {
- DecodedString::Latin1(characters) => Utf16String::from_utf16(
- &characters
- .iter()
- .map(|&character| u16::from(character))
- .collect::<Vec<_>>(),
- ),
+ DecodedString::Latin1(characters) => Utf16String::from_latin1(characters),
DecodedString::Utf16(code_units) => Utf16String::from_utf16(&code_units),
})
}
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rs
index 1b4e205fd36..e938bbc128d 100644
--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs
@@ -8412,7 +8412,7 @@ pub(crate) mod ffi_test_stubs {
#[unsafe(no_mangle)]
extern "C" fn ladybird_utf16_string_unref(_raw: usize) {}
#[unsafe(no_mangle)]
- extern "C" fn ladybird_utf16_string_create_uninitialized(_length: usize, _has_ascii_storage: bool) -> usize {
+ extern "C" fn ladybird_utf16_string_create_uninitialized(_length: usize, _has_latin1_storage: bool) -> usize {
unreachable!("no unit test makes a string the host owns");
}
#[unsafe(no_mangle)]
diff --git a/Tests/AK/TestUtf16String.cpp b/Tests/AK/TestUtf16String.cpp
index 0fcee1e567b..9c05e001dd5 100644
--- a/Tests/AK/TestUtf16String.cpp
+++ b/Tests/AK/TestUtf16String.cpp
@@ -1353,14 +1353,16 @@ TEST_CASE(latin1_storage)
static constexpr u8 bytes[] = { 'c', 'r', 0xE8, 'm', 'e', ' ', 'b', 'r', 0xFB, 'l', 0xE9, 'e' };
auto string = Utf16String::from_utf16(Utf16View::from_latin1(bytes, false));
auto utf16_string = Utf16String::from_utf8("crème brûlée"sv);
+ auto utf16_view = u"crème brûlée"sv;
EXPECT(string.has_long_storage());
EXPECT(!string.has_ascii_storage());
EXPECT(string.utf16_view().has_latin1_storage());
- EXPECT(utf16_string.has_long_utf16_storage());
+ EXPECT(!utf16_view.has_latin1_storage());
EXPECT_EQ(string, utf16_string);
- EXPECT_EQ(string.hash(), utf16_string.hash());
+ EXPECT_EQ(string, utf16_view);
+ EXPECT_EQ(string.hash(), utf16_view.hash());
EXPECT_EQ(string.to_utf8(), "crème brûlée"sv);
Utf16FlyString fly_string { utf16_string };
EXPECT_EQ(Utf16FlyString::from_utf16(string.utf16_view()), fly_string);
@@ -1374,3 +1376,32 @@ TEST_CASE(latin1_storage)
auto ascii_string = Utf16String::from_utf16(Utf16View::from_latin1(ascii_bytes, false));
EXPECT(ascii_string.has_long_ascii_storage());
}
+
+TEST_CASE(latin1_storage_for_text_up_to_u00ff)
+{
+ auto expect_latin1 = [](Utf16String const& string) {
+ EXPECT(string.has_long_storage());
+ EXPECT(string.utf16_view().has_latin1_storage());
+ EXPECT(!string.has_ascii_storage());
+ };
+
+ expect_latin1(Utf16String::from_utf8("café"sv));
+ expect_latin1(Utf16String::from_utf16(u"café"sv));
+ expect_latin1(Utf16String::from_utf8("ÿ"sv));
+ // Only ASCII is stored in a short string.
+ expect_latin1(Utf16String::from_utf8("é"sv));
+
+ auto string = Utf16String::from_utf8("Grüße aus Köln"sv);
+ expect_latin1(string);
+ EXPECT_EQ(string.length_in_code_units(), 14uz);
+ EXPECT_EQ(string.utf16_view().code_unit_at(2), 0xFC);
+ EXPECT_EQ(string.to_utf8(), "Grüße aus Köln"sv);
+
+ EXPECT(Utf16String::from_utf8("café €"sv).has_long_utf16_storage());
+ EXPECT(Utf16String::from_utf16(u"Ā"sv).has_long_utf16_storage());
+ EXPECT(Utf16String::from_utf16(u"cafe"sv).has_short_ascii_storage());
+
+ // A substring that is ASCII is ASCII storage.
+ EXPECT(Utf16String::from_utf16(string.substring_view(6, 3)).has_short_ascii_storage());
+ EXPECT(Utf16String::from_utf16(Utf16String::from_utf8("éabcdefghij"sv).substring_view(1)).has_long_ascii_storage());
+}
diff --git a/Tests/AK/TestUtf16StringBuilder.cpp b/Tests/AK/TestUtf16StringBuilder.cpp
index f2f54c9bede..b76efd1fea7 100644
--- a/Tests/AK/TestUtf16StringBuilder.cpp
+++ b/Tests/AK/TestUtf16StringBuilder.cpp
@@ -34,6 +34,32 @@ TEST_CASE(widen_to_utf16_storage)
EXPECT(!string.is_ascii());
}
+TEST_CASE(build_latin1_string)
+{
+ Utf16StringBuilder builder;
+ builder.append_ascii("caf"sv);
+ builder.append_code_point(0xE9);
+ builder.append(u" cr\u00E8me"sv);
+
+ EXPECT(builder.view().has_latin1_storage());
+ EXPECT_EQ(builder.view(), u"caf\u00E9 cr\u00E8me"sv);
+
+ auto string = builder.to_string();
+ EXPECT_EQ(string, u"caf\u00E9 cr\u00E8me"sv);
+ EXPECT(string.utf16_view().has_latin1_storage());
+ EXPECT(!string.has_ascii_storage());
+}
+
+TEST_CASE(widen_latin1_to_utf16_storage)
+{
+ Utf16StringBuilder builder;
+ builder.append_code_unit(0xE9);
+ builder.append_code_unit(0x263A);
+
+ EXPECT_EQ(builder.view(), u"\u00E9\u263A"sv);
+ EXPECT(builder.to_string().has_long_utf16_storage());
+}
+
TEST_CASE(append_quoted_escaped_for_json)
{
Utf16StringBuilder ascii_builder;
@@ -78,6 +104,18 @@ TEST_CASE(trim_ascii_storage)
EXPECT_EQ(builder.to_string(), "ab"sv);
}
+TEST_CASE(trim_latin1_storage)
+{
+ Utf16StringBuilder builder;
+ builder.append(u"ab\u00E9"sv);
+
+ builder.trim(1);
+
+ auto string = builder.to_string();
+ EXPECT_EQ(string, "ab"sv);
+ EXPECT(string.has_short_ascii_storage());
+}
+
TEST_CASE(trim_utf16_storage)
{
Utf16StringBuilder builder;
@@ -113,6 +151,18 @@ TEST_CASE(long_utf16_string)
EXPECT_EQ(string.utf16_view().code_unit_at(299), 0x0100);
}
+TEST_CASE(long_latin1_string)
+{
+ Utf16StringBuilder builder;
+ builder.append_repeated(u"\u00E9"sv, 300);
+
+ auto string = builder.to_string();
+ EXPECT_EQ(string.length_in_code_units(), 300uz);
+ EXPECT(string.utf16_view().has_latin1_storage());
+ EXPECT(!string.has_ascii_storage());
+ EXPECT_EQ(string.utf16_view().code_unit_at(299), 0xE9);
+}
+
TEST_CASE(reuse_after_creating_long_utf16_string)
{
Utf16StringBuilder builder;
diff --git a/Tests/LibJS/Runtime/latin1-strings.js b/Tests/LibJS/Runtime/latin1-strings.js
new file mode 100644
index 00000000000..85ed6bf37d6
--- /dev/null
+++ b/Tests/LibJS/Runtime/latin1-strings.js
@@ -0,0 +1,87 @@
+// NB: This file spells characters above U+00FF as escapes, so that its source is Latin-1 as well.
+
+describe("strings with code units up to U+00FF", () => {
+ test("case conversion", () => {
+ expect("café".toUpperCase()).toBe("CAFÉ");
+ expect("CAFÉ".toLowerCase()).toBe("café");
+ expect("ÿ".toUpperCase()).toBe("\u0178");
+ expect("µ".toUpperCase()).toBe("\u039C");
+ expect("ß".toUpperCase()).toBe("SS");
+ expect("café".toLocaleUpperCase("tr")).toBe("CAFÉ");
+ });
+
+ test("code units", () => {
+ const string = "crème brûlée";
+ expect(string).toHaveLength(12);
+ expect(string.charCodeAt(2)).toBe(0xe8);
+ expect(string.codePointAt(10)).toBe(0xe9);
+ expect(string.at(-2)).toBe("é");
+ expect([...string]).toHaveLength(12);
+ expect(string.indexOf("brû")).toBe(6);
+ expect(string.split(" ")).toEqual(["crème", "brûlée"]);
+ expect(string.slice(8)).toBe("ûlée");
+ expect(String.fromCharCode(0x63, 0xe9)).toBe("cé");
+ });
+
+ test("equal to the same text stored with two bytes per code unit", () => {
+ const wide = ["c", "a", "f", "é", "\u20AC"].join("").slice(0, 4);
+ expect(wide).toBe("café");
+ expect(new Map([["café", 1]]).get(wide)).toBe(1);
+ expect({ café: 1 }[wide]).toBe(1);
+ expect(new Set(["café", wide]).size).toBe(1);
+ expect(wide.localeCompare("café")).toBe(0);
+ expect("caf" + "é" === "café").toBeTrue();
+ });
+
+ test("ordering", () => {
+ expect("é" < "\u20AC").toBeTrue();
+ expect("ÿ" > "é").toBeTrue();
+ expect(["é", "\u20AC", "f", "e"].sort()).toEqual(["e", "f", "é", "\u20AC"]);
+ expect(["é", "f", "e"].sort(new Intl.Collator("en").compare)).toEqual(["e", "é", "f"]);
+ expect("é".localeCompare("f", "en")).toBe(-1);
+ });
+
+ test("concatenation and building", () => {
+ expect("é".repeat(3)).toBe("ééé");
+ expect(["à", "b", "ç"].join("-")).toBe("à-b-ç");
+ expect(`${"é"}${1}`).toBe("é1");
+ expect("é" + "\u20AC").toHaveLength(2);
+ expect("é".padStart(3, "à")).toBe("ààé");
+ expect("a-é".replace("-", "ü")).toBe("aüé");
+ expect("aéa".replaceAll("a", "\u20AC")).toBe("\u20ACé\u20AC");
+ expect(String.raw`é${1}`).toBe("é1");
+ });
+
+ test("JSON", () => {
+ expect(JSON.stringify({ clé: "valeur é" })).toBe('{"clé":"valeur é"}');
+ const reviver = (key, value) => (typeof value === "string" ? value + "!" : value);
+ expect(JSON.parse('{"clé":"é"}', reviver)).toEqual({ clé: "é!" });
+ });
+
+ test("URI functions", () => {
+ expect(encodeURIComponent("é")).toBe("%C3%A9");
+ expect(decodeURIComponent("%C3%A9")).toBe("é");
+ expect(escape("é")).toBe("%E9");
+ expect(unescape("%E9")).toBe("é");
+ });
+
+ test("regular expressions", () => {
+ expect(/é/.test("café")).toBeTrue();
+ expect(/É/i.test("café")).toBeTrue();
+ expect(/ÿ/iu.test("\u0178")).toBeTrue();
+ expect(/^.$/u.test("é")).toBeTrue();
+ expect(/[à-ÿ]+/.exec("crème")[0]).toBe("è");
+ expect("crème brûlée".match(/[^\x00-\x7f]/g)).toEqual(["è", "û", "é"]);
+ expect("é\u20AC".replace(/\u20AC/, "e")).toBe("ée");
+ });
+
+ test("normalization", () => {
+ expect("e\u0301".normalize("NFC")).toBe("é");
+ expect("é".normalize("NFD")).toBe("e\u0301");
+ });
+
+ test("Intl", () => {
+ expect([...new Intl.Segmenter("en", { granularity: "grapheme" }).segment("café")]).toHaveLength(4);
+ expect(() => new Intl.Locale("é")).toThrowWithMessage(RangeError, "é is not a structurally valid language tag");
+ });
+});
diff --git a/Tests/LibWeb/Text/expected/latin1-strings.txt b/Tests/LibWeb/Text/expected/latin1-strings.txt
new file mode 100644
index 00000000000..06c66cca32a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/latin1-strings.txt
@@ -0,0 +1,13 @@
+TextEncoder: 99,97,102,195,169
+TextDecoder windows-1252: cé€
+TextDecoder UTF-8: cé
+URL: http://xn--caf-dma.example/%C3%A9?q=%C3%BC#%C3%BF
+URLSearchParams: ?q=%C3%BC&cl%C3%A9=%C3%A9
+textContent: crème brûlée (12)
+dataset: valeur
+querySelector: true
+attribute: true
+style: "é"
+structuredClone: crème brûlée
+Blob: é
+btoa: 6Q==, atob: true
diff --git a/Tests/LibWeb/Text/input/latin1-strings.html b/Tests/LibWeb/Text/input/latin1-strings.html
new file mode 100644
index 00000000000..13415fb27a7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/latin1-strings.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<div id="target" data-clé="valeur">crème brûlée</div>
+<script src="include.js"></script>
+<script>
+ promiseTest(async () => {
+ println(`TextEncoder: ${new TextEncoder().encode("café").join(",")}`);
+ println(`TextDecoder windows-1252: ${new TextDecoder("windows-1252").decode(new Uint8Array([0x63, 0xe9, 0x80]))}`);
+ println(`TextDecoder UTF-8: ${new TextDecoder().decode(new Uint8Array([0x63, 0xc3, 0xa9]))}`);
+
+ const url = new URL("http://café.example/é?q=ü#ÿ");
+ println(`URL: ${url.href}`);
+ url.searchParams.set("clé", "é");
+ println(`URLSearchParams: ${url.search}`);
+
+ const target = document.getElementById("target");
+ println(`textContent: ${target.textContent} (${target.textContent.length})`);
+ println(`dataset: ${target.dataset["clé"]}`);
+ println(`querySelector: ${document.querySelector("[data-clé='valeur']") === target}`);
+ target.setAttribute("title", "ça");
+ println(`attribute: ${target.title === "ça"}`);
+ target.style.setProperty("content", '"é"');
+ println(`style: ${target.style.getPropertyValue("content")}`);
+
+ println(`structuredClone: ${structuredClone({ clé: "crème brûlée" })["clé"]}`);
+ println(`Blob: ${await new Blob(["é"]).text()}`);
+ println(`btoa: ${btoa("é")}, atob: ${atob("6Q==") === "é"}`);
+ });
+</script>