Skip to content

Truly independent web browser

Everywhere: Handle Latin-1 Utf16String storage in every reader

Shannon Boothc17c9ae7196e
diff --git a/AK/Utf16StringData.cpp b/AK/Utf16StringData.cpp
index a5c04fbd64a..bdaa132eca7 100644
--- a/AK/Utf16StringData.cpp
+++ b/AK/Utf16StringData.cpp
@@ -134,13 +134,13 @@ NonnullRefPtr<Utf16StringData> Utf16StringData::from_string_builder(Utf16StringB
if (auto buffer = builder.leak_buffer_for_string_construction(Badge<Utf16StringData> {}); buffer.has_value()) {
auto storage_type = view.has_latin1_storage() ? StorageType::Latin1 : StorageType::UTF16;
string = adopt_ref(*new (buffer->buffer.data()) Utf16StringData { storage_type, code_unit_length });
- if (view.has_latin1_storage() && !view.has_ascii_storage())
+ if (view.has_latin1_storage() && !view.is_ascii())
string->m_header.flags |= ContainsNonAscii;
} else {
if (view.has_latin1_storage()) {
string = create_uninitialized(StorageType::Latin1, code_unit_length);
TypedTransfer<u8>::copy(string->latin1_data(), view.latin1_span().data(), code_unit_length);
- if (!view.has_ascii_storage())
+ if (!view.is_ascii())
string->m_header.flags |= ContainsNonAscii;
} else {
string = create_uninitialized(StorageType::UTF16, code_unit_length);
diff --git a/AK/Utf16View.h b/AK/Utf16View.h
index 6d5db9cadf1..334e278ff42 100644
--- a/AK/Utf16View.h
+++ b/AK/Utf16View.h
@@ -227,15 +227,16 @@ public:
return { reinterpret_cast<u8 const*>(m_string.latin1), length_in_code_units() };
}
+ // NB: A substring of Latin-1 storage that is not ASCII may still be ASCII itself, which these check.
[[nodiscard]] ALWAYS_INLINE ReadonlyBytes ascii_bytes() const
{
- VERIFY(has_ascii_storage());
+ VERIFY(has_ascii_storage() || (has_latin1_storage() && is_ascii()));
return { reinterpret_cast<u8 const*>(m_string.latin1), length_in_code_units() };
}
[[nodiscard]] constexpr ReadonlySpan<char> ascii_span() const
{
- VERIFY(has_ascii_storage());
+ VERIFY(has_ascii_storage() || (has_latin1_storage() && is_ascii()));
return { m_string.latin1, length_in_code_units() };
}
diff --git a/Libraries/LibGfx/TextLayout.cpp b/Libraries/LibGfx/TextLayout.cpp
index 570a38b7ec9..94bea57b418 100644
--- a/Libraries/LibGfx/TextLayout.cpp
+++ b/Libraries/LibGfx/TextLayout.cpp
@@ -401,7 +401,10 @@ static hb_buffer_t* setup_text_shaping(Utf16View const& string, Font const& font
hb_buffer_set_script(buffer, HB_SCRIPT_LATIN);
hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
} else {
- hb_buffer_add_utf16(buffer, reinterpret_cast<u16 const*>(string.utf16_span().data()), string.length_in_code_units(), 0, -1);
+ if (string.has_latin1_storage())
+ hb_buffer_add_latin1(buffer, string.latin1_span().data(), string.length_in_code_units(), 0, -1);
+ else
+ hb_buffer_add_utf16(buffer, reinterpret_cast<u16 const*>(string.utf16_span().data()), string.length_in_code_units(), 0, -1);
// For non-ASCII, set direction from text_type if known, otherwise guess.
if (text_type == GlyphRun::TextType::Ltr) {
hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
diff --git a/Libraries/LibIPC/Encoder.cpp b/Libraries/LibIPC/Encoder.cpp
index 89931ddef19..2dfbdb69a97 100644
--- a/Libraries/LibIPC/Encoder.cpp
+++ b/Libraries/LibIPC/Encoder.cpp
@@ -78,6 +78,10 @@ ErrorOr<void> encode(Encoder& encoder, Utf16View const& value)
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)));
} 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/LibJS/Runtime/ExternalMemory.h b/Libraries/LibJS/Runtime/ExternalMemory.h
index e5eb4ca1a02..5a2aff3c2cd 100644
--- a/Libraries/LibJS/Runtime/ExternalMemory.h
+++ b/Libraries/LibJS/Runtime/ExternalMemory.h
@@ -41,7 +41,7 @@ inline size_t utf16_string_external_memory_size(Utf16String const& string)
if (!string.has_long_storage())
return 0;
- auto code_unit_size = string.has_ascii_storage() ? sizeof(char) : sizeof(char16_t);
+ auto code_unit_size = string.utf16_view().has_latin1_storage() ? sizeof(u8) : sizeof(char16_t);
if (string.length_in_code_units() > NumericLimits<size_t>::max() / code_unit_size)
return NumericLimits<size_t>::max();
return string.length_in_code_units() * code_unit_size;
diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cpp
index f6f261e415e..ed72677acd4 100644
--- a/Libraries/LibJS/Runtime/VM.cpp
+++ b/Libraries/LibJS/Runtime/VM.cpp
@@ -121,7 +121,7 @@ static ImportedModulePayload imported_module_payload_from_abi(JSImportedModulePa
static void append_utf16_string_to_sink(JSStringSink const& sink, Utf16View string)
{
- if (!string.has_ascii_storage()) {
+ if (!string.has_latin1_storage()) {
sink.append(sink.context, reinterpret_cast<u16 const*>(string.utf16_span().data()), string.length_in_code_units());
return;
}
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
index 1bcf8904928..b95d14ba460 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
@@ -81,7 +81,7 @@ impl EcmaScriptRegex {
has_indices: flags.has_indices,
};
- // Converted as rust_regex_compile_ascii and rust_regex_compile convert the pattern they are passed.
+ // Converted as rust_regex_compile_latin1 and rust_regex_compile convert the pattern they are passed.
let pattern_characters = match pattern {
Utf16View::Ascii(bytes) | Utf16View::Latin1(bytes) => bytes.iter().map(|&byte| char::from(byte)).collect(),
Utf16View::Utf16(code_units) => char::decode_utf16(code_units.iter().copied())
@@ -115,11 +115,9 @@ impl EcmaScriptRegex {
let mut capture_buffer = self.capture_buffer.borrow_mut();
capture_buffer.resize(slots, 0);
let result = match input {
- Utf16View::Ascii(bytes) => self.regex.exec_into_ascii(bytes, start_position, &mut capture_buffer),
- // NB: The byte matcher only matches ASCII, so Latin-1 is matched as UTF-16.
- Utf16View::Latin1(_) => input.with_utf16_code_units(|code_units| {
- self.regex.exec_into(code_units, start_position, &mut capture_buffer)
- }),
+ Utf16View::Ascii(bytes) | Utf16View::Latin1(bytes) => {
+ self.regex.exec_into_latin1(bytes, start_position, &mut capture_buffer)
+ }
Utf16View::Utf16(code_units) => self.regex.exec_into(code_units, start_position, &mut capture_buffer),
};
MatchResult::from_vm_result(result)
@@ -135,10 +133,7 @@ impl EcmaScriptRegex {
/// Test for a match without filling capture buffer.
pub fn test(&self, input: Utf16View<'_>, start_position: usize) -> MatchResult {
let result = match input {
- Utf16View::Ascii(bytes) => self.regex.test_ascii(bytes, start_position),
- Utf16View::Latin1(_) => {
- input.with_utf16_code_units(|code_units| self.regex.test(code_units, start_position))
- }
+ Utf16View::Ascii(bytes) | Utf16View::Latin1(bytes) => self.regex.test_latin1(bytes, start_position),
Utf16View::Utf16(code_units) => self.regex.test(code_units, start_position),
};
MatchResult::from_vm_result(result)
@@ -175,13 +170,10 @@ impl EcmaScriptRegex {
loop {
let result = match input {
- Utf16View::Ascii(bytes) => self
- .regex
- .find_all_into_ascii(bytes, start_position, &mut find_all_buffer),
- Utf16View::Latin1(_) => input.with_utf16_code_units(|code_units| {
+ Utf16View::Ascii(bytes) | Utf16View::Latin1(bytes) => {
self.regex
- .find_all_into(code_units, start_position, &mut find_all_buffer)
- }),
+ .find_all_into_latin1(bytes, start_position, &mut find_all_buffer)
+ }
Utf16View::Utf16(code_units) => {
self.regex
.find_all_into(code_units, start_position, &mut find_all_buffer)
diff --git a/Libraries/LibRegex/Rust/src/ffi.rs b/Libraries/LibRegex/Rust/src/ffi.rs
index aed2b58d98e..b301d333499 100644
--- a/Libraries/LibRegex/Rust/src/ffi.rs
+++ b/Libraries/LibRegex/Rust/src/ffi.rs
@@ -87,15 +87,15 @@ pub unsafe extern "C" fn rust_regex_compile(
compile_pattern(pattern, flags, error_out, error_len_out)
}
-/// Compile an ASCII-only regex pattern. Returns an opaque handle, or null on error.
+/// Compile a regex pattern of Latin-1 code units. Returns an opaque handle, or null on error.
/// On error, writes the error message to `error_out` and `error_len_out`.
/// The caller must free the error string with `rust_regex_free_error`.
///
/// # Safety
-/// `pattern` must be a valid pointer to `pattern_len` ASCII bytes.
+/// `pattern` must be a valid pointer to `pattern_len` Latin-1 bytes.
/// `error_out` and `error_len_out` must be valid pointers.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_regex_compile_ascii(
+pub unsafe extern "C" fn rust_regex_compile_latin1(
pattern: *const u8,
pattern_len: usize,
flags: RustRegexFlags,
@@ -201,14 +201,14 @@ pub unsafe extern "C" fn rust_regex_exec_into(
exec_into_internal(regex, input, start_pos, out_captures, out_capture_slots)
}
-/// Execute a regex against ASCII input, writing captures into a caller-provided buffer.
+/// Execute a regex against Latin-1 input, writing captures into a caller-provided buffer.
///
/// # Safety
/// - `regex` must be a valid pointer from `rust_regex_compile`.
-/// - `input` must point to `input_len` ASCII code units.
+/// - `input` must point to `input_len` Latin-1 code units.
/// - `out_captures` must point to a buffer of at least `capture_count * 2` i32s.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_regex_exec_into_ascii(
+pub unsafe extern "C" fn rust_regex_exec_into_latin1(
regex: *const RustRegex,
input: *const u8,
input_len: usize,
@@ -252,12 +252,12 @@ pub unsafe extern "C" fn rust_regex_test(
test_internal(regex, input, start_pos)
}
-/// Test whether a regex matches anywhere in ASCII input.
+/// Test whether a regex matches anywhere in Latin-1 input.
///
/// # Safety
/// Same requirements as `rust_regex_test`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_regex_test_ascii(
+pub unsafe extern "C" fn rust_regex_test_latin1(
regex: *const RustRegex,
input: *const u8,
input_len: usize,
@@ -331,14 +331,14 @@ pub unsafe extern "C" fn rust_regex_find_all(
find_all_internal(regex, input, start_pos, out, out_capacity)
}
-/// Find all non-overlapping matches in ASCII input.
+/// Find all non-overlapping matches in Latin-1 input.
///
/// # Safety
/// - `regex` must be a valid pointer from `rust_regex_compile`.
-/// - `input` must point to `input_len` ASCII code units.
+/// - `input` must point to `input_len` Latin-1 code units.
/// - `out` must point to at least `out_capacity` i32s.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_regex_find_all_ascii(
+pub unsafe extern "C" fn rust_regex_find_all_latin1(
regex: *const RustRegex,
input: *const u8,
input_len: usize,
diff --git a/Libraries/LibRegex/Rust/src/regex.rs b/Libraries/LibRegex/Rust/src/regex.rs
index c4f9b4e4a7b..59f82693c1f 100644
--- a/Libraries/LibRegex/Rust/src/regex.rs
+++ b/Libraries/LibRegex/Rust/src/regex.rs
@@ -80,7 +80,7 @@ impl Regex {
self.exec_into_input(input, start, out)
}
- pub fn exec_into_ascii(&self, input: &[u8], start: usize, out: &mut [i32]) -> vm::VmResult {
+ pub fn exec_into_latin1(&self, input: &[u8], start: usize, out: &mut [i32]) -> vm::VmResult {
self.exec_into_input(input, start, out)
}
@@ -123,7 +123,7 @@ impl Regex {
self.test_input(input, start)
}
- pub fn test_ascii(&self, input: &[u8], start: usize) -> vm::VmResult {
+ pub fn test_latin1(&self, input: &[u8], start: usize) -> vm::VmResult {
self.test_input(input, start)
}
@@ -540,7 +540,7 @@ impl Regex {
self.find_all_into_input(input, start, result_buf)
}
- pub fn find_all_into_ascii(&self, input: &[u8], start: usize, result_buf: &mut [i32]) -> i32 {
+ pub fn find_all_into_latin1(&self, input: &[u8], start: usize, result_buf: &mut [i32]) -> i32 {
self.find_all_into_input(input, start, result_buf)
}
diff --git a/Libraries/LibRegex/Rust/src/vm.rs b/Libraries/LibRegex/Rust/src/vm.rs
index 701c6d2515c..9d12e297d9b 100644
--- a/Libraries/LibRegex/Rust/src/vm.rs
+++ b/Libraries/LibRegex/Rust/src/vm.rs
@@ -133,9 +133,6 @@ impl Input for &[u8] {
#[inline(always)]
fn find_code_unit(self, start: usize, end: usize, ch16: u16) -> Option<usize> {
let byte = u8::try_from(ch16).ok()?;
- if byte > 0x7F {
- return None;
- }
let offset = memchr::memchr(byte, self.get(start..end)?)?;
Some(start + offset)
}
@@ -146,7 +143,7 @@ impl Input for &[u8] {
return false;
};
for (actual, expected) in slice.iter().zip(needle.iter()) {
- if *expected > 0x7F || *actual != *expected as u8 {
+ if u8::try_from(*expected) != Ok(*actual) {
return false;
}
}
diff --git a/Libraries/LibRegex/RustRegex.cpp b/Libraries/LibRegex/RustRegex.cpp
index 58e15b159d1..79b5aae6636 100644
--- a/Libraries/LibRegex/RustRegex.cpp
+++ b/Libraries/LibRegex/RustRegex.cpp
@@ -14,11 +14,11 @@ ErrorOr<CompiledRustRegex, String> CompiledRustRegex::compile(Utf16View pattern,
size_t error_len = 0;
RustRegex* regex = nullptr;
- if (pattern.has_ascii_storage()) {
- auto ascii = pattern.ascii_span();
- regex = rust_regex_compile_ascii(
- reinterpret_cast<unsigned char const*>(ascii.data()),
- ascii.size(),
+ if (pattern.has_latin1_storage()) {
+ auto latin1 = pattern.latin1_span();
+ regex = rust_regex_compile_latin1(
+ latin1.data(),
+ latin1.size(),
flags,
&error_ptr,
&error_len);
@@ -107,12 +107,12 @@ int CompiledRustRegex::exec_internal(Utf16View input, size_t start_pos) const
auto slots = m_capture_count * 2;
m_capture_buffer.resize(slots);
- if (input.has_ascii_storage()) {
- auto ascii = input.ascii_span();
- return rust_regex_exec_into_ascii(
+ if (input.has_latin1_storage()) {
+ auto latin1 = input.latin1_span();
+ return rust_regex_exec_into_latin1(
m_regex,
- reinterpret_cast<uint8_t const*>(ascii.data()),
- ascii.size(),
+ latin1.data(),
+ latin1.size(),
start_pos,
m_capture_buffer.data(),
slots);
@@ -144,12 +144,12 @@ bool CompiledRustRegex::is_single_non_bmp_literal() const
int CompiledRustRegex::test(Utf16View input, size_t start_pos) const
{
- if (input.has_ascii_storage()) {
- auto ascii = input.ascii_span();
- return rust_regex_test_ascii(
+ if (input.has_latin1_storage()) {
+ auto latin1 = input.latin1_span();
+ return rust_regex_test_latin1(
m_regex,
- reinterpret_cast<uint8_t const*>(ascii.data()),
- ascii.size(),
+ latin1.data(),
+ latin1.size(),
start_pos);
}
@@ -169,12 +169,12 @@ int CompiledRustRegex::find_all(Utf16View input, size_t start_pos) const
for (;;) {
int result;
- if (input.has_ascii_storage()) {
- auto ascii = input.ascii_span();
- result = rust_regex_find_all_ascii(
+ if (input.has_latin1_storage()) {
+ auto latin1 = input.latin1_span();
+ result = rust_regex_find_all_latin1(
m_regex,
- reinterpret_cast<uint8_t const*>(ascii.data()),
- ascii.size(),
+ latin1.data(),
+ latin1.size(),
start_pos,
m_find_all_buffer.data(),
m_find_all_buffer.size());
diff --git a/Libraries/LibTextCodec/Decoder.cpp b/Libraries/LibTextCodec/Decoder.cpp
index 8358f6ef19d..cc9b578b2f2 100644
--- a/Libraries/LibTextCodec/Decoder.cpp
+++ b/Libraries/LibTextCodec/Decoder.cpp
@@ -94,7 +94,7 @@ Optional<StringView> get_standardized_encoding(Utf16View encoding)
return {};
}
- if (encoding.has_ascii_storage()) {
+ if (encoding.has_latin1_storage()) {
auto ascii = encoding.ascii_span();
return get_standardized_encoding(StringView { ascii.data(), ascii.size() });
}
diff --git a/Libraries/LibURL/Parser.cpp b/Libraries/LibURL/Parser.cpp
index 46acd0f442a..7b7156b1306 100644
--- a/Libraries/LibURL/Parser.cpp
+++ b/Libraries/LibURL/Parser.cpp
@@ -55,7 +55,7 @@ static bool basic_parse_with_state_override_impl(FFI::RustUrlInput input, URL& u
Optional<URL> Parser::basic_parse(StringView raw_input, Optional<URL const&> base_url, Optional<StringView> encoding)
{
auto input = String::from_wtf8_with_replacement_character(raw_input);
- return basic_parse_impl({ input.bytes().data(), nullptr, input.bytes().size() }, base_url, encoding);
+ return basic_parse_impl({ input.bytes().data(), nullptr, nullptr, input.bytes().size() }, base_url, encoding);
}
Optional<URL> Parser::basic_parse(Utf16View raw_input, Optional<URL const&> base_url, Optional<StringView> encoding)
@@ -66,7 +66,7 @@ Optional<URL> Parser::basic_parse(Utf16View raw_input, Optional<URL const&> base
bool Parser::basic_parse(StringView raw_input, URL& url, State state_override, Optional<StringView> encoding)
{
auto input = String::from_wtf8_with_replacement_character(raw_input);
- return basic_parse_with_state_override_impl({ input.bytes().data(), nullptr, input.bytes().size() }, url, state_override, encoding);
+ return basic_parse_with_state_override_impl({ input.bytes().data(), nullptr, nullptr, input.bytes().size() }, url, state_override, encoding);
}
bool Parser::basic_parse(Utf16View raw_input, URL& url, State state_override, Optional<StringView> encoding)
diff --git a/Libraries/LibURL/Rust/src/ffi/url.rs b/Libraries/LibURL/Rust/src/ffi/url.rs
index b7658844736..b462f517b98 100644
--- a/Libraries/LibURL/Rust/src/ffi/url.rs
+++ b/Libraries/LibURL/Rust/src/ffi/url.rs
@@ -21,19 +21,22 @@ use crate::url::{UrlInput, parse_host_into};
#[derive(Clone, Copy)]
pub struct RustUrlInput {
pub utf8: *const u8,
+ pub latin1: *const u8,
pub utf16: *const u16,
pub length: usize,
}
impl RustUrlInput {
/// # Safety
- /// The selected pointer must borrow length storage units. Byte input must be valid UTF-8.
+ /// The selected pointer must borrow length storage units. UTF-8 input must be valid UTF-8.
pub(crate) unsafe fn borrow<'a>(self) -> UrlInput<'a> {
if self.length == 0 {
return UrlInput::Utf8("");
}
if !self.utf16.is_null() {
UrlInput::Utf16(unsafe { ak::slice_from_raw_parts(self.utf16, self.length) })
+ } else if !self.latin1.is_null() {
+ UrlInput::Latin1(unsafe { ak::slice_from_raw_parts(self.latin1, self.length) })
} else {
UrlInput::Utf8(unsafe { std::str::from_utf8_unchecked(ak::slice_from_raw_parts(self.utf8, self.length)) })
}
diff --git a/Libraries/LibURL/RustIntegration.cpp b/Libraries/LibURL/RustIntegration.cpp
index 1195563b3be..7ce1581fa06 100644
--- a/Libraries/LibURL/RustIntegration.cpp
+++ b/Libraries/LibURL/RustIntegration.cpp
@@ -350,11 +350,11 @@ static void on_parse_host_complete(void* ctx_ptr, FFI::FfiUrlHost const* ffi_res
FFI::RustUrlInput rust_url_input(Utf16View input)
{
- return {
- input.has_ascii_storage() ? reinterpret_cast<u8 const*>(input.ascii_span().data()) : nullptr,
- input.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(input.utf16_span().data()),
- input.length_in_code_units(),
- };
+ if (input.has_ascii_storage())
+ return { input.ascii_bytes().data(), nullptr, nullptr, input.length_in_code_units() };
+ if (input.has_latin1_storage())
+ return { nullptr, input.latin1_span().data(), nullptr, input.length_in_code_units() };
+ return { nullptr, nullptr, reinterpret_cast<u16 const*>(input.utf16_span().data()), input.length_in_code_units() };
}
static Optional<Host> parse_host_impl(FFI::RustUrlInput input, bool is_opaque)
@@ -374,7 +374,7 @@ static Optional<Host> parse_host_impl(FFI::RustUrlInput input, bool is_opaque)
Optional<Host> parse_host(StringView input, bool is_opaque)
{
auto processed_input = String::from_wtf8_with_replacement_character(input);
- return parse_host_impl({ processed_input.bytes().data(), nullptr, processed_input.bytes().size() }, is_opaque);
+ return parse_host_impl({ processed_input.bytes().data(), nullptr, nullptr, processed_input.bytes().size() }, is_opaque);
}
Optional<Host> parse_host(Utf16View input, bool is_opaque)
diff --git a/Libraries/LibURL/URL.cpp b/Libraries/LibURL/URL.cpp
index b09a2409a42..8d1d326bf90 100644
--- a/Libraries/LibURL/URL.cpp
+++ b/Libraries/LibURL/URL.cpp
@@ -165,7 +165,7 @@ void URL::set_from_rust_callback(void* url, FFI::RustUrl const* rust_url)
static FFI::RustUrlInput rust_url_input(StringView input)
{
- return { reinterpret_cast<u8 const*>(input.characters_without_null_termination()), nullptr, input.length() };
+ return { reinterpret_cast<u8 const*>(input.characters_without_null_termination()), nullptr, nullptr, input.length() };
}
static FFI::RustUrlByteSlice rust_byte_slice(Optional<StringView> string)
diff --git a/Libraries/LibUnicode/Bidi.cpp b/Libraries/LibUnicode/Bidi.cpp
index adff1b86070..366c2b719d8 100644
--- a/Libraries/LibUnicode/Bidi.cpp
+++ b/Libraries/LibUnicode/Bidi.cpp
@@ -12,7 +12,8 @@ namespace Unicode {
bool may_require_bidi_processing(Utf16View const& text)
{
- if (text.has_ascii_storage())
+ // NB: No code point up to U+00FF is right to left.
+ if (text.has_latin1_storage())
return false;
for (auto code_point : text) {
diff --git a/Libraries/LibUnicode/Collator.cpp b/Libraries/LibUnicode/Collator.cpp
index d7451b7b8f7..f8b08f5e35f 100644
--- a/Libraries/LibUnicode/Collator.cpp
+++ b/Libraries/LibUnicode/Collator.cpp
@@ -170,7 +170,7 @@ public:
SubstringSearcherImpl(icu::RuleBasedCollator const& collator, Utf16View const& haystack, Utf16View const& needle)
{
auto to_unicode_string = [](Utf16View const& string) {
- if (string.has_ascii_storage()) {
+ if (string.has_latin1_storage()) {
auto utf8 = MUST(string.to_utf8());
return icu::UnicodeString::fromUTF8(icu_string_piece(utf8.bytes_as_string_view()));
}
@@ -225,11 +225,17 @@ public:
virtual Collator::Order compare(Utf16View const& lhs, Utf16View const& rhs) const override
{
UErrorCode status = U_ZERO_ERROR;
-
- auto lhs_it = icu_string_iterator(lhs);
- auto rhs_it = icu_string_iterator(rhs);
-
- auto result = m_collator->compare(lhs_it, rhs_it, status);
+ UCollationResult result;
+
+ // NB: ICU has no iterator over Latin-1, so a string with Latin-1 storage that is not ASCII is compared as UTF-16.
+ auto has_non_ascii_latin1_storage = [](Utf16View const& string) { return string.has_latin1_storage() && !string.has_ascii_storage(); };
+ if (has_non_ascii_latin1_storage(lhs) || has_non_ascii_latin1_storage(rhs)) {
+ result = m_collator->compare(icu_string(lhs), icu_string(rhs), status);
+ } else {
+ auto lhs_it = icu_string_iterator(lhs);
+ auto rhs_it = icu_string_iterator(rhs);
+ result = m_collator->compare(lhs_it, rhs_it, status);
+ }
verify_icu_success(status);
switch (result) {
diff --git a/Libraries/LibUnicode/ICU.h b/Libraries/LibUnicode/ICU.h
index 6dc8498b25f..d375c1413d2 100644
--- a/Libraries/LibUnicode/ICU.h
+++ b/Libraries/LibUnicode/ICU.h
@@ -117,12 +117,21 @@ ALWAYS_INLINE icu::UnicodeString icu_string(StringView string)
return icu::UnicodeString::fromUTF8(icu_string_piece(string));
}
-// If the Utf16View has ASCII storage, this creates an owned icu::UnicodeString. Otherwise, the icu::UnicodeString is
+// If the Utf16View has Latin-1 storage, this creates an owned icu::UnicodeString. Otherwise, the icu::UnicodeString is
// unowned (i.e. it is effectively a view).
ALWAYS_INLINE icu::UnicodeString icu_string(Utf16View const& string)
{
if (string.has_ascii_storage())
return icu::UnicodeString::fromUTF8(icu_string_piece(string.ascii_bytes()));
+ if (string.has_latin1_storage()) {
+ auto latin1 = string.latin1_span();
+ icu::UnicodeString result;
+ auto* buffer = result.getBuffer(static_cast<i32>(latin1.size()));
+ for (size_t i = 0; i < latin1.size(); ++i)
+ buffer[i] = latin1[i];
+ result.releaseBuffer(static_cast<i32>(latin1.size()));
+ return result;
+ }
return { false, string.utf16_span().data(), static_cast<i32>(string.length_in_code_units()) };
}
diff --git a/Libraries/LibUnicode/Locale.cpp b/Libraries/LibUnicode/Locale.cpp
index 25816aee174..15e988854ec 100644
--- a/Libraries/LibUnicode/Locale.cpp
+++ b/Libraries/LibUnicode/Locale.cpp
@@ -571,7 +571,7 @@ Optional<Utf16String> canonicalize_unicode_locale_id(Utf16View locale)
Utf16String canonicalize_unicode_extension_values(StringView key, Utf16View value)
{
- VERIFY(value.has_ascii_storage());
+ VERIFY(value.is_ascii());
auto lowercase_value = value.to_ascii_lowercase();
UErrorCode status = U_ZERO_ERROR;
diff --git a/Libraries/LibUnicode/Segmenter.cpp b/Libraries/LibUnicode/Segmenter.cpp
index 0a1218ff257..2c46e73a66f 100644
--- a/Libraries/LibUnicode/Segmenter.cpp
+++ b/Libraries/LibUnicode/Segmenter.cpp
@@ -573,7 +573,11 @@ public:
return;
}
- m_segmented_text = icu::UnicodeString { text.utf16_span().data(), static_cast<i32>(text.length_in_code_units()) };
+ // NB: Latin-1 that is not ASCII is segmented as UTF-16, so that the boundaries are code unit offsets.
+ if (text.has_latin1_storage())
+ m_segmented_text = icu_string(text);
+ else
+ m_segmented_text = icu::UnicodeString { text.utf16_span().data(), static_cast<i32>(text.length_in_code_units()) };
m_segmenter->setText(m_segmented_text.get<icu::UnicodeString>());
}
diff --git a/Libraries/LibWeb/CSS/CSSFunctionRule.cpp b/Libraries/LibWeb/CSS/CSSFunctionRule.cpp
index fb1217774e7..e1b34d69ef0 100644
--- a/Libraries/LibWeb/CSS/CSSFunctionRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSFunctionRule.cpp
@@ -23,8 +23,8 @@ GC_DEFINE_ALLOCATOR(CSSFunctionRule);
static Utf16View parameter_name(Parser::ValueParserFFI::FfiFunctionParameterView const& parameter)
{
- if (parameter.name.ascii)
- return StringView { reinterpret_cast<char const*>(parameter.name.ascii), parameter.name.length };
+ if (parameter.name.latin1)
+ return Utf16View::from_latin1({ parameter.name.latin1, parameter.name.length }, false);
return { reinterpret_cast<char16_t const*>(parameter.name.utf16), parameter.name.length };
}
diff --git a/Libraries/LibWeb/CSS/CSSMarginRule.cpp b/Libraries/LibWeb/CSS/CSSMarginRule.cpp
index c32be850954..848f2bbc191 100644
--- a/Libraries/LibWeb/CSS/CSSMarginRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSMarginRule.cpp
@@ -24,7 +24,7 @@ CSSMarginRule::CSSMarginRule(RustRule rule)
: CSSRule(move(rule))
, m_name([&] {
auto name = native_rule().payload().name;
- auto view = name.ascii ? Utf16View { StringView { reinterpret_cast<char const*>(name.ascii), name.length } } : Utf16View { reinterpret_cast<char16_t const*>(name.utf16), name.length };
+ auto view = name.latin1 ? Utf16View::from_latin1({ name.latin1, name.length }, false) : Utf16View { reinterpret_cast<char16_t const*>(name.utf16), name.length };
return Utf16FlyString::from_utf16(view);
}())
, m_declarations(Parser::ValueParserFFI::rust_declaration_block_retain(native_rule().payload().declarations))
diff --git a/Libraries/LibWeb/CSS/CSSPositionTryRule.cpp b/Libraries/LibWeb/CSS/CSSPositionTryRule.cpp
index 7a852e5c891..a7f3c8e909d 100644
--- a/Libraries/LibWeb/CSS/CSSPositionTryRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSPositionTryRule.cpp
@@ -25,7 +25,7 @@ CSSPositionTryRule::CSSPositionTryRule(RustRule rule)
: CSSRule(move(rule))
, m_name([&] {
auto name = native_rule().payload().name;
- auto view = name.ascii ? Utf16View { StringView { reinterpret_cast<char const*>(name.ascii), name.length } } : Utf16View { reinterpret_cast<char16_t const*>(name.utf16), name.length };
+ auto view = name.latin1 ? Utf16View::from_latin1({ name.latin1, name.length }, false) : Utf16View { reinterpret_cast<char16_t const*>(name.utf16), name.length };
return Utf16FlyString::from_utf16(view);
}())
, m_declarations(Parser::ValueParserFFI::rust_declaration_block_retain(native_rule().payload().declarations))
diff --git a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.h b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.h
index 0771a70af77..124b99beecc 100644
--- a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.h
+++ b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.h
@@ -52,8 +52,8 @@ private:
inline ValueParserFFI::FfiUtf16View ffi_utf16_view(Utf16View view)
{
return {
- .ascii = view.has_ascii_storage() ? reinterpret_cast<u8 const*>(view.ascii_span().data()) : nullptr,
- .utf16 = view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
+ .latin1 = view.has_latin1_storage() ? view.latin1_span().data() : nullptr,
+ .utf16 = view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
.length = view.length_in_code_units(),
};
}
diff --git a/Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp b/Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp
index 8dcd3aea7b7..a201ffa704b 100644
--- a/Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp
+++ b/Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp
@@ -19,8 +19,8 @@ Optional<SelectorList> Parser::parse_as_selector(Utf16View source, SelectorParsi
Optional<Selector::PseudoElementSelector> Parser::parse_as_pseudo_element_selector(Utf16View input_view, PseudoElementParsingMode mode)
{
SelectorFFI::FfiUtf16View input {
- .ascii = input_view.has_ascii_storage() ? reinterpret_cast<u8 const*>(input_view.ascii_span().data()) : nullptr,
- .utf16 = input_view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(input_view.utf16_span().data()),
+ .latin1 = input_view.has_latin1_storage() ? input_view.latin1_span().data() : nullptr,
+ .utf16 = input_view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(input_view.utf16_span().data()),
.length = input_view.length_in_code_units(),
};
auto parsed = SelectorFFI::rust_selector_parse_pseudo_element(input, mode == PseudoElementParsingMode::ComputedStyle);
diff --git a/Libraries/LibWeb/CSS/RustMediaList.h b/Libraries/LibWeb/CSS/RustMediaList.h
index 2125cac3983..972612a7370 100644
--- a/Libraries/LibWeb/CSS/RustMediaList.h
+++ b/Libraries/LibWeb/CSS/RustMediaList.h
@@ -111,8 +111,8 @@ public:
private:
static Parser::ValueParserFFI::FfiUtf16View view(Utf16View text)
{
- return { text.has_ascii_storage() ? reinterpret_cast<u8 const*>(text.ascii_span().data()) : nullptr,
- text.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(text.utf16_span().data()), text.length_in_code_units() };
+ return { text.has_latin1_storage() ? text.latin1_span().data() : nullptr,
+ text.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(text.utf16_span().data()), text.length_in_code_units() };
}
static void copy_text(void* context, u16 const* data, size_t length)
{
diff --git a/Libraries/LibWeb/CSS/RustPageSelectors.h b/Libraries/LibWeb/CSS/RustPageSelectors.h
index f7fa61a00c9..3f7617745b5 100644
--- a/Libraries/LibWeb/CSS/RustPageSelectors.h
+++ b/Libraries/LibWeb/CSS/RustPageSelectors.h
@@ -44,8 +44,8 @@ public:
static Optional<RustPageSelectors> parse(Utf16View text)
{
auto* selectors = Parser::ValueParserFFI::rust_parse_page_selector_list({
- .ascii = text.has_ascii_storage() ? reinterpret_cast<u8 const*>(text.ascii_span().data()) : nullptr,
- .utf16 = text.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(text.utf16_span().data()),
+ .latin1 = text.has_latin1_storage() ? text.latin1_span().data() : nullptr,
+ .utf16 = text.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(text.utf16_span().data()),
.length = text.length_in_code_units(),
});
if (!selectors)
diff --git a/Libraries/LibWeb/CSS/Selector.cpp b/Libraries/LibWeb/CSS/Selector.cpp
index e2541cbb90d..891b94ce04c 100644
--- a/Libraries/LibWeb/CSS/Selector.cpp
+++ b/Libraries/LibWeb/CSS/Selector.cpp
@@ -83,8 +83,8 @@ Optional<SelectorList> parse_selector_list_in_rust(Utf16View input, RustNamespac
{
auto* parsed = SelectorFFI::rust_selector_parse_with_namespace_context(
{
- .ascii = input.has_ascii_storage() ? reinterpret_cast<u8 const*>(input.ascii_span().data()) : nullptr,
- .utf16 = input.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(input.utf16_span().data()),
+ .latin1 = input.has_latin1_storage() ? input.latin1_span().data() : nullptr,
+ .utf16 = input.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(input.utf16_span().data()),
.length = input.length_in_code_units(),
},
namespaces.handle(), is_relative, is_forgiving);
diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cpp
index cd7f205e2ee..7932c0e8d54 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -114,9 +114,9 @@ static Utf16View utf16_view(ComputedValuesFFI::FfiUtf16View view)
{
if (view.length == 0)
return {};
- VERIFY((view.ascii == nullptr) != (view.utf16 == nullptr));
- if (view.ascii)
- return StringView { reinterpret_cast<char const*>(view.ascii), view.length };
+ VERIFY((view.latin1 == nullptr) != (view.utf16 == nullptr));
+ if (view.latin1)
+ return Utf16View::from_latin1({ view.latin1, view.length }, false);
return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
}
diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.h b/Libraries/LibWeb/CSS/StyleEngineBridge.h
index 86904e4bcc2..37dd15421d0 100644
--- a/Libraries/LibWeb/CSS/StyleEngineBridge.h
+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.h
@@ -114,12 +114,12 @@ u64 style_engine_size_query_container_scan_visits(DocumentHost const*, BegunRead
u64 style_engine_ensure_random_base_value(DocumentHost const*, BegunRead const*, StyleNodeID node, ReadonlySpan<u16> name, bool element_shared);
}
-// A view of the code units of a string, ASCII or UTF-16 as it stores them, which the engine copies if it keeps them.
+// A view of the code units of a string, Latin-1 or UTF-16 as it stores them, which the engine copies if it keeps them.
inline FfiUtf16View ffi_utf16_view(Utf16View view)
{
- if (view.has_ascii_storage())
- return { .ascii = reinterpret_cast<u8 const*>(view.ascii_span().data()), .utf16 = nullptr, .length = view.length_in_code_units() };
- return { .ascii = nullptr, .utf16 = reinterpret_cast<u16 const*>(view.utf16_span().data()), .length = view.length_in_code_units() };
+ if (view.has_latin1_storage())
+ return { .latin1 = view.latin1_span().data(), .utf16 = nullptr, .length = view.length_in_code_units() };
+ return { .latin1 = nullptr, .utf16 = reinterpret_cast<u16 const*>(view.utf16_span().data()), .length = view.length_in_code_units() };
}
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
index bd1cd1568cc..81c59b7a1b3 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
@@ -29,8 +29,8 @@ StyleValueFFI::StyleValueData const* ImageStyleValue::make_image_url_data(URL co
auto resource_base_url = style_resource_base_url.has_value() ? style_resource_base_url->to_string() : String {};
auto resource_base_url_bytes = resource_base_url.bytes();
return StyleValueFFI::rust_style_value_create_image(
- { url_string.has_ascii_storage() ? reinterpret_cast<u8 const*>(url_string.ascii_span().data()) : nullptr,
- url_string.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(url_string.utf16_span().data()), url_string.length_in_code_units() },
+ { url_string.has_latin1_storage() ? url_string.latin1_span().data() : nullptr,
+ url_string.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(url_string.utf16_span().data()), url_string.length_in_code_units() },
to_underlying(url.type()), modifiers.data(), modifiers.size(),
{ resource_base_url_bytes.data(), nullptr, resource_base_url_bytes.size() }, style_resource_base_url.has_value());
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h
index 8174c4690f5..f6efe29a86b 100644
--- a/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h
@@ -15,8 +15,8 @@ namespace Web::CSS {
inline Utf16View url_text_from_rust_data(StyleValueFFI::RetainedString const& string)
{
auto view = StyleValueFFI::rust_css_url_text_view(&string);
- if (view.ascii)
- return Utf16View { StringView { reinterpret_cast<char const*>(view.ascii), view.length } };
+ if (view.latin1)
+ return Utf16View::from_latin1({ view.latin1, view.length }, false);
return Utf16View { reinterpret_cast<char16_t const*>(view.utf16), view.length };
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp
index 453402d0113..b3b4f4e11fa 100644
--- a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp
@@ -18,8 +18,8 @@ static StyleValueFFI::StyleValueData const* create_rust_style_value_from_source(
{
auto token_source_view = token_source.utf16_view();
return StyleValueFFI::rust_style_value_create_unresolved_from_source(
- token_source_view.has_ascii_storage() ? reinterpret_cast<u8 const*>(token_source_view.ascii_span().data()) : nullptr,
- token_source_view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(token_source_view.utf16_span().data()),
+ token_source_view.has_latin1_storage() ? token_source_view.latin1_span().data() : nullptr,
+ token_source_view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(token_source_view.utf16_span().data()),
token_source_view.length_in_code_units(),
to_underlying(source_text_mode),
substitution_presence.attr,
diff --git a/Libraries/LibWeb/CSS/SyntaxHighlighter/SyntaxHighlighter.cpp b/Libraries/LibWeb/CSS/SyntaxHighlighter/SyntaxHighlighter.cpp
index f881420cfce..dc34187a18d 100644
--- a/Libraries/LibWeb/CSS/SyntaxHighlighter/SyntaxHighlighter.cpp
+++ b/Libraries/LibWeb/CSS/SyntaxHighlighter/SyntaxHighlighter.cpp
@@ -39,8 +39,8 @@ void SyntaxHighlighter::rehighlight(Palette const& palette)
Vector<CSS::Parser::FFI::CssSyntaxToken> tokens;
tokens.ensure_capacity((input_view.length_in_code_units() / 2) + 1);
CSS::Parser::FFI::rust_css_tokenize_for_syntax_highlighting(
- input_view.has_ascii_storage() ? reinterpret_cast<u8 const*>(input_view.ascii_span().data()) : nullptr,
- input_view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(input_view.utf16_span().data()),
+ input_view.has_latin1_storage() ? input_view.latin1_span().data() : nullptr,
+ input_view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(input_view.utf16_span().data()),
input_view.length_in_code_units(),
&tokens,
[](void* raw_tokens, CSS::Parser::FFI::CssSyntaxToken const* token) {
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index ead82656e12..107757f1cd6 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -293,8 +293,8 @@ namespace Web::DOM {
static CSS::ComputedValuesFFI::FfiUtf16View ffi_utf16_view(Utf16View view)
{
return {
- .ascii = view.has_ascii_storage() ? reinterpret_cast<u8 const*>(view.ascii_span().data()) : nullptr,
- .utf16 = view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
+ .latin1 = view.has_latin1_storage() ? view.latin1_span().data() : nullptr,
+ .utf16 = view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
.length = view.length_in_code_units(),
};
}
@@ -10497,8 +10497,8 @@ Vector<GC::Root<Range>> Document::find_matching_text(Utf16View query, CaseSensit
};
Search search { *this, {} };
auto query_view = Layout::RustFFI::FfiUtf16View {
- .ascii = query.has_ascii_storage() ? reinterpret_cast<u8 const*>(query.ascii_span().data()) : nullptr,
- .utf16 = query.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(query.utf16_span().data()),
+ .latin1 = query.has_latin1_storage() ? query.latin1_span().data() : nullptr,
+ .utf16 = query.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(query.utf16_span().data()),
.length = query.length_in_code_units(),
};
Layout::RustFFI::layout_script_find_matching_text(
diff --git a/Libraries/LibWeb/DOM/SelectorQuery.cpp b/Libraries/LibWeb/DOM/SelectorQuery.cpp
index 0be6e3e411b..679e12f60ed 100644
--- a/Libraries/LibWeb/DOM/SelectorQuery.cpp
+++ b/Libraries/LibWeb/DOM/SelectorQuery.cpp
@@ -129,8 +129,8 @@ void const* node_to_ffi(Node const* node)
CSS::SelectorFFI::FfiUtf16View utf16_view_to_ffi(Utf16View view)
{
return {
- .ascii = view.has_ascii_storage() ? reinterpret_cast<u8 const*>(view.ascii_span().data()) : nullptr,
- .utf16 = view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
+ .latin1 = view.has_latin1_storage() ? view.latin1_span().data() : nullptr,
+ .utf16 = view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
.length = view.length_in_code_units(),
};
}
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 1eef3eda258..67f580517f8 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -1747,6 +1747,14 @@ static decltype(auto) with_code_unit_span(Utf16View input, Callback&& callback)
{
if (input.has_ascii_storage())
return callback(ReadonlySpan<char> { input.ascii_span().data(), input.length_in_code_units() });
+ // NB: The fast path makes UTF-8 strings of one-byte spans, so Latin-1 is parsed as UTF-16.
+ if (input.has_latin1_storage()) {
+ Vector<char16_t> code_units;
+ code_units.ensure_capacity(input.length_in_code_units());
+ for (auto byte : input.latin1_span())
+ code_units.unchecked_append(byte);
+ return callback(ReadonlySpan<char16_t> { code_units.data(), code_units.size() });
+ }
return callback(input.utf16_span());
}
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp b/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp
index 790234f0743..4cd9c2b62a4 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp
@@ -20,8 +20,8 @@ static ReadonlySpan<u16> utf16_units(Utf16View input)
static RustFfiTokenizerHandle* create_tokenizer_from_utf16(Utf16View input)
{
- if (input.has_ascii_storage())
- return rust_html_tokenizer_create_from_ascii(input.ascii_bytes());
+ if (input.has_latin1_storage())
+ return rust_html_tokenizer_create_from_latin1(input.latin1_span());
return rust_html_tokenizer_create_from_utf16(utf16_units(input));
}
@@ -173,8 +173,8 @@ void HTMLTokenizer::append_to_input_stream(Utf16View input)
if (input.is_empty())
return;
- if (input.has_ascii_storage()) {
- rust_html_tokenizer_append_ascii_input(m_tokenizer, input.ascii_bytes());
+ if (input.has_latin1_storage()) {
+ rust_html_tokenizer_append_latin1_input(m_tokenizer, input.latin1_span());
return;
}
rust_html_tokenizer_append_utf16_input(m_tokenizer, utf16_units(input));
@@ -188,8 +188,8 @@ void HTMLTokenizer::close_input_stream()
void HTMLTokenizer::insert_input_at_insertion_point(Utf16View input)
{
- if (input.has_ascii_storage()) {
- rust_html_tokenizer_insert_ascii_input(m_tokenizer, input.ascii_bytes());
+ if (input.has_latin1_storage()) {
+ rust_html_tokenizer_insert_latin1_input(m_tokenizer, input.latin1_span());
return;
}
rust_html_tokenizer_insert_utf16_input(m_tokenizer, utf16_units(input));
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs
index 9f5470cf41a..6f19ebd778c 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs
@@ -135,7 +135,7 @@ pub extern "C" fn rust_html_tokenizer_create_from_utf16(input: ak::Span<'_, u16>
/// Create a new Rust HTML tokenizer directly from an ASCII byte buffer.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_html_tokenizer_create_from_ascii(input: ak::Span<'_, u8>) -> *mut RustFfiTokenizerHandle {
+pub extern "C" fn rust_html_tokenizer_create_from_latin1(input: ak::Span<'_, u8>) -> *mut RustFfiTokenizerHandle {
let code_units = input.as_slice().iter().map(|byte| u16::from(*byte)).collect();
make_handle(HtmlTokenizer::new(code_units))
@@ -336,7 +336,7 @@ pub extern "C" fn rust_html_tokenizer_insert_utf16_input(
/// Insert ASCII input at the current insertion point.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_html_tokenizer_insert_ascii_input(
+pub extern "C" fn rust_html_tokenizer_insert_latin1_input(
handle: Option<&mut RustFfiTokenizerHandle>,
input: ak::Span<'_, u8>,
) {
@@ -344,7 +344,7 @@ pub extern "C" fn rust_html_tokenizer_insert_ascii_input(
return;
};
let input = input.as_slice();
- handle.tokenizer.insert_ascii_input_at_insertion_point(input);
+ handle.tokenizer.insert_latin1_input_at_insertion_point(input);
}
/// Append UTF-16 input to the tokenizer input stream.
@@ -362,7 +362,7 @@ pub extern "C" fn rust_html_tokenizer_append_utf16_input(
/// Append ASCII input to the tokenizer input stream.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_html_tokenizer_append_ascii_input(
+pub extern "C" fn rust_html_tokenizer_append_latin1_input(
handle: Option<&mut RustFfiTokenizerHandle>,
input: ak::Span<'_, u8>,
) {
@@ -370,7 +370,7 @@ pub extern "C" fn rust_html_tokenizer_append_ascii_input(
return;
};
let input = input.as_slice();
- handle.tokenizer.append_ascii_input(input);
+ handle.tokenizer.append_latin1_input(input);
}
/// Get the tokenizer input that has not been consumed yet.
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs
index adf3f998ff9..c0fdd38ed19 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs
@@ -72,21 +72,19 @@ pub struct RustFfiPreloadScannerEntry {
pub media_len: usize,
}
-/// Scan pending parser input for resources the speculative HTML parser can fetch.
+/// Scan pending Latin-1 parser input for resources the speculative HTML parser can fetch.
///
/// # Safety
-/// `input` must be valid UTF-8. `callback` must not retain pointers from the provided entry beyond the callback
-/// invocation.
+/// `callback` must not retain pointers from the provided entry beyond the callback invocation.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_html_preload_scanner_scan(
+pub unsafe extern "C" fn rust_html_preload_scanner_scan_latin1(
input: ak::Span<'_, u8>,
scripting_enabled: bool,
ctx: *mut c_void,
callback: unsafe extern "C" fn(ctx: *mut c_void, entry: *const RustFfiPreloadScannerEntry) -> bool,
) {
- let input = input.as_slice();
-
- scan(input, scripting_enabled, |entry| unsafe {
+ let code_units = input.as_slice().iter().map(|&byte| u16::from(byte)).collect();
+ scan_code_units(code_units, scripting_enabled, &mut |entry| unsafe {
callback(ctx, &raw const *entry)
});
}
@@ -109,6 +107,7 @@ pub unsafe extern "C" fn rust_html_preload_scanner_scan_utf16(
});
}
+#[cfg(test)]
pub(crate) fn scan(
input: &[u8],
scripting_enabled: bool,
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
index ea8218dd94e..670f54f9689 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
@@ -405,7 +405,7 @@ impl HtmlTokenizer {
self.input.extend_from_slice(code_units);
}
- pub fn append_ascii_input(&mut self, bytes: &[u8]) {
+ pub fn append_latin1_input(&mut self, bytes: &[u8]) {
self.input.extend(bytes.iter().map(|byte| u16::from(*byte)));
}
@@ -424,7 +424,7 @@ impl HtmlTokenizer {
}
}
- pub fn insert_ascii_input_at_insertion_point(&mut self, bytes: &[u8]) {
+ pub fn insert_latin1_input_at_insertion_point(&mut self, bytes: &[u8]) {
if let Some(ip) = self.insertion_point {
let ip = ip.min(self.input.len());
self.input.splice(ip..ip, bytes.iter().map(|byte| u16::from(*byte)));
diff --git a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
index 94489704ef6..854f97abf4d 100644
--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
@@ -79,9 +79,8 @@ void SpeculativeHTMLParser::run()
auto scripting_enabled = m_scripting_mode != ParserScriptingMode::Disabled;
auto input = m_input.utf16_view();
- if (input.has_ascii_storage()) {
- auto bytes = input.ascii_bytes();
- rust_html_preload_scanner_scan(bytes, scripting_enabled, this, scanner_callback);
+ if (input.has_latin1_storage()) {
+ rust_html_preload_scanner_scan_latin1(input.latin1_span(), scripting_enabled, this, scanner_callback);
} else {
auto code_units = input.utf16_span();
rust_html_preload_scanner_scan_utf16({ reinterpret_cast<u16 const*>(code_units.data()), code_units.size() }, scripting_enabled, this, scanner_callback);
diff --git a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp
index f177bbcb8d5..8ba89985284 100644
--- a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp
+++ b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp
@@ -454,8 +454,8 @@ Optional<Vector<CSS::LengthPercentage>> IntersectionObserver::parse_a_margin(Str
auto source = Utf16String::from_utf8(margin_string);
auto source_view = source.utf16_view();
CSS::Parser::ValueParserFFI::FfiUtf16View ffi_source {
- .ascii = source_view.has_ascii_storage() ? reinterpret_cast<u8 const*>(source_view.ascii_span().data()) : nullptr,
- .utf16 = source_view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(source_view.utf16_span().data()),
+ .latin1 = source_view.has_latin1_storage() ? source_view.latin1_span().data() : nullptr,
+ .utf16 = source_view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(source_view.utf16_span().data()),
.length = source_view.length_in_code_units(),
};
auto visit = [](void* context, u8 type, double value, u16 const* unit, size_t unit_length) {
diff --git a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
index 4c5d224bc9a..db5ed14c9c4 100644
--- a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
+++ b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
@@ -131,12 +131,12 @@ impl Default for TokenizerInput<'_> {
impl TokenizerInput<'_> {
/// # Safety
/// Exactly one non-empty input pointer must identify `length` readable units.
- pub(crate) unsafe fn from_raw_parts(ascii: *const u8, utf16: *const u16, length: usize) -> Option<Self> {
+ pub(crate) unsafe fn from_raw_parts(latin1: *const u8, utf16: *const u16, length: usize) -> Option<Self> {
if length == 0 {
return Some(Self::Latin1(&[]));
}
- match (ascii.is_null(), utf16.is_null()) {
- (false, true) => Some(Self::Latin1(unsafe { ak::slice_from_raw_parts(ascii, length) })),
+ match (latin1.is_null(), utf16.is_null()) {
+ (false, true) => Some(Self::Latin1(unsafe { ak::slice_from_raw_parts(latin1, length) })),
(true, false) => Some(Self::Utf16(unsafe { ak::slice_from_raw_parts(utf16, length) })),
_ => None,
}
@@ -503,21 +503,21 @@ pub(crate) enum ParserSource {
#[derive(Debug)]
pub(crate) enum SourceStorage {
- Ascii(Box<[u8]>),
+ Latin1(Box<[u8]>),
Utf16(Box<[u16]>),
}
impl SourceStorage {
fn from_input(input: TokenizerInput<'_>) -> Self {
match input {
- TokenizerInput::Latin1(units) => Self::Ascii(units.into()),
+ TokenizerInput::Latin1(units) => Self::Latin1(units.into()),
TokenizerInput::Utf16(units) => Self::Utf16(units.into()),
}
}
fn as_input(&self) -> TokenizerInput<'_> {
match self {
- Self::Ascii(units) => TokenizerInput::Latin1(units),
+ Self::Latin1(units) => TokenizerInput::Latin1(units),
Self::Utf16(units) => TokenizerInput::Utf16(units),
}
}
@@ -550,7 +550,7 @@ impl TextDetacher {
Arc::clone(storage)
} else {
Arc::new(match storage.as_ref() {
- SourceStorage::Ascii(units) => SourceStorage::Ascii(units[span.clone()].into()),
+ SourceStorage::Latin1(units) => SourceStorage::Latin1(units[span.clone()].into()),
SourceStorage::Utf16(units) => SourceStorage::Utf16(units[span.clone()].into()),
})
});
@@ -660,7 +660,7 @@ impl ParserSource {
Self::Empty => ParserSourceIter::Empty,
Self::Owned(source) => ParserSourceIter::Owned(source.iter()),
Self::Shared { storage, range } => match storage.as_ref() {
- SourceStorage::Ascii(source) => ParserSourceIter::Ascii(source[range.clone()].iter()),
+ SourceStorage::Latin1(source) => ParserSourceIter::Ascii(source[range.clone()].iter()),
SourceStorage::Utf16(source) => ParserSourceIter::Utf16(source[range.clone()].iter()),
},
}
@@ -671,7 +671,7 @@ impl ParserSource {
Self::Empty => {}
Self::Owned(source) => target.extend_from_slice(source),
Self::Shared { storage, range } => match storage.as_ref() {
- SourceStorage::Ascii(source) => target.extend(source[range.clone()].iter().copied().map(u16::from)),
+ SourceStorage::Latin1(source) => target.extend(source[range.clone()].iter().copied().map(u16::from)),
SourceStorage::Utf16(source) => target.extend_from_slice(&source[range.clone()]),
},
}
@@ -2456,7 +2456,7 @@ mod tests {
let ParserSource::Shared { storage, range } = &ascii_tokens[0].source else {
panic!("token source should use shared storage");
};
- assert!(matches!(storage.as_ref(), SourceStorage::Ascii(_)));
+ assert!(matches!(storage.as_ref(), SourceStorage::Latin1(_)));
assert_eq!(range.clone(), 0..5);
let utf16 = "café".encode_utf16().collect::<Vec<_>>();
diff --git a/Libraries/LibWeb/Rust/src/css/ffi_support.rs b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
index f70f7dea1db..ae02641bbe9 100644
--- a/Libraries/LibWeb/Rust/src/css/ffi_support.rs
+++ b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
@@ -162,14 +162,14 @@ impl<T> Drop for OwnedBox<T> {
}
}
-/// Text borrowed for `'a`, as ASCII bytes or UTF-16 code units.
+/// Text borrowed for `'a`, as Latin-1 bytes or UTF-16 code units.
///
/// Rust builds a view only from a borrowed slice, and C++ hands one over under the same contract: exactly one non-empty
/// pointer identifies `length` units that stay readable for `'a`.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct FfiUtf16View<'a> {
- ascii: *const u8,
+ latin1: *const u8,
utf16: *const u16,
length: usize,
units: PhantomData<TokenizerInput<'a>>,
@@ -178,7 +178,7 @@ pub struct FfiUtf16View<'a> {
impl Default for FfiUtf16View<'_> {
fn default() -> Self {
Self {
- ascii: std::ptr::null(),
+ latin1: std::ptr::null(),
utf16: std::ptr::null(),
length: 0,
units: PhantomData,
@@ -187,9 +187,9 @@ impl Default for FfiUtf16View<'_> {
}
impl<'a> FfiUtf16View<'a> {
- pub(crate) fn from_ascii(units: &'a [u8]) -> Self {
+ pub(crate) fn from_latin1(units: &'a [u8]) -> Self {
Self {
- ascii: units.as_ptr(),
+ latin1: units.as_ptr(),
length: units.len(),
..Self::default()
}
@@ -205,7 +205,7 @@ impl<'a> FfiUtf16View<'a> {
pub(crate) fn from_input(input: TokenizerInput<'a>) -> Self {
match input {
- TokenizerInput::Latin1(units) => Self::from_ascii(units),
+ TokenizerInput::Latin1(units) => Self::from_latin1(units),
TokenizerInput::Utf16(units) => Self::from_utf16(units),
}
}
@@ -217,7 +217,7 @@ impl<'a> FfiUtf16View<'a> {
/// The viewed units, or none for a view that names both or neither kind of storage.
pub(crate) fn units(self) -> Option<TokenizerInput<'a>> {
// SAFETY: The view's contract keeps exactly one non-empty pointer readable for `length` units during `'a`.
- unsafe { TokenizerInput::from_raw_parts(self.ascii, self.utf16, self.length) }
+ unsafe { TokenizerInput::from_raw_parts(self.latin1, self.utf16, self.length) }
}
pub(crate) fn to_utf16(self) -> Option<Vec<u16>> {
diff --git a/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs b/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs
index 67935991388..1e81dc8a847 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs
@@ -257,15 +257,15 @@ impl TextDigest {
.each_ref()
.map(RandomState::build_hasher);
let mut write = |bytes: &[u8]| hashers.iter_mut().for_each(|hasher| hasher.write(bytes));
- // NB: Equal texts hash equally whether they arrive as ASCII or as UTF-16, so UTF-16 text that is all ASCII is
- // hashed as ASCII. The first byte keeps the two forms apart otherwise.
+ // NB: Equal texts hash equally whether they arrive as Latin-1 or as UTF-16, so UTF-16 text that is all Latin-1 is
+ // hashed as Latin-1. The first byte keeps the two forms apart otherwise.
let mut chunk = [0u8; CHUNK_BYTES];
match source {
TokenizerInput::Latin1(units) => {
write(&[0]);
write(units);
}
- TokenizerInput::Utf16(units) if units.iter().all(|&unit| unit < 0x80) => {
+ TokenizerInput::Utf16(units) if units.iter().all(|&unit| unit <= 0xFF) => {
write(&[0]);
for part in units.chunks(CHUNK_BYTES) {
for (byte, &unit) in chunk.iter_mut().zip(part) {
diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
index e526b8b90d0..02e73e2ab83 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
@@ -7855,7 +7855,7 @@ mod tests {
kind: FfiValueParsingContextKind::Function,
value: 0,
secondary_value: 0,
- name: FfiUtf16View::from_ascii(function_name),
+ name: FfiUtf16View::from_latin1(function_name),
}));
let mut parse_context = context();
parse_context.value_contexts = ak::Span::new(&function_contexts);
diff --git a/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rs b/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rs
index 6486c15c644..b8eb9d093ca 100644
--- a/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rs
@@ -132,13 +132,13 @@ fn length_registry() -> Arc<CustomPropertyRegistry> {
value: 0.0,
unit: crate::css::style_compute::px_length_unit(),
});
- let syntax = rust_parse_syntax(FfiUtf16View::from_ascii(b"<length>"), false);
+ let syntax = rust_parse_syntax(FfiUtf16View::from_latin1(b"<length>"), false);
let registration = FfiCustomPropertyRegistration {
- name: FfiUtf16View::from_ascii(b"--width"),
+ name: FfiUtf16View::from_latin1(b"--width"),
syntax,
inherits: false,
has_initial_value: true,
- initial_value: FfiUtf16View::from_ascii(b"0px"),
+ initial_value: FfiUtf16View::from_latin1(b"0px"),
computed_initial_value: initial.pointer().cast(),
};
let context = FfiCustomPropertyRegistryContext {
diff --git a/Libraries/LibWeb/Rust/src/css/style_value.rs b/Libraries/LibWeb/Rust/src/css/style_value.rs
index fccf6303d3b..b700d2abfd9 100644
--- a/Libraries/LibWeb/Rust/src/css/style_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_value.rs
@@ -733,12 +733,9 @@ impl RetainedString {
fn from_units(units: TokenizerInput<'_>) -> Self {
use crate::css::css_tokenizer::SourceStorage;
Self::from_storage(match units {
- TokenizerInput::Latin1(bytes) => {
- assert!(bytes.is_ascii());
- SourceStorage::Ascii(bytes.into())
- }
+ TokenizerInput::Latin1(bytes) => SourceStorage::Latin1(bytes.into()),
TokenizerInput::Utf16(units) if units.iter().all(|unit| *unit <= 0x7f) => {
- SourceStorage::Ascii(units.iter().map(|unit| *unit as u8).collect())
+ SourceStorage::Latin1(units.iter().map(|unit| *unit as u8).collect())
}
TokenizerInput::Utf16(units) => SourceStorage::Utf16(units.into()),
})
@@ -746,7 +743,7 @@ impl RetainedString {
pub(crate) fn from_ascii(string: String) -> Self {
assert!(string.is_ascii());
- Self::from_storage(crate::css::css_tokenizer::SourceStorage::Ascii(
+ Self::from_storage(crate::css::css_tokenizer::SourceStorage::Latin1(
string.into_bytes().into_boxed_slice(),
))
}
@@ -761,16 +758,18 @@ impl RetainedString {
pub(crate) fn units(&self) -> TokenizerInput<'_> {
use crate::css::css_tokenizer::SourceStorage;
match unsafe { &*self.storage.cast::<SourceStorage>() } {
- SourceStorage::Ascii(bytes) => TokenizerInput::Latin1(bytes),
+ SourceStorage::Latin1(bytes) => TokenizerInput::Latin1(bytes),
SourceStorage::Utf16(units) => TokenizerInput::Utf16(units),
}
}
pub(crate) fn url_input(&self) -> liburl_rust::url::UrlInput<'_> {
match self.units() {
- TokenizerInput::Latin1(bytes) => {
+ // SAFETY: ASCII is UTF-8.
+ TokenizerInput::Latin1(bytes) if bytes.is_ascii() => {
liburl_rust::url::UrlInput::Utf8(unsafe { std::str::from_utf8_unchecked(bytes) })
}
+ TokenizerInput::Latin1(bytes) => liburl_rust::url::UrlInput::Latin1(bytes),
TokenizerInput::Utf16(units) => liburl_rust::url::UrlInput::Utf16(units),
}
}
diff --git a/Libraries/LibWeb/SVG/AttributeParsing.cpp b/Libraries/LibWeb/SVG/AttributeParsing.cpp
index 0d4440438a6..ec61cc3d735 100644
--- a/Libraries/LibWeb/SVG/AttributeParsing.cpp
+++ b/Libraries/LibWeb/SVG/AttributeParsing.cpp
@@ -17,8 +17,8 @@ namespace Web::SVG {
static RustFFI::FfiUtf16View ffi_svg_input(Utf16View input)
{
return {
- .ascii = input.has_ascii_storage() ? reinterpret_cast<u8 const*>(input.ascii_span().data()) : nullptr,
- .utf16 = input.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(input.utf16_span().data()),
+ .latin1 = input.has_latin1_storage() ? input.latin1_span().data() : nullptr,
+ .utf16 = input.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(input.utf16_span().data()),
.length = input.length_in_code_units(),
};
}
diff --git a/Libraries/LibWeb/SVG/Path.cpp b/Libraries/LibWeb/SVG/Path.cpp
index 4331c20c2df..b5460dc5023 100644
--- a/Libraries/LibWeb/SVG/Path.cpp
+++ b/Libraries/LibWeb/SVG/Path.cpp
@@ -17,8 +17,8 @@ namespace Web::SVG {
static RustFFI::FfiUtf16View ffi_svg_input(Utf16View input)
{
return {
- .ascii = input.has_ascii_storage() ? reinterpret_cast<u8 const*>(input.ascii_span().data()) : nullptr,
- .utf16 = input.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(input.utf16_span().data()),
+ .latin1 = input.has_latin1_storage() ? input.latin1_span().data() : nullptr,
+ .utf16 = input.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(input.utf16_span().data()),
.length = input.length_in_code_units(),
};
}
diff --git a/Libraries/LibWeb/SVG/SVGFilterElement.cpp b/Libraries/LibWeb/SVG/SVGFilterElement.cpp
index 0d0bcd9c0c9..04c6c3fe6b3 100644
--- a/Libraries/LibWeb/SVG/SVGFilterElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGFilterElement.cpp
@@ -57,8 +57,8 @@ namespace {
Layout::RustFFI::FfiUtf16View view_of(Utf16View view)
{
return {
- .ascii = view.has_ascii_storage() ? reinterpret_cast<u8 const*>(view.ascii_span().data()) : nullptr,
- .utf16 = view.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
+ .latin1 = view.has_latin1_storage() ? view.latin1_span().data() : nullptr,
+ .utf16 = view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(view.utf16_span().data()),
.length = view.length_in_code_units(),
};
}
diff --git a/Libraries/LibWebCommon/MimeSniff/MimeType.cpp b/Libraries/LibWebCommon/MimeSniff/MimeType.cpp
index 374070ab487..fc82435fca0 100644
--- a/Libraries/LibWebCommon/MimeSniff/MimeType.cpp
+++ b/Libraries/LibWebCommon/MimeSniff/MimeType.cpp
@@ -18,16 +18,16 @@ namespace Web::MimeSniff {
static FFI::FfiStringInput ffi_string_input(StringView string)
{
- return { reinterpret_cast<u8 const*>(string.characters_without_null_termination()), nullptr, string.length() };
+ return { reinterpret_cast<u8 const*>(string.characters_without_null_termination()), nullptr, nullptr, string.length() };
}
static FFI::FfiStringInput ffi_string_input(Utf16View string)
{
- return {
- string.has_ascii_storage() ? reinterpret_cast<u8 const*>(string.ascii_span().data()) : nullptr,
- string.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(string.utf16_span().data()),
- string.length_in_code_units(),
- };
+ if (string.has_ascii_storage())
+ return { string.ascii_bytes().data(), nullptr, nullptr, string.length_in_code_units() };
+ if (string.has_latin1_storage())
+ return { nullptr, string.latin1_span().data(), nullptr, string.length_in_code_units() };
+ return { nullptr, nullptr, reinterpret_cast<u16 const*>(string.utf16_span().data()), string.length_in_code_units() };
}
static String string_from_ffi(ReadonlyBytes bytes)
diff --git a/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs b/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs
index c2034757dc8..403b0ae05e4 100644
--- a/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs
+++ b/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs
@@ -21,6 +21,7 @@ use crate::rust_panic::abort_on_panic;
#[derive(Clone, Copy)]
pub struct FfiStringInput {
pub utf8: *const u8,
+ pub latin1: *const u8,
pub utf16: *const u16,
pub length: usize,
}
@@ -45,6 +46,11 @@ impl FfiStringInput {
.collect(),
);
}
+ if !self.latin1.is_null() {
+ // SAFETY: The caller lends `length` Latin-1 code units.
+ let units = unsafe { ak::slice_from_raw_parts(self.latin1, self.length) };
+ return Some(units.iter().map(|&unit| char::from(unit)).collect());
+ }
// SAFETY: The caller lends `length` bytes.
let bytes = unsafe { ak::slice_from_raw_parts(self.utf8, self.length) };
Some(std::str::from_utf8(bytes).ok()?.chars().collect())
diff --git a/Tests/AK/TestUtf16String.cpp b/Tests/AK/TestUtf16String.cpp
index d61a2325e0b..fc74e9cc367 100644
--- a/Tests/AK/TestUtf16String.cpp
+++ b/Tests/AK/TestUtf16String.cpp
@@ -11,6 +11,7 @@
#include <AK/Enumerate.h>
#include <AK/MemoryStream.h>
#include <AK/StringBuilder.h>
+#include <AK/Utf16FlyString.h>
#include <AK/Utf16String.h>
static_assert(AK::Concepts::HashCompatible<Utf16String, Utf16View>);
@@ -1352,3 +1353,31 @@ TEST_CASE(utf16_string_builder_clear_resets_ascii_flag)
EXPECT_EQ(second.code_unit_at(0), 0x000A); // Must be newline, not null.
EXPECT_EQ(second.code_unit_at(1), 0x0020);
}
+
+TEST_CASE(latin1_storage)
+{
+ // "crème brûlée", with each code unit as one byte.
+ 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);
+
+ 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_EQ(string, utf16_string);
+ EXPECT_EQ(string.hash(), utf16_string.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);
+
+ Utf16StringBuilder builder;
+ builder.append(string);
+ EXPECT_EQ(builder.to_string(), utf16_string);
+
+ // Latin-1 storage whose code units are all ASCII is ASCII storage.
+ static constexpr u8 ascii_bytes[] = { 'c', 'r', 'e', 'm', 'e', ' ', 'b', 'r', 'u', 'l', 'e', 'e' };
+ auto ascii_string = Utf16String::from_utf16(Utf16View::from_latin1(ascii_bytes, false));
+ EXPECT(ascii_string.has_long_ascii_storage());
+}
diff --git a/Tests/AK/TestUtf16View.cpp b/Tests/AK/TestUtf16View.cpp
index 3e23af39c02..225923582c3 100644
--- a/Tests/AK/TestUtf16View.cpp
+++ b/Tests/AK/TestUtf16View.cpp
@@ -997,3 +997,45 @@ TEST_CASE(previous_code_point_at)
EXPECT_EQ(index, 0u);
}
}
+
+TEST_CASE(latin1_storage)
+{
+ // "café", with U+00E9 as one byte.
+ static constexpr u8 bytes[] = { 'c', 'a', 'f', 0xE9 };
+ auto view = Utf16View::from_latin1(bytes, false);
+
+ EXPECT(view.has_latin1_storage());
+ EXPECT(!view.has_ascii_storage());
+ EXPECT(!view.is_ascii());
+ EXPECT(view.validate());
+ EXPECT_EQ(view.length_in_code_units(), 4uz);
+ EXPECT_EQ(view.length_in_code_points(), 4uz);
+ EXPECT_EQ(view.code_unit_at(3), u'é');
+ EXPECT_EQ(view.code_point_at(3), 0xE9u);
+
+ EXPECT_EQ(view, u"café"sv);
+ EXPECT_EQ(view.hash(), u"café"sv.hash());
+ EXPECT_EQ(view.ascii_case_insensitive_hash(), u"CAFé"sv.ascii_case_insensitive_hash());
+ EXPECT(view == "café"sv);
+ EXPECT_EQ(MUST(view.to_utf8()), "café"sv);
+
+ EXPECT_EQ(view.find_code_unit_offset(u'é'), 3uz);
+ EXPECT_EQ(view.find_last_code_point_offset(0xE9), 3uz);
+ EXPECT(!view.find_code_unit_offset(u'ĩ').has_value());
+
+ auto prefix = view.substring_view(0, 3);
+ EXPECT(!prefix.has_ascii_storage());
+ EXPECT(prefix.is_ascii());
+ EXPECT_EQ(StringView { prefix.ascii_bytes() }, "caf"sv);
+}
+
+TEST_CASE(latin1_storage_is_not_utf8)
+{
+ // "é", whose two bytes are the UTF-8 encoding of "é".
+ static constexpr u8 bytes[] = { 0xC3, 0xA9 };
+ auto view = Utf16View::from_latin1(bytes, false);
+
+ EXPECT(view != "é"sv);
+ EXPECT(view == "é"sv);
+ EXPECT_EQ(MUST(view.to_utf8()), "é"sv);
+}