Truly independent web browser
LibWeb: Stop making UTF-8 strings in the HTML parser
Andreas Kling495e30a01a83
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cppindex 911e15960ac..5cd44f1edc6 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp@@ -17,6 +17,7 @@#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>#include <LibWeb/HTML/Parser/RustFFI.h>+#include <LibWeb/HTML/Parser/RustUtf16View.h>#include <LibWeb/HTMLTokenizerRustFFI.h>#include <LibWebCommon/Infra/CharacterTypes.h>@@ -626,10 +627,19 @@ EncodingDeclarationPrescan::~EncodingDeclarationPrescan()EncodingDeclarationPrescan::Result EncodingDeclarationPrescan::scan(ReadonlyBytes bytes, bool input_complete){auto result = rust_html_meta_charset_scanner_scan(m_scanner, bytes, input_complete, &m_encoding,- [](void* context, u8 const* value, size_t value_length, bool is_content) {- StringView value_view { value, value_length };+ [](void* context, RustFfiHtmlUtf16View value, bool is_content) {auto& encoding = *static_cast<Optional<StringView>*>(context);- encoding = is_content ? extract_character_encoding_from_meta_element(ByteString { value_view }) : TextCodec::get_standardized_encoding(value_view);+ // NB: The scanner reads bytes that haven't been decoded yet, so the value is a byte per code unit unless+ // a character reference put something else in it. An encoding label with such a code unit in it names+ // no encoding, but a content attribute may still have a charset next to one.+ auto value_view = utf16_view_from_ffi(value);+ if (is_content) {+ encoding = extract_character_encoding_from_meta_element(MUST(value_view.to_byte_string()));+ } else if (value_view.has_latin1_storage()) {+ encoding = TextCodec::get_standardized_encoding(StringView { value_view.latin1_span() });+ } else {+ encoding = {};+ }return encoding.has_value();});diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cppindex 1195d39f207..799035054f6 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp@@ -56,6 +56,7 @@#include <LibWeb/HTML/Parser/HTMLParser.h>#include <LibWeb/HTML/Parser/HTMLToken.h>#include <LibWeb/HTML/Parser/ParserScriptingMode.h>+#include <LibWeb/HTML/Parser/RustUtf16View.h>#include <LibWeb/HTML/Parser/SpeculativeHTMLParser.h>#include <LibWeb/HTML/PolicyContainers.h>#include <LibWeb/HTML/PreloadEntry.h>@@ -152,20 +153,6 @@ static Utf16String utf16_string_from_span(ReadonlySpan<char16_t> utf16, IsKnownTreturn utf16_string_from_span(utf16);}-static Utf16String utf16_string_from_ffi(u16 const* ptr, size_t len)-{- if (!ptr)- return {};- return utf16_string_from_span(ReadonlySpan<char16_t> { reinterpret_cast<char16_t const*>(ptr), len });-}--static Utf16String utf8_string_from_ffi(u8 const* ptr, size_t len)-{- if (!ptr)- return {};- return utf16_string_from_span(ReadonlySpan<char> { reinterpret_cast<char const*>(ptr), len });-}-static constexpr size_t newline_then_spaces_table_size = 64;static Utf16String const& newline_then_spaces_string(size_t length)@@ -215,11 +202,10 @@ extern "C" size_t ladybird_html_parser_document_node(void*);extern "C" size_t ladybird_html_parser_document_html_element(void*);extern "C" void ladybird_html_parser_set_document_quirks_mode(void*, RustFfiHtmlQuirksMode);extern "C" bool ladybird_html_parser_document_is_iframe_srcdoc_document(void*);-extern "C" size_t ladybird_html_parser_create_document_type(void*, u16 const*, size_t, u16 const*, size_t, u16 const*, size_t);-extern "C" size_t ladybird_html_parser_create_comment(void*, u16 const*, size_t);-extern "C" void ladybird_html_parser_insert_latin1_text(size_t, size_t, u8 const*, size_t, bool);-extern "C" void ladybird_html_parser_insert_utf16_text(size_t, size_t, u16 const*, size_t, bool);-extern "C" void ladybird_html_parser_add_missing_attribute(void*, size_t, size_t, u16 const*, size_t);+extern "C" size_t ladybird_html_parser_create_document_type(void*, RustFfiHtmlUtf16View, RustFfiHtmlUtf16View, RustFfiHtmlUtf16View);+extern "C" size_t ladybird_html_parser_create_comment(void*, RustFfiHtmlUtf16View);+extern "C" void ladybird_html_parser_insert_text(size_t, size_t, RustFfiHtmlUtf16View, bool);+extern "C" void ladybird_html_parser_add_missing_attribute(void*, size_t, size_t, RustFfiHtmlUtf16View);extern "C" u8 ladybird_html_parser_sanitizer_action(void*, size_t);extern "C" size_t ladybird_html_parser_child_at_index(size_t, size_t);extern "C" u32 ladybird_html_parser_declarative_shadow_root_attributes(size_t);@@ -1231,10 +1217,10 @@ GC::Ref<DOM::Element> HTMLParser::create_element_for(Utf16FlyString const& local// 4. Let localName be token's tag name.- auto attribute_value = [&](Utf16FlyString const& name) -> Optional<StringView> {+ auto attribute_value = [&](Utf16FlyString const& name) -> Optional<Utf16View> {for (auto const& attribute : attributes) {if (attribute.local_name == name.raw_identity())- return StringView { reinterpret_cast<char const*>(attribute.value_ptr), attribute.value_len };+ return utf16_view_from_ffi(attribute.value);}return {};};@@ -1253,7 +1239,7 @@ GC::Ref<DOM::Element> HTMLParser::create_element_for(Utf16FlyString const& local// 8. Let is be the value of the "is" attribute in token, if such an attribute exists; otherwise null.Optional<Utf16FlyString> is_value;if (auto is_attribute = attribute_value(AttributeNames::is); is_attribute.has_value())- is_value = Utf16FlyString::from_utf8_without_validation(*is_attribute);+ is_value = Utf16FlyString::from_utf16(*is_attribute);// 9. If is is non-null, sanitizerConfig is non-null, and the result of checking if a sanitizer config allows an// attribute given "is", null, is, localName, namespace, and sanitizerConfig is false, then set is to null.@@ -1325,7 +1311,7 @@ GC::Ref<DOM::Element> HTMLParser::create_element_for(Utf16FlyString const& localfor (auto const& attribute : attributes) {auto attribute_local_name = Utf16FlyString::from_raw(attribute.local_name);auto attribute_namespace = attribute_namespace_from_html_parser_ffi(attribute.namespace_);- auto value = utf8_string_from_ffi(attribute.value_ptr, attribute.value_len);+ auto value = Utf16String::from_utf16(utf16_view_from_ffi(attribute.value));// 1. If sanitizerConfig is not null:if (sanitizer_config) {@@ -1339,8 +1325,8 @@ GC::Ref<DOM::Element> HTMLParser::create_element_for(Utf16FlyString const& local}Optional<Utf16FlyString> prefix;- if (attribute.prefix_len != 0)- prefix = Utf16FlyString::from_utf8_without_validation({ reinterpret_cast<char const*>(attribute.prefix_ptr), attribute.prefix_len });+ if (attribute.prefix.length != 0)+ prefix = Utf16FlyString::from_utf16(utf16_view_from_ffi(attribute.prefix));DOM::QualifiedName qualified_name { move(attribute_local_name), move(prefix), move(attribute_namespace) };// 2. Append attribute to element.element->append_attribute(move(qualified_name), move(value));@@ -3090,22 +3076,20 @@ extern "C" bool ladybird_html_parser_document_is_iframe_srcdoc_document(void* pareturn url_matches_about_srcdoc(parser_from_html_parser_ffi(parser).document().url());}-extern "C" size_t ladybird_html_parser_create_document_type(void* parser, u16 const* name_ptr, size_t name_len, u16 const* public_id_ptr, size_t public_id_len, u16 const* system_id_ptr, size_t system_id_len)+extern "C" size_t ladybird_html_parser_create_document_type(void* parser, RustFfiHtmlUtf16View name, RustFfiHtmlUtf16View public_id, RustFfiHtmlUtf16View system_id){auto& html_parser = parser_from_html_parser_ffi(parser);auto document_type = DOM::DocumentType::create(html_parser.document());- document_type->set_name(utf16_fly_string_from_ffi(name_ptr, name_len));- auto public_id = utf16_string_from_ffi(public_id_ptr, public_id_len);- auto system_id = utf16_string_from_ffi(system_id_ptr, system_id_len);- document_type->set_public_id(public_id.utf16_view());- document_type->set_system_id(system_id.utf16_view());+ document_type->set_name(Utf16FlyString::from_utf16(utf16_view_from_ffi(name)));+ document_type->set_public_id(utf16_view_from_ffi(public_id));+ document_type->set_system_id(utf16_view_from_ffi(system_id));return reinterpret_cast<size_t>(document_type.ptr());}-extern "C" size_t ladybird_html_parser_create_comment(void* parser, u16 const* data_ptr, size_t data_len)+extern "C" size_t ladybird_html_parser_create_comment(void* parser, RustFfiHtmlUtf16View data){auto& html_parser = parser_from_html_parser_ffi(parser);- auto comment = DOM::Comment::create(html_parser.document(), utf16_string_from_ffi(data_ptr, data_len));+ auto comment = DOM::Comment::create(html_parser.document(), Utf16String::from_utf16(utf16_view_from_ffi(data)));return reinterpret_cast<size_t>(comment.ptr());}@@ -3132,23 +3116,21 @@ static void insert_text_for_rust_parser(size_t parent, size_t offset, ReadonlySpinsert_node_for_parser(parent_node, *text_node, insertion_location.child_at_offset());}-extern "C" void ladybird_html_parser_insert_latin1_text(size_t parent, size_t offset, u8 const* data_ptr, size_t data_len, bool is_ascii)-{- insert_text_for_rust_parser(parent, offset, ReadonlyBytes { data_ptr, data_len }, is_ascii);-}--extern "C" void ladybird_html_parser_insert_utf16_text(size_t parent, size_t offset, u16 const* data_ptr, size_t data_len, bool is_ascii)+extern "C" void ladybird_html_parser_insert_text(size_t parent, size_t offset, RustFfiHtmlUtf16View text, bool is_ascii){- insert_text_for_rust_parser(parent, offset, ReadonlySpan<char16_t> { reinterpret_cast<char16_t const*>(data_ptr), data_len }, is_ascii);+ if (text.latin1)+ insert_text_for_rust_parser(parent, offset, ReadonlyBytes { text.latin1, text.length }, is_ascii);+ else+ insert_text_for_rust_parser(parent, offset, ReadonlySpan<char16_t> { reinterpret_cast<char16_t const*>(text.utf16), text.length }, is_ascii);}// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inbody// NB: The steps for each attribute of an "html" or "body" start tag token in the "in body" insertion mode.-extern "C" void ladybird_html_parser_add_missing_attribute(void* parser, size_t element, size_t local_name_raw, u16 const* value_ptr, size_t value_len)+extern "C" void ladybird_html_parser_add_missing_attribute(void* parser, size_t element, size_t local_name_raw, RustFfiHtmlUtf16View value_view){auto& dom_element = as<DOM::Element>(node_from_html_parser_ffi(element));auto local_name = Utf16FlyString::from_raw(local_name_raw);- auto value = utf16_string_from_ffi(value_ptr, value_len);+ auto value = Utf16String::from_utf16(utf16_view_from_ffi(value_view));// 1. If the parser's parser sanitizer configuration is not null and the result of checking if a sanitizer config// allows an attribute given attribute's name, null, attribute's value, element's local name, element'sdiff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/code_units.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/code_units.rsnew file mode 100644index 00000000000..f1af4526795--- /dev/null+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/code_units.rs@@ -0,0 +1,339 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use crate::scan;+use ak::Utf16View;+use std::ops::Range;++/// A string of code units, in either of the two forms the engine's own strings have: one byte per code unit while+/// every code unit is below U+0100, and UTF-16 otherwise.+///+/// The tokenizer's input stream is one of these, and so is everything the tokenizer reads out of it. Most documents+/// only have code units below U+0100. A string is widened the first time it is given a code unit that doesn't fit.+/// Both forms are indexed by code unit, so offsets into a string stay the same when that happens.+#[derive(Clone, Debug)]+pub enum CodeUnits {+ Latin1(Vec<u8>),+ Utf16(Vec<u16>),+}++/// Where a run of code units is in the input.+#[derive(Clone, Debug)]+pub struct InputRun {+ pub range: Range<usize>,+ /// Whether every code unit of the run is known to be ASCII.+ pub is_ascii: bool,+}++/// A `Utf16View` as the host is handed one. Exactly one pointer is non-null unless the view is empty, and what it+/// points at is only readable until the call it is passed to returns.+#[repr(C)]+#[derive(Clone, Copy, Debug)]+pub struct RustFfiHtmlUtf16View {+ pub latin1: *const u8,+ pub utf16: *const u16,+ pub length: usize,+}++impl From<Utf16View<'_>> for RustFfiHtmlUtf16View {+ fn from(view: Utf16View<'_>) -> Self {+ match view {+ Utf16View::Latin1(code_units) => Self {+ latin1: code_units.as_ptr(),+ utf16: std::ptr::null(),+ length: code_units.len(),+ },+ Utf16View::Utf16(code_units) => Self {+ latin1: std::ptr::null(),+ utf16: code_units.as_ptr(),+ length: code_units.len(),+ },+ }+ }+}++#[cfg(test)]+impl RustFfiHtmlUtf16View {+ /// What a test's stand-in for the host was handed, as text.+ pub(crate) fn to_test_string(self) -> String {+ let code_units = if self.length == 0 {+ Vec::new()+ } else if !self.latin1.is_null() {+ Utf16View::Latin1(unsafe { ak::slice_from_raw_parts(self.latin1, self.length) }).to_utf16()+ } else {+ unsafe { ak::slice_from_raw_parts(self.utf16, self.length) }.to_vec()+ };+ String::from_utf16(&code_units).unwrap()+ }+}++/// Whether any code unit is something other than the ASCII whitespace the tree builder ignores for "frameset-ok".+pub fn contains_non_whitespace(view: Utf16View<'_>) -> bool {+ match view {+ Utf16View::Latin1(code_units) => scan::contains_non_whitespace(code_units),+ Utf16View::Utf16(code_units) => scan::contains_non_whitespace(code_units),+ }+}++impl Default for CodeUnits {+ fn default() -> Self {+ Self::Latin1(Vec::new())+ }+}++impl From<Vec<u8>> for CodeUnits {+ fn from(code_units: Vec<u8>) -> Self {+ Self::Latin1(code_units)+ }+}++impl From<Vec<u16>> for CodeUnits {+ fn from(code_units: Vec<u16>) -> Self {+ Self::Utf16(code_units)+ }+}++impl CodeUnits {+ #[inline(always)]+ pub fn len(&self) -> usize {+ match self {+ Self::Latin1(code_units) => code_units.len(),+ Self::Utf16(code_units) => code_units.len(),+ }+ }++ #[inline(always)]+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// The code unit at `offset`, which must be inside the input.+ #[inline(always)]+ pub fn code_unit_at(&self, offset: usize) -> u16 {+ match self {+ Self::Latin1(code_units) => u16::from(code_units[offset]),+ Self::Utf16(code_units) => code_units[offset],+ }+ }++ #[inline(always)]+ pub fn get(&self, offset: usize) -> Option<u16> {+ match self {+ Self::Latin1(code_units) => code_units.get(offset).copied().map(u16::from),+ Self::Utf16(code_units) => code_units.get(offset).copied(),+ }+ }++ pub fn slice_from(&self, start: usize) -> Utf16View<'_> {+ match self {+ Self::Latin1(code_units) => Utf16View::Latin1(&code_units[start..]),+ Self::Utf16(code_units) => Utf16View::Utf16(&code_units[start..]),+ }+ }++ pub fn slice(&self, range: Range<usize>) -> Utf16View<'_> {+ match self {+ Self::Latin1(code_units) => Utf16View::Latin1(&code_units[range]),+ Self::Utf16(code_units) => Utf16View::Utf16(&code_units[range]),+ }+ }++ pub fn append(&mut self, code_units: Utf16View<'_>) {+ self.insert(self.len(), code_units);+ }++ pub fn insert(&mut self, offset: usize, code_units: Utf16View<'_>) {+ if self.is_empty() {+ *self = match code_units {+ Utf16View::Latin1(code_units) => Self::Latin1(code_units.to_vec()),+ Utf16View::Utf16(code_units) => Self::Utf16(code_units.to_vec()),+ };+ return;+ }+ match (&mut *self, code_units) {+ (Self::Latin1(input), Utf16View::Latin1(code_units)) => {+ input.splice(offset..offset, code_units.iter().copied());+ }+ (Self::Utf16(input), Utf16View::Latin1(code_units)) => {+ input.splice(offset..offset, code_units.iter().copied().map(u16::from));+ }+ (Self::Utf16(input), Utf16View::Utf16(code_units)) => {+ input.splice(offset..offset, code_units.iter().copied());+ }+ (Self::Latin1(input), Utf16View::Utf16(code_units)) => {+ let mut widened = Vec::with_capacity(input.len() + code_units.len());+ widened.extend(input[..offset].iter().copied().map(u16::from));+ widened.extend_from_slice(code_units);+ widened.extend(input[offset..].iter().copied().map(u16::from));+ *self = Self::Utf16(widened);+ }+ }+ }++ pub fn to_utf16(&self) -> Vec<u16> {+ self.slice_from(0).to_utf16()+ }++ pub const fn new() -> Self {+ Self::Latin1(Vec::new())+ }++ pub fn as_slice(&self) -> Utf16View<'_> {+ self.slice_from(0)+ }++ pub fn capacity(&self) -> usize {+ match self {+ Self::Latin1(code_units) => code_units.capacity(),+ Self::Utf16(code_units) => code_units.capacity(),+ }+ }++ /// Empties the string. A one-byte string keeps its buffer.+ pub fn clear(&mut self) {+ match self {+ Self::Latin1(code_units) => code_units.clear(),+ // NB: An empty string is always in the one-byte form, so that what is written to it next stays at one+ // byte per code unit if it can.+ Self::Utf16(_) => *self = Self::new(),+ }+ }++ /// Takes the string out, and leaves an empty one.+ pub fn take(&mut self) -> Self {+ std::mem::take(self)+ }++ #[inline(always)]+ pub fn push_ascii(&mut self, byte: u8) {+ debug_assert!(byte.is_ascii());+ match self {+ Self::Latin1(code_units) => code_units.push(byte),+ Self::Utf16(code_units) => code_units.push(u16::from(byte)),+ }+ }++ pub fn push_ascii_str(&mut self, string: &str) {+ debug_assert!(string.is_ascii());+ self.append(Utf16View::Latin1(string.as_bytes()));+ }++ /// Appends a code point. A surrogate is replaced with U+FFFD REPLACEMENT CHARACTER.+ #[inline(always)]+ pub fn push_code_point(&mut self, code_point: u32) {+ if let Self::Latin1(code_units) = self+ && code_point < 0x100+ {+ code_units.push(code_point as u8);+ return;+ }+ self.push_wide_code_point(code_point);+ }++ fn push_wide_code_point(&mut self, code_point: u32) {+ if let Self::Latin1(code_units) = self {+ *self = Self::Utf16(code_units.iter().copied().map(u16::from).collect());+ }+ let Self::Utf16(code_units) = self else {+ unreachable!();+ };+ match code_point {+ 0xD800..=0xDFFF => code_units.push(0xFFFD),+ 0..=0xFFFF => code_units.push(code_point as u16),+ _ => {+ let offset = code_point - 0x10000;+ code_units.push(0xD800 | (offset >> 10) as u16);+ code_units.push(0xDC00 | (offset & 0x3FF) as u16);+ }+ }+ }+}++impl PartialEq for CodeUnits {+ fn eq(&self, other: &Self) -> bool {+ self.as_slice() == other.as_slice()+ }+}++impl Eq for CodeUnits {}++impl PartialEq<str> for CodeUnits {+ fn eq(&self, other: &str) -> bool {+ self.as_slice() == *other+ }+}++impl PartialEq<&str> for CodeUnits {+ fn eq(&self, other: &&str) -> bool {+ self.as_slice() == **other+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn code_units(input: &str) -> Vec<u16> {+ input.encode_utf16().collect()+ }++ #[test]+ fn one_byte_input_stays_one_byte() {+ let mut input = CodeUnits::default();+ input.append(Utf16View::Latin1(b"<p>"));+ input.append(Utf16View::Latin1(b"caf\xe9"));+ input.insert(3, Utf16View::Latin1(b"un "));+ assert!(matches!(input, CodeUnits::Latin1(_)));+ assert_eq!(input.to_utf16(), code_units("<p>un caf\u{e9}"));+ assert_eq!(input.code_unit_at(9), 0xe9);+ assert_eq!(input.get(10), None);+ }++ #[test]+ fn wide_code_units_widen_the_input_in_place() {+ let mut input = CodeUnits::default();+ input.append(Utf16View::Latin1(b"<p>caf\xe9</p>"));+ input.insert(7, Utf16View::Utf16(&code_units(" \u{2014} \u{1f600}")));+ assert!(matches!(input, CodeUnits::Utf16(_)));+ assert_eq!(input.to_utf16(), code_units("<p>caf\u{e9} \u{2014} \u{1f600}</p>"));+ input.append(Utf16View::Latin1(b"\xe9"));+ assert_eq!(input.code_unit_at(input.len() - 1), 0xe9);+ }++ #[test]+ fn code_points_are_pushed_at_one_byte_each_until_one_doesnt_fit() {+ let mut string = CodeUnits::new();+ string.push_ascii(b'a');+ string.push_code_point(0xe9);+ assert!(matches!(string, CodeUnits::Latin1(_)));+ string.push_code_point(0x2014);+ string.push_code_point(0x1f600);+ string.push_code_point(0xd83d);+ string.push_ascii_str("ok");+ assert!(matches!(string, CodeUnits::Utf16(_)));+ assert_eq!(string, "a\u{e9}\u{2014}\u{1f600}\u{fffd}ok");+ string.clear();+ string.push_ascii(b'a');+ assert!(matches!(string, CodeUnits::Latin1(_)));+ }++ #[test]+ fn strings_compare_by_code_unit_whatever_form_they_are_in() {+ let narrow = CodeUnits::from(b"caf\xe9".to_vec());+ let wide = CodeUnits::from(code_units("caf\u{e9}"));+ assert_eq!(narrow, wide);+ assert_eq!(narrow, "caf\u{e9}");+ assert_ne!(narrow, "cafe");+ assert_ne!(wide, "caf");+ }++ #[test]+ fn empty_input_takes_the_form_of_what_it_is_given() {+ let mut input = CodeUnits::from(Vec::<u16>::new());+ input.append(Utf16View::Latin1(b"abc"));+ assert!(matches!(input, CodeUnits::Latin1(_)));+ }+}diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/input.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/input.rsdeleted file mode 100644index 317a512bfd2..00000000000--- a/Libraries/LibWeb/HTML/Parser/Rust/src/input.rs+++ /dev/null@@ -1,210 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use crate::scan;-use std::ops::Range;--/// The code units of a tokenizer's input stream.-///-/// Most documents only have code units below U+0100, and are kept at one byte per code unit. The stream is widened-/// the first time it is given a code unit that doesn't fit. Both forms are indexed by code unit, so offsets into the-/// stream stay the same when that happens.-#[derive(Clone, Debug)]-pub enum Input {- Latin1(Vec<u8>),- Utf16(Vec<u16>),-}--/// Where a run of code units is in the input.-#[derive(Clone, Debug)]-pub struct InputRun {- pub range: Range<usize>,- /// Whether every code unit of the run is known to be ASCII.- pub is_ascii: bool,-}--/// A borrowed run of input code units.-#[derive(Clone, Copy, Debug)]-pub enum InputSlice<'a> {- Latin1(&'a [u8]),- Utf16(&'a [u16]),-}--impl Default for Input {- fn default() -> Self {- Self::Latin1(Vec::new())- }-}--impl From<Vec<u8>> for Input {- fn from(code_units: Vec<u8>) -> Self {- Self::Latin1(code_units)- }-}--impl From<Vec<u16>> for Input {- fn from(code_units: Vec<u16>) -> Self {- Self::Utf16(code_units)- }-}--impl Input {- #[inline(always)]- pub fn len(&self) -> usize {- match self {- Self::Latin1(code_units) => code_units.len(),- Self::Utf16(code_units) => code_units.len(),- }- }-- #[inline(always)]- pub fn is_empty(&self) -> bool {- self.len() == 0- }-- /// The code unit at `offset`, which must be inside the input.- #[inline(always)]- pub fn code_unit_at(&self, offset: usize) -> u16 {- match self {- Self::Latin1(code_units) => u16::from(code_units[offset]),- Self::Utf16(code_units) => code_units[offset],- }- }-- #[inline(always)]- pub fn get(&self, offset: usize) -> Option<u16> {- match self {- Self::Latin1(code_units) => code_units.get(offset).copied().map(u16::from),- Self::Utf16(code_units) => code_units.get(offset).copied(),- }- }-- pub fn slice_from(&self, start: usize) -> InputSlice<'_> {- match self {- Self::Latin1(code_units) => InputSlice::Latin1(&code_units[start..]),- Self::Utf16(code_units) => InputSlice::Utf16(&code_units[start..]),- }- }-- pub fn slice(&self, range: Range<usize>) -> InputSlice<'_> {- match self {- Self::Latin1(code_units) => InputSlice::Latin1(&code_units[range]),- Self::Utf16(code_units) => InputSlice::Utf16(&code_units[range]),- }- }-- pub fn append(&mut self, code_units: InputSlice<'_>) {- self.insert(self.len(), code_units);- }-- pub fn insert(&mut self, offset: usize, code_units: InputSlice<'_>) {- if self.is_empty() {- *self = code_units.to_input();- return;- }- match (&mut *self, code_units) {- (Self::Latin1(input), InputSlice::Latin1(code_units)) => {- input.splice(offset..offset, code_units.iter().copied());- }- (Self::Utf16(input), InputSlice::Latin1(code_units)) => {- input.splice(offset..offset, code_units.iter().copied().map(u16::from));- }- (Self::Utf16(input), InputSlice::Utf16(code_units)) => {- input.splice(offset..offset, code_units.iter().copied());- }- (Self::Latin1(input), InputSlice::Utf16(code_units)) => {- let mut widened = Vec::with_capacity(input.len() + code_units.len());- widened.extend(input[..offset].iter().copied().map(u16::from));- widened.extend_from_slice(code_units);- widened.extend(input[offset..].iter().copied().map(u16::from));- *self = Self::Utf16(widened);- }- }- }-- pub fn to_utf16(&self) -> Vec<u16> {- self.slice_from(0).to_utf16()- }-}--impl InputSlice<'_> {- pub fn len(&self) -> usize {- match self {- Self::Latin1(code_units) => code_units.len(),- Self::Utf16(code_units) => code_units.len(),- }- }-- pub fn is_empty(&self) -> bool {- self.len() == 0- }-- pub fn to_utf16(&self) -> Vec<u16> {- let mut code_units = Vec::with_capacity(self.len());- self.append_to(&mut code_units);- code_units- }-- pub fn contains_non_whitespace(&self) -> bool {- match self {- Self::Latin1(code_units) => scan::contains_non_whitespace(code_units),- Self::Utf16(code_units) => scan::contains_non_whitespace(code_units),- }- }-- pub fn append_to(&self, output: &mut Vec<u16>) {- match self {- Self::Latin1(code_units) => output.extend(code_units.iter().copied().map(u16::from)),- Self::Utf16(code_units) => output.extend_from_slice(code_units),- }- }-- fn to_input(self) -> Input {- match self {- Self::Latin1(code_units) => Input::Latin1(code_units.to_vec()),- Self::Utf16(code_units) => Input::Utf16(code_units.to_vec()),- }- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn code_units(input: &str) -> Vec<u16> {- input.encode_utf16().collect()- }-- #[test]- fn one_byte_input_stays_one_byte() {- let mut input = Input::default();- input.append(InputSlice::Latin1(b"<p>"));- input.append(InputSlice::Latin1(b"caf\xe9"));- input.insert(3, InputSlice::Latin1(b"un "));- assert!(matches!(input, Input::Latin1(_)));- assert_eq!(input.to_utf16(), code_units("<p>un caf\u{e9}"));- assert_eq!(input.code_unit_at(9), 0xe9);- assert_eq!(input.get(10), None);- }-- #[test]- fn wide_code_units_widen_the_input_in_place() {- let mut input = Input::default();- input.append(InputSlice::Latin1(b"<p>caf\xe9</p>"));- input.insert(7, InputSlice::Utf16(&code_units(" \u{2014} \u{1f600}")));- assert!(matches!(input, Input::Utf16(_)));- assert_eq!(input.to_utf16(), code_units("<p>caf\u{e9} \u{2014} \u{1f600}</p>"));- input.append(InputSlice::Latin1(b"\xe9"));- assert_eq!(input.code_unit_at(input.len() - 1), 0xe9);- }-- #[test]- fn empty_input_takes_the_form_of_what_it_is_given() {- let mut input = Input::from(Vec::<u16>::new());- input.append(InputSlice::Latin1(b"abc"));- assert!(matches!(input, Input::Latin1(_)));- }-}diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rsindex 924a50c2217..1ea6829f931 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs@@ -4,8 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/+pub mod code_units;pub mod entities;-pub mod input;mod known_names;pub mod meta_charset_scanner;pub mod parser;@@ -14,7 +14,7 @@ mod scan;pub mod token;pub mod tokenizer;-use input::InputSlice;+use ak::Utf16View;use std::ptr;use token::Attribute;use token::Position;@@ -268,7 +268,7 @@ fn next_token_slow(let (value_end_line, value_end_column) =position_to_ffi(handle.tokenizer.position_at(value_end_offset));handle.last_attr_names.push(local_name);- handle.last_attr_values.push(value.encode_utf16().collect());+ handle.last_attr_values.push(value.to_utf16());let last_idx = handle.last_attr_names.len() - 1;let name = &handle.last_attr_names[last_idx];let value_code_units = &handle.last_attr_values[last_idx];@@ -290,14 +290,14 @@ fn next_token_slow(out.attributes_len = handle.last_attributes.len();}TokenPayload::Comment(data) => {- handle.last_comment = data.encode_utf16().collect();+ handle.last_comment = data.to_utf16();out.comment_ptr = handle.last_comment.as_ptr();out.comment_len = handle.last_comment.len();}TokenPayload::Doctype(doctype) => {- handle.last_doctype_name = doctype.name.encode_utf16().collect();- handle.last_public_id = doctype.public_identifier.encode_utf16().collect();- handle.last_system_id = doctype.system_identifier.encode_utf16().collect();+ handle.last_doctype_name = doctype.name.to_utf16();+ handle.last_public_id = doctype.public_identifier.to_utf16();+ handle.last_system_id = doctype.system_identifier.to_utf16();out.doctype_name_ptr = handle.last_doctype_name.as_ptr();out.doctype_name_len = handle.last_doctype_name.len();out.public_id_ptr = handle.last_public_id.as_ptr();@@ -339,7 +339,7 @@ pub extern "C" fn rust_html_tokenizer_insert_utf16_input(};handle.tokenizer- .insert_input_at_insertion_point(InputSlice::Utf16(input.as_slice()));+ .insert_input_at_insertion_point(Utf16View::Utf16(input.as_slice()));}/// Insert Latin-1 input at the current insertion point.@@ -353,7 +353,7 @@ pub extern "C" fn rust_html_tokenizer_insert_latin1_input(};handle.tokenizer- .insert_input_at_insertion_point(InputSlice::Latin1(input.as_slice()));+ .insert_input_at_insertion_point(Utf16View::Latin1(input.as_slice()));}/// Append UTF-16 input to the tokenizer input stream.@@ -365,7 +365,7 @@ pub extern "C" fn rust_html_tokenizer_append_utf16_input(let Some(handle) = handle else {return;};- handle.tokenizer.append_input(InputSlice::Utf16(input.as_slice()));+ handle.tokenizer.append_input(Utf16View::Utf16(input.as_slice()));}/// Append Latin-1 input to the tokenizer input stream.@@ -377,7 +377,7 @@ pub extern "C" fn rust_html_tokenizer_append_latin1_input(let Some(handle) = handle else {return;};- handle.tokenizer.append_input(InputSlice::Latin1(input.as_slice()));+ handle.tokenizer.append_input(Utf16View::Latin1(input.as_slice()));}/// Get the tokenizer input that has not been consumed yet.diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/meta_charset_scanner.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/meta_charset_scanner.rsindex 71cf660493f..2c88bfe0e1e 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/meta_charset_scanner.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/meta_charset_scanner.rs@@ -7,7 +7,7 @@//! Finds a document's encoding declaration before the HTML parser starts, by tokenizing the document's first bytes as//! the parser will: the prescan proposed in https://github.com/whatwg/html/issues/6962.-use crate::input::InputSlice;+use crate::code_units::RustFfiHtmlUtf16View;use crate::known_names::attribute_name;use crate::known_names::tag_name;use crate::preload_scanner::tokenizer_state_after_start_tag;@@ -17,6 +17,7 @@ use crate::token::KnownName;use crate::token::TokenPayload;use crate::token::TokenType;use crate::tokenizer::HtmlTokenizer;+use ak::Utf16View;use std::ffi::c_void;#[repr(C)]@@ -77,14 +78,14 @@ impl MetaCharsetScanner {&mut self,bytes: &[u8],input_complete: bool,- mut is_encoding: impl FnMut(&str, bool) -> bool,+ mut is_encoding: impl FnMut(Utf16View<'_>, bool) -> bool,) -> RustFfiMetaCharsetScanResult {if self.finished {return RustFfiMetaCharsetScanResult::NotFound;}// Bytes before a declaration only ever matter as ASCII, which every encoding a declaration can name reads the// same way, so reading them as Latin-1 tokenizes them as the parser will.- self.tokenizer.append_input(InputSlice::Latin1(bytes));+ self.tokenizer.append_input(Utf16View::Latin1(bytes));if input_complete {self.tokenizer.set_input_stream_closed(true);}@@ -174,7 +175,7 @@ impl MetaCharsetScanner {}// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inhead (a start tag whose tag name is "meta")-fn declares_encoding(attributes: &[Attribute], is_encoding: &mut impl FnMut(&str, bool) -> bool) -> bool {+fn declares_encoding(attributes: &[Attribute], is_encoding: &mut impl FnMut(Utf16View<'_>, bool) -> bool) -> bool {// If the element has a charset attribute, and getting an encoding from its value results in an encoding, ...if let Some(charset) = attribute_value(attributes, attribute_name!("charset"))&& is_encoding(charset, false)@@ -193,11 +194,11 @@ fn declares_encoding(attributes: &[Attribute], is_encoding: &mut impl FnMut(&strattribute_value(attributes, attribute_name!("content")).is_some_and(|content| is_encoding(content, true))}-fn attribute_value(attributes: &[Attribute], name: KnownName) -> Option<&str> {+fn attribute_value(attributes: &[Attribute], name: KnownName) -> Option<Utf16View<'_>> {attributes.iter().find(|attribute| attribute.local_name == name)- .map(|attribute| attribute.value.as_str())+ .map(|attribute| attribute.value.as_slice())}// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inhead@@ -269,11 +270,11 @@ pub unsafe extern "C" fn rust_html_meta_charset_scanner_scan(input: ak::Span<'_, u8>,input_complete: bool,ctx: *mut c_void,- is_encoding: unsafe extern "C" fn(ctx: *mut c_void, value: *const u8, value_len: usize, is_content: bool) -> bool,+ is_encoding: unsafe extern "C" fn(ctx: *mut c_void, value: RustFfiHtmlUtf16View, is_content: bool) -> bool,) -> RustFfiMetaCharsetScanResult {let scanner = unsafe { &mut *scanner };scanner.scan(input.as_slice(), input_complete, |value, is_content| unsafe {- is_encoding(ctx, value.as_ptr(), value.len(), is_content)+ is_encoding(ctx, value.into(), is_content)})}@@ -281,8 +282,10 @@ pub unsafe extern "C" fn rust_html_meta_charset_scanner_scan(mod tests {use super::*;- fn is_utf8(value: &str, _: bool) -> bool {- value.to_ascii_lowercase().contains("utf-8")+ fn is_utf8(value: Utf16View<'_>, _: bool) -> bool {+ String::from_utf16_lossy(&value.to_utf16())+ .to_ascii_lowercase()+ .contains("utf-8")}fn scan_all(input: &[u8]) -> RustFfiMetaCharsetScanResult {diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rsindex dea193a65a4..609525118d7 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs@@ -5,9 +5,10 @@*/use crate::RustFfiTokenizerHandle;-use crate::input::Input;-use crate::input::InputRun;-use crate::input::InputSlice;+use crate::code_units::CodeUnits;+use crate::code_units::InputRun;+use crate::code_units::RustFfiHtmlUtf16View;+use crate::code_units::contains_non_whitespace;use crate::known_names::attribute_name;use crate::known_names::tag_id;use crate::known_names::tag_name;@@ -22,6 +23,7 @@ use crate::token::TokenType;use crate::token::tag_set;use crate::tokenizer::HtmlTokenizer;use crate::tokenizer::State;+use ak::Utf16View;use std::collections::HashMap;use std::ffi::c_void;use std::ops::Deref;@@ -92,11 +94,9 @@ pub enum RustFfiHtmlAttributeNamespace {#[repr(C)]pub struct RustFfiHtmlParserAttribute {pub local_name: usize,- pub prefix_ptr: *const u8,- pub prefix_len: usize,+ pub prefix: RustFfiHtmlUtf16View,pub namespace_: RustFfiHtmlAttributeNamespace,- pub value_ptr: *const u8,- pub value_len: usize,+ pub value: RustFfiHtmlUtf16View,}#[repr(C)]@@ -120,34 +120,17 @@ unsafe extern "C" {fn ladybird_html_parser_visit_node(visitor: *mut c_void, node: usize);fn ladybird_html_parser_create_document_type(parser: *mut c_void,- name_ptr: *const u16,- name_len: usize,- public_id_ptr: *const u16,- public_id_len: usize,- system_id_ptr: *const u16,- system_id_len: usize,+ name: RustFfiHtmlUtf16View,+ public_id: RustFfiHtmlUtf16View,+ system_id: RustFfiHtmlUtf16View,) -> usize;- fn ladybird_html_parser_create_comment(parser: *mut c_void, data_ptr: *const u16, data_len: usize) -> usize;- fn ladybird_html_parser_insert_latin1_text(- parent: usize,- offset: usize,- data_ptr: *const u8,- data_len: usize,- is_ascii: bool,- );- fn ladybird_html_parser_insert_utf16_text(- parent: usize,- offset: usize,- data_ptr: *const u16,- data_len: usize,- is_ascii: bool,- );+ fn ladybird_html_parser_create_comment(parser: *mut c_void, data: RustFfiHtmlUtf16View) -> usize;+ fn ladybird_html_parser_insert_text(parent: usize, offset: usize, text: RustFfiHtmlUtf16View, is_ascii: bool);fn ladybird_html_parser_add_missing_attribute(parser: *mut c_void,element: usize,local_name: usize,- value_ptr: *const u16,- value_len: usize,+ value: RustFfiHtmlUtf16View,);fn ladybird_html_parser_remove_node(node: usize);fn ladybird_html_parser_handle_element_popped(element: usize);@@ -255,9 +238,9 @@ enum InsertionMode {#[derive(Clone, Debug, Eq, PartialEq)]struct OwnedAttribute {local_name: HtmlName,- prefix: Option<String>,+ prefix: Option<CodeUnits>,namespace_: RustFfiHtmlAttributeNamespace,- value: String,+ value: CodeUnits,}#[derive(Clone, Debug)]@@ -265,7 +248,7 @@ struct StackNode {handle: usize,local_name: HtmlName,namespace_: RustFfiHtmlNamespace,- namespace_uri: Option<String>,+ namespace_uri: Option<Vec<u16>>,attributes: Vec<OwnedAttribute>,template_content: Option<usize>,}@@ -409,7 +392,7 @@ struct ParserState {next_line_feed_can_be_ignored: bool,pending_text: PendingText,attribute_buffers: AttributeBuffers,- pending_table_text: String,+ pending_table_text: Vec<u32>,pending_table_text_contains_non_whitespace: bool,pending_script: Option<usize>,pending_svg_script: Option<usize>,@@ -445,7 +428,7 @@ impl ParserState {next_line_feed_can_be_ignored: false,pending_text: PendingText::default(),attribute_buffers: AttributeBuffers::default(),- pending_table_text: String::new(),+ pending_table_text: Vec::new(),pending_table_text_contains_non_whitespace: false,pending_script: None,pending_svg_script: None,@@ -704,7 +687,7 @@ impl TreeBuilder {let run = unsafe { self.tokenizer.as_mut().try_fast_data_run().unwrap() };// SAFETY: See above.let input = unsafe { &self.tokenizer.as_ref().input };- if self.frameset_ok && input.slice(run.range.clone()).contains_non_whitespace() {+ if self.frameset_ok && contains_non_whitespace(input.slice(run.range.clone())) {self.frameset_ok = false;}self.pending_text.push_input_run(run, input);@@ -842,21 +825,16 @@ impl TreeBuilder {// token (or the empty string if the system identifier was missing). Then, if the Document node has neither// a DocumentType child nor an element child, append doctype to the Document node.// FIXME: Check for an existing DocumentType or element child before appending the new doctype.- let name = if doctype.missing_name {- ""- } else {- doctype.name.as_str()- };- let public_id = if doctype.missing_public_identifier {- ""- } else {- doctype.public_identifier.as_str()- };- let system_id = if doctype.missing_system_identifier {- ""- } else {- doctype.system_identifier.as_str()- };+ fn present(missing: bool, string: &CodeUnits) -> Utf16View<'_> {+ if missing {+ Utf16View::Latin1(&[])+ } else {+ string.as_slice()+ }+ }+ let name = present(doctype.missing_name, &doctype.name);+ let public_id = present(doctype.missing_public_identifier, &doctype.public_identifier);+ let system_id = present(doctype.missing_system_identifier, &doctype.system_identifier);let document_type = self.create_document_type(name, public_id, system_id);let document = self.document_node();self.append_child(document, document_type);@@ -1656,7 +1634,7 @@ impl TreeBuilder {// Parse error. Change the token's tag name to "img" and reprocess it. (Don't ask.)self.parse_error("image start tag in in body insertion mode");let mut token = token;- token.set_tag_name("img");+ token.set_tag_name(Utf16View::Latin1(b"img"));self.process_using_the_rules_for(self.insertion_mode, token);return;}@@ -2362,9 +2340,7 @@ impl TreeBuilder {if !token.is_parser_whitespace() {self.pending_table_text_contains_non_whitespace = true;}- if let Some(character) = char::from_u32(token.code_point) {- self.pending_table_text.push(character);- }+ self.pending_table_text.push(token.code_point);return;}@@ -2374,14 +2350,14 @@ impl TreeBuilder {self.parse_error("non-whitespace character token in table text insertion mode");let old_foster_parenting_enabled = self.foster_parenting_enabled;self.foster_parenting_enabled = true;- for character in pending_table_text.chars() {- self.process_using_the_rules_for(InsertionMode::InBody, Token::synthetic_character(character as u32));+ for code_point in pending_table_text {+ self.process_using_the_rules_for(InsertionMode::InBody, Token::synthetic_character(code_point));self.flush_character_insertions();}self.foster_parenting_enabled = old_foster_parenting_enabled;} else {- for character in pending_table_text.chars() {- self.insert_character(character as u32);+ for code_point in pending_table_text {+ self.insert_character(code_point);}self.flush_character_insertions();}@@ -3236,39 +3212,35 @@ impl TreeBuilder {if doctype.name != "html" {return RustFfiHtmlQuirksMode::Yes;}- let public_identifier = doctype.public_identifier.as_str();- let system_identifier = doctype.system_identifier.as_str();- if doctype- .public_identifier- .eq_ignore_ascii_case("-//W3O//DTD W3 HTML Strict 3.0//EN//")- || doctype- .public_identifier- .eq_ignore_ascii_case("-/W3C/DTD HTML 4.0 Transitional/EN")- || doctype.public_identifier.eq_ignore_ascii_case("HTML")+ let public_identifier = doctype.public_identifier.as_slice();+ let system_identifier = doctype.system_identifier.as_slice();+ if public_identifier.eq_ignore_ascii_case("-//W3O//DTD W3 HTML Strict 3.0//EN//")+ || public_identifier.eq_ignore_ascii_case("-/W3C/DTD HTML 4.0 Transitional/EN")+ || public_identifier.eq_ignore_ascii_case("HTML")|| system_identifier.eq_ignore_ascii_case("http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"){return RustFfiHtmlQuirksMode::Yes;}if QUIRKS_PUBLIC_IDS.iter()- .any(|public_id| starts_with_ignore_ascii_case(public_identifier, public_id))+ .any(|public_id| public_identifier.starts_with_ignore_ascii_case(public_id)){return RustFfiHtmlQuirksMode::Yes;}if doctype.missing_system_identifier- && (starts_with_ignore_ascii_case(public_identifier, "-//W3C//DTD HTML 4.01 Frameset//")- || starts_with_ignore_ascii_case(public_identifier, "-//W3C//DTD HTML 4.01 Transitional//"))+ && (public_identifier.starts_with_ignore_ascii_case("-//W3C//DTD HTML 4.01 Frameset//")+ || public_identifier.starts_with_ignore_ascii_case("-//W3C//DTD HTML 4.01 Transitional//")){return RustFfiHtmlQuirksMode::Yes;}- if starts_with_ignore_ascii_case(public_identifier, "-//W3C//DTD XHTML 1.0 Frameset//")- || starts_with_ignore_ascii_case(public_identifier, "-//W3C//DTD XHTML 1.0 Transitional//")+ if public_identifier.starts_with_ignore_ascii_case("-//W3C//DTD XHTML 1.0 Frameset//")+ || public_identifier.starts_with_ignore_ascii_case("-//W3C//DTD XHTML 1.0 Transitional//"){return RustFfiHtmlQuirksMode::Limited;}if !doctype.missing_system_identifier- && (starts_with_ignore_ascii_case(public_identifier, "-//W3C//DTD HTML 4.01 Frameset//")- || starts_with_ignore_ascii_case(public_identifier, "-//W3C//DTD HTML 4.01 Transitional//"))+ && (public_identifier.starts_with_ignore_ascii_case("-//W3C//DTD HTML 4.01 Frameset//")+ || public_identifier.starts_with_ignore_ascii_case("-//W3C//DTD HTML 4.01 Transitional//")){return RustFfiHtmlQuirksMode::Limited;}@@ -3485,7 +3457,7 @@ impl TreeBuilder {&mut self,intended_parent: usize,namespace_: RustFfiHtmlNamespace,- namespace_uri: Option<&str>,+ namespace_uri: Option<&[u16]>,local_name: &HtmlName,attributes: &[RustFfiHtmlParserAttribute],had_duplicate_attribute: bool,@@ -3499,16 +3471,13 @@ impl TreeBuilder {.filter(|form_element| !self.insertion_target_redirection_map.contains_key(form_element)).unwrap_or(0);let has_template_element_on_stack = self.has_template_element_on_stack_of_open_elements();- let namespace_uri = namespace_uri.map(|namespace_uri| namespace_uri.encode_utf16().collect::<Vec<_>>());unsafe {ladybird_html_parser_create_element(self.host,intended_parent,namespace_,- namespace_uri- .as_ref()- .map_or(std::ptr::null(), |namespace_uri| namespace_uri.as_ptr()),- namespace_uri.as_ref().map_or(0, |namespace_uri| namespace_uri.len()),+ namespace_uri.map_or(std::ptr::null(), |namespace_uri| namespace_uri.as_ptr()),+ namespace_uri.map_or(0, |namespace_uri| namespace_uri.len()),local_name.raw_identity(),attributes.as_ptr(),attributes.len(),@@ -3564,26 +3533,17 @@ impl TreeBuilder {}}- fn create_document_type(&mut self, name: &str, public_id: &str, system_id: &str) -> usize {- let name = name.encode_utf16().collect::<Vec<_>>();- let public_id = public_id.encode_utf16().collect::<Vec<_>>();- let system_id = system_id.encode_utf16().collect::<Vec<_>>();- unsafe {- ladybird_html_parser_create_document_type(- self.host,- name.as_ptr(),- name.len(),- public_id.as_ptr(),- public_id.len(),- system_id.as_ptr(),- system_id.len(),- )- }+ fn create_document_type(+ &mut self,+ name: Utf16View<'_>,+ public_id: Utf16View<'_>,+ system_id: Utf16View<'_>,+ ) -> usize {+ unsafe { ladybird_html_parser_create_document_type(self.host, name.into(), public_id.into(), system_id.into()) }}- fn create_comment(&mut self, data: &str) -> usize {- let data = data.encode_utf16().collect::<Vec<_>>();- unsafe { ladybird_html_parser_create_comment(self.host, data.as_ptr(), data.len()) }+ fn create_comment(&mut self, data: Utf16View<'_>) -> usize {+ unsafe { ladybird_html_parser_create_comment(self.host, data.into()) }}fn append_child(&mut self, parent: usize, child: usize) {@@ -3995,7 +3955,7 @@ impl TreeBuilder {}// https://html.spec.whatwg.org/multipage/parsing.html#insert-a-comment- fn insert_comment(&mut self, data: &str, insertion_location: Option<AdjustedInsertionLocation>) {+ fn insert_comment(&mut self, data: Utf16View<'_>, insertion_location: Option<AdjustedInsertionLocation>) {// 1. If the parser's parser sanitizer configuration is non-null and the parser's parser sanitizer configuration// does not allow comments, then return.if self.sanitizing && !self.sanitizer_allows_comments {@@ -4016,7 +3976,7 @@ impl TreeBuilder {self.insert_node_at_insertion_location(insertion_location, comment);}- fn append_comment_to_node(&mut self, parent: usize, data: &str) {+ fn append_comment_to_node(&mut self, parent: usize, data: Utf16View<'_>) {let insertion_location = AdjustedInsertionLocation {parent,offset: APPEND_CHILD_OFFSET,@@ -4050,7 +4010,7 @@ impl TreeBuilder {let input = unsafe { &self.tokenizer.as_ref().input };self.insert_text(insertion_location, input.slice(input_run.range), input_run.is_ascii);} else {- self.insert_text(insertion_location, InputSlice::Utf16(&code_units), false);+ self.insert_text(insertion_location, Utf16View::Utf16(&code_units), false);}// OPTIMIZATION: Keep small text buffers for the next run without retaining large text nodes.if code_units.capacity() <= 4096 && self.pending_text.is_empty() {@@ -4059,18 +4019,9 @@ impl TreeBuilder {}}- fn insert_text(&mut self, insertion_location: AdjustedInsertionLocation, text: InputSlice<'_>, is_ascii: bool) {+ fn insert_text(&mut self, insertion_location: AdjustedInsertionLocation, text: Utf16View<'_>, is_ascii: bool) {let AdjustedInsertionLocation { parent, offset } = insertion_location;- unsafe {- match text {- InputSlice::Latin1(text) => {- ladybird_html_parser_insert_latin1_text(parent, offset, text.as_ptr(), text.len(), is_ascii)- }- InputSlice::Utf16(text) => {- ladybird_html_parser_insert_utf16_text(parent, offset, text.as_ptr(), text.len(), is_ascii)- }- }- }+ unsafe { ladybird_html_parser_insert_text(parent, offset, text.into(), is_ascii) }}fn add_missing_attributes_to_element(&mut self, element: usize, token: &Token) {@@ -4078,14 +4029,12 @@ impl TreeBuilder {return;};for attribute in attributes {- let value = attribute.value.encode_utf16().collect::<Vec<_>>();unsafe {ladybird_html_parser_add_missing_attribute(self.host,element,attribute.local_name.raw_identity(),- value.as_ptr(),- value.len(),+ attribute.value.as_slice().into(),);}}@@ -5110,7 +5059,7 @@ impl PendingText {self.input_run.is_none() && self.code_units.is_empty()}- fn push_code_point(&mut self, code_point: u32, input: &Input) {+ fn push_code_point(&mut self, code_point: u32, input: &CodeUnits) {let Some(character) = char::from_u32(code_point) else {return;};@@ -5118,7 +5067,7 @@ impl PendingText {self.code_units.extend_from_slice(character.encode_utf16(&mut [0; 2]));}- fn push_input_run(&mut self, run: InputRun, input: &Input) {+ fn push_input_run(&mut self, run: InputRun, input: &CodeUnits) {if self.is_empty() {self.input_run = Some(run);return;@@ -5134,7 +5083,7 @@ impl PendingText {input.slice(run.range).append_to(&mut self.code_units);}- fn copy_input_run(&mut self, input: &Input) {+ fn copy_input_run(&mut self, input: &CodeUnits) {if let Some(input_run) = self.input_run.take() {input.slice(input_run.range).append_to(&mut self.code_units);}@@ -5167,7 +5116,9 @@ fn owned_attributes_from_token(token: &Token, namespace_: RustFfiHtmlNamespace)let adjusted_name = adjusted_foreign_attribute_name(&attribute.local_name, namespace_);attributes.push(OwnedAttribute {local_name: adjusted_name.local_name,- prefix: adjusted_name.prefix.map(ToOwned::to_owned),+ prefix: adjusted_name+ .prefix+ .map(|prefix| CodeUnits::from(prefix.as_bytes().to_vec())),namespace_: adjusted_name.namespace_,value: attribute.value.clone(),});@@ -5175,20 +5126,19 @@ fn owned_attributes_from_token(token: &Token, namespace_: RustFfiHtmlNamespace)attributes}-unsafe fn utf16_string_from_ffi(ptr: *const u16, len: usize) -> String {+unsafe fn utf16_string_from_ffi(ptr: *const u16, len: usize) -> Vec<u16> {if ptr.is_null() || len == 0 {- return String::new();+ return Vec::new();}- let code_units = unsafe { ak::slice_from_raw_parts(ptr, len) };- String::from_utf16_lossy(code_units)+ unsafe { ak::slice_from_raw_parts(ptr, len) }.to_vec()}unsafe fn utf16_namespace_uri_from_ffi(namespace_: RustFfiHtmlNamespace,ptr: *const u16,len: usize,-) -> Option<String> {+) -> Option<Vec<u16>> {if namespace_ != RustFfiHtmlNamespace::Other || ptr.is_null() || len == 0 {return None;}@@ -5211,10 +5161,10 @@ unsafe fn owned_context_attributes_from_ffi(prefix: if attribute.prefix_len == 0 {None} else {- Some(unsafe { utf16_string_from_ffi(attribute.prefix_ptr, attribute.prefix_len) })+ Some(unsafe { utf16_string_from_ffi(attribute.prefix_ptr, attribute.prefix_len) }.into())},namespace_: attribute.namespace_,- value: unsafe { utf16_string_from_ffi(attribute.value_ptr, attribute.value_len) },+ value: unsafe { utf16_string_from_ffi(attribute.value_ptr, attribute.value_len) }.into(),}).collect()}@@ -5237,14 +5187,15 @@ impl AttributeBuffers {// The caller keeps the source attributes alive until the synchronous host callback returns.fn fill_from_owned_attributes(&mut self, attributes: &[OwnedAttribute]) {self.attributes.extend(attributes.iter().map(|attribute| {- let prefix = attribute.prefix.as_deref().unwrap_or("");+ let prefix = attribute+ .prefix+ .as_ref()+ .map_or(Utf16View::Latin1(&[]), CodeUnits::as_slice);RustFfiHtmlParserAttribute {local_name: attribute.local_name.raw_identity(),- prefix_ptr: prefix.as_ptr(),- prefix_len: prefix.len(),+ prefix: prefix.into(),namespace_: attribute.namespace_,- value_ptr: attribute.value.as_ptr(),- value_len: attribute.value.len(),+ value: attribute.value.as_slice().into(),}}));}@@ -5261,11 +5212,9 @@ impl AttributeBuffers {self.local_names.push(adjusted_name.local_name);self.attributes.push(RustFfiHtmlParserAttribute {local_name: self.local_names.last().unwrap().raw_identity(),- prefix_ptr: prefix.as_ptr(),- prefix_len: prefix.len(),+ prefix: Utf16View::Latin1(prefix.as_bytes()).into(),namespace_: adjusted_name.namespace_,- value_ptr: attribute.value.as_ptr(),- value_len: attribute.value.len(),+ value: attribute.value.as_slice().into(),});}}@@ -5518,8 +5467,8 @@ fn is_html_integration_point(node: &StackNode) -> bool {&& attribute.local_name == "encoding"}).is_some_and(|attribute| {- attribute.value.eq_ignore_ascii_case("text/html")- || attribute.value.eq_ignore_ascii_case("application/xhtml+xml")+ attribute.value.as_slice().eq_ignore_ascii_case("text/html")+ || attribute.value.as_slice().eq_ignore_ascii_case("application/xhtml+xml")}){return true;@@ -5680,12 +5629,6 @@ fn is_thoroughly_implied_end_tag(tag_name: &HtmlName) -> bool {])}-fn starts_with_ignore_ascii_case(string: &str, prefix: &str) -> bool {- string- .get(..prefix.len())- .is_some_and(|start| start.eq_ignore_ascii_case(prefix))-}-// https://html.spec.whatwg.org/multipage/parsing.html#specialfn is_special_tag(node: &StackNode) -> bool {match node.namespace_ {@@ -5818,9 +5761,9 @@ trait TokenExt {fn is_start_tag_one_of(&self, names: &TagSet) -> bool;fn is_end_tag_one_of(&self, names: &TagSet) -> bool;fn is_parser_whitespace(&self) -> bool;- fn comment_data(&self) -> &str;+ fn comment_data(&self) -> Utf16View<'_>;fn doctype_data(&self) -> &crate::token::DoctypeData;- fn attribute(&self, name: KnownName) -> Option<&str>;+ fn attribute(&self, name: KnownName) -> Option<Utf16View<'_>>;fn has_attribute(&self, name: KnownName) -> bool;}@@ -5860,11 +5803,11 @@ impl TokenExt for Token {matches!(self.code_point, 0x09 | 0x0a | 0x0c | 0x0d | 0x20)}- fn comment_data(&self) -> &str {+ fn comment_data(&self) -> Utf16View<'_> {let TokenPayload::Comment(data) = &self.payload else {- return "";+ return Utf16View::Latin1(&[]);};- data+ data.as_slice()}fn doctype_data(&self) -> &crate::token::DoctypeData {@@ -5874,13 +5817,13 @@ impl TokenExt for Token {data}- fn attribute(&self, name: KnownName) -> Option<&str> {+ fn attribute(&self, name: KnownName) -> Option<Utf16View<'_>> {let TokenPayload::Tag { attributes, .. } = &self.payload else {return None;};attributes.iter().find_map(|attribute| {if attribute.local_name == name {- Some(attribute.value.as_str())+ Some(attribute.value.as_slice())} else {None}diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rsindex e991ba4c394..1c69a5d177b 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs@@ -12,6 +12,7 @@ use super::RustFfiHtmlParserAttribute;use super::RustFfiHtmlQuirksMode;use super::RustFfiHtmlShadowRootMode;use super::RustFfiHtmlSlotAssignmentMode;+use crate::code_units::RustFfiHtmlUtf16View;use std::cell::RefCell;use std::ffi::c_void;use std::ptr::NonNull;@@ -244,53 +245,28 @@ extern "C" fn ladybird_html_parser_visit_node(_visitor: *mut c_void, _node: usiz#[unsafe(no_mangle)]extern "C" fn ladybird_html_parser_create_document_type(_parser: *mut c_void,- _name_ptr: *const u16,- _name_len: usize,- _public_id_ptr: *const u16,- _public_id_len: usize,- _system_id_ptr: *const u16,- _system_id_len: usize,+ _name: RustFfiHtmlUtf16View,+ _public_id: RustFfiHtmlUtf16View,+ _system_id: RustFfiHtmlUtf16View,) -> usize {with_fake_dom(|dom| dom.create_node(FakeNodeKind::DocumentType))}#[unsafe(no_mangle)]-extern "C" fn ladybird_html_parser_create_comment(- _parser: *mut c_void,- _data_ptr: *const u16,- _data_len: usize,-) -> usize {+extern "C" fn ladybird_html_parser_create_comment(_parser: *mut c_void, _data: RustFfiHtmlUtf16View) -> usize {with_fake_dom(|dom| dom.create_node(FakeNodeKind::Comment))}#[unsafe(no_mangle)]-unsafe extern "C" fn ladybird_html_parser_insert_latin1_text(- parent: usize,- offset: usize,- data_ptr: *const u8,- data_len: usize,- is_ascii: bool,-) {- let data = unsafe { ak::slice_from_raw_parts(data_ptr, data_len) };- assert!(!is_ascii || data.is_ascii());- insert_text(- parent,- offset,- &data.iter().copied().map(char::from).collect::<String>(),- );-}--#[unsafe(no_mangle)]-unsafe extern "C" fn ladybird_html_parser_insert_utf16_text(+extern "C" fn ladybird_html_parser_insert_text(parent: usize,offset: usize,- data_ptr: *const u16,- data_len: usize,+ text: RustFfiHtmlUtf16View,is_ascii: bool,) {- let data = unsafe { ak::slice_from_raw_parts(data_ptr, data_len) };- assert!(!is_ascii || data.iter().all(|code_unit| *code_unit < 0x80));- insert_text(parent, offset, &String::from_utf16(data).unwrap());+ let text = text.to_test_string();+ assert!(!is_ascii || text.is_ascii());+ insert_text(parent, offset, &text);}fn insert_text(parent: usize, offset: usize, data: &str) {@@ -316,8 +292,7 @@ extern "C" fn ladybird_html_parser_add_missing_attribute(_parser: *mut c_void,_element: usize,_local_name: usize,- _value_ptr: *const u16,- _value_len: usize,+ _value: RustFfiHtmlUtf16View,) {}diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rsindex 59413bf6fa4..54b95afcf75 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rs@@ -16,10 +16,10 @@ use super::test_host::FakeInsertion;use super::test_host::FakeInsertionCall;use super::test_host::FakeNodeKind;use crate::RustFfiTokenizerHandle;-use crate::input::InputSlice;use crate::make_handle;use crate::rust_html_tokenizer_destroy;use crate::tokenizer::HtmlTokenizer;+use ak::Utf16View;const HTML_ELEMENT: FakeNodeKind = FakeNodeKind::Element(RustFfiHtmlNamespace::Html);@@ -61,7 +61,7 @@ impl ScriptCreatedParser {fn write(&mut self, markup: &str) {let code_units: Vec<u16> = markup.encode_utf16().collect();self.tokenizer()- .insert_input_at_insertion_point(InputSlice::Utf16(&code_units));+ .insert_input_at_insertion_point(Utf16View::Utf16(&code_units));self.run(true);}@@ -70,9 +70,9 @@ impl ScriptCreatedParser {let code_units: Vec<u16> = markup.encode_utf16().collect();if code_units.iter().all(|code_unit| *code_unit <= 0xff) {let bytes: Vec<u8> = code_units.iter().map(|code_unit| *code_unit as u8).collect();- self.tokenizer().append_input(InputSlice::Latin1(&bytes));+ self.tokenizer().append_input(Utf16View::Latin1(&bytes));} else {- self.tokenizer().append_input(InputSlice::Utf16(&code_units));+ self.tokenizer().append_input(Utf16View::Utf16(&code_units));}self.close();}@@ -218,7 +218,7 @@ fn text_is_inserted_as_one_node_however_the_tokenizer_emits_it() {let mut parser = ScriptCreatedParser::open();parser.tokenizer()- .append_input(InputSlice::Utf16(&[0x3C, 0x70, 0x3E, 0x61, 0xD83D, 0x62]));+ .append_input(Utf16View::Utf16(&[0x3C, 0x70, 0x3E, 0x61, 0xD83D, 0x62]));parser.close();let paragraph = test_host::children(body_element())[0];assert_eq!(diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rsindex 90476a43dc6..e275c301fa7 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs@@ -5,7 +5,7 @@*/use crate::RustFfiTokenizerHandle;-use crate::input::InputSlice;+use crate::code_units::RustFfiHtmlUtf16View;use crate::known_names::attribute_name;use crate::known_names::tag_name;use crate::token::Attribute;@@ -16,6 +16,7 @@ use crate::token::TokenPayload;use crate::token::TokenType;use crate::tokenizer::HtmlTokenizer;use crate::tokenizer::State;+use ak::Utf16View;use std::borrow::Cow;use std::ffi::c_void;@@ -57,21 +58,15 @@ pub enum RustFfiPreloadScannerCorsSetting {#[repr(C)]pub struct RustFfiPreloadScannerEntry {pub action: RustFfiPreloadScannerAction,- pub url_ptr: *const u8,- pub url_len: usize,+ pub url: RustFfiHtmlUtf16View,pub destination: RustFfiPreloadScannerDestination,pub cors_setting: RustFfiPreloadScannerCorsSetting,- pub nonce_ptr: *const u8,- pub nonce_len: usize,- pub integrity_ptr: *const u8,- pub integrity_len: usize,+ pub nonce: RustFfiHtmlUtf16View,+ pub integrity: RustFfiHtmlUtf16View,pub integrity_present: bool,- pub referrer_policy_ptr: *const u8,- pub referrer_policy_len: usize,- pub fetch_priority_ptr: *const u8,- pub fetch_priority_len: usize,- pub media_ptr: *const u8,- pub media_len: usize,+ pub referrer_policy: RustFfiHtmlUtf16View,+ pub fetch_priority: RustFfiHtmlUtf16View,+ pub media: RustFfiHtmlUtf16View,}/// A preload scanner that keeps its place in the parser's input from one run to the next, so that a speculative HTML@@ -101,7 +96,7 @@ impl RustFfiPreloadScanner {*self = Self::new(self.scripting_enabled);}- fn append_input(&mut self, code_units: InputSlice<'_>) {+ fn append_input(&mut self, code_units: Utf16View<'_>) {self.tokenizer.append_input(code_units);}@@ -210,7 +205,7 @@ pub(crate) fn scan_utf16(mut callback: impl FnMut(&RustFfiPreloadScannerEntry) -> bool,) {let mut scanner = RustFfiPreloadScanner::new(scripting_enabled);- scanner.append_input(InputSlice::Utf16(input));+ scanner.append_input(Utf16View::Utf16(input));scanner.tokenizer.set_input_stream_closed(true);scanner.scan(&mut callback);}@@ -377,10 +372,14 @@ fn script_type_from_attributes(attributes: &[Attribute]) -> Option<ScriptType> {// Otherwise, el has a non-empty language attribute; let the script block's type string be the concatenation of// "text/" and the value of el's language attribute.// FIXME: Preserve whitespace in the type string; only the classic JavaScript MIME comparison strips it.- let type_string: Cow<'_, [u8]> = match (type_attribute, language_attribute) {- (Some(""), _) | (None, Some("")) | (None, None) => Cow::Borrowed(b"text/javascript"),- (Some(type_attribute), _) => Cow::Borrowed(type_attribute.as_bytes().trim_ascii()),- (None, Some(language)) => Cow::Owned([b"text/".as_slice(), language.as_bytes()].concat()),+ let type_attribute = type_attribute.map(keyword_bytes);+ let language_attribute = language_attribute.map(keyword_bytes);+ let type_string: Cow<'_, [u8]> = match (&type_attribute, &language_attribute) {+ (Some(type_attribute), _) if type_attribute.is_empty() => Cow::Borrowed(b"text/javascript"),+ (None, Some(language)) if language.is_empty() => Cow::Borrowed(b"text/javascript"),+ (None, None) => Cow::Borrowed(b"text/javascript"),+ (Some(type_attribute), _) => Cow::Borrowed(type_attribute.trim_ascii()),+ (None, Some(language)) => Cow::Owned([b"text/".as_slice(), language].concat()),};// 9. If the script block's type string is a JavaScript MIME type essence match, or el has a type attribute whose@@ -426,19 +425,20 @@ fn process_link(attributes: &[Attribute], callback: &mut impl FnMut(&RustFfiPrellet Some(rel) = attribute_value(attributes, attribute_name!("rel")) else {return true;};+ let rel = keyword_bytes(rel);- let (action, destination) = if rel_contains_keyword(rel.as_bytes(), b"stylesheet") {+ let (action, destination) = if rel_contains_keyword(&rel, b"stylesheet") {(RustFfiPreloadScannerAction::Fetch,RustFfiPreloadScannerDestination::Style,)- } else if rel_contains_keyword(rel.as_bytes(), b"modulepreload") {+ } else if rel_contains_keyword(&rel, b"modulepreload") {let Some(destination) = translate_modulepreload_destination(attribute_value(attributes, attribute_name!("as")))else {return true;};(RustFfiPreloadScannerAction::ModulePreload, destination)- } else if rel_contains_keyword(rel.as_bytes(), b"preload") {+ } else if rel_contains_keyword(&rel, b"preload") {let Some(destination) = translate_preload_destination(attribute_value(attributes, attribute_name!("as")))else {return true;@@ -479,47 +479,47 @@ fn process_img(attributes: &[Attribute], callback: &mut impl FnMut(&RustFfiPrelofn emit_entry(callback: &mut impl FnMut(&RustFfiPreloadScannerEntry) -> bool,action: RustFfiPreloadScannerAction,- url: &str,+ url: Utf16View<'_>,destination: RustFfiPreloadScannerDestination,cors_setting: RustFfiPreloadScannerCorsSetting,attributes: Option<&[Attribute]>,) -> bool {- let attribute_pointer_and_length = |name| {- attribute_value(attributes.unwrap_or_default(), name)- .map(|value| (value.as_ptr(), value.len()))- .unwrap_or((std::ptr::null(), 0))- };- let (nonce_ptr, nonce_len) = attribute_pointer_and_length(attribute_name!("nonce"));- let (integrity_ptr, integrity_len) = attribute_pointer_and_length(attribute_name!("integrity"));- let (referrer_policy_ptr, referrer_policy_len) = attribute_pointer_and_length(attribute_name!("referrerpolicy"));- let (fetch_priority_ptr, fetch_priority_len) = attribute_pointer_and_length(attribute_name!("fetchpriority"));- let (media_ptr, media_len) = attribute_pointer_and_length(attribute_name!("media"));+ let attribute = |name| attribute_value(attributes.unwrap_or_default(), name);+ let attribute_or_empty = |name| attribute(name).unwrap_or(Utf16View::Latin1(&[])).into();let entry = RustFfiPreloadScannerEntry {action,- url_ptr: url.as_ptr(),- url_len: url.len(),+ url: url.into(),destination,cors_setting,- nonce_ptr,- nonce_len,- integrity_ptr,- integrity_len,- integrity_present: !integrity_ptr.is_null(),- referrer_policy_ptr,- referrer_policy_len,- fetch_priority_ptr,- fetch_priority_len,- media_ptr,- media_len,+ nonce: attribute_or_empty(attribute_name!("nonce")),+ integrity: attribute_or_empty(attribute_name!("integrity")),+ integrity_present: attribute(attribute_name!("integrity")).is_some(),+ referrer_policy: attribute_or_empty(attribute_name!("referrerpolicy")),+ fetch_priority: attribute_or_empty(attribute_name!("fetchpriority")),+ media: attribute_or_empty(attribute_name!("media")),};callback(&entry)}-fn attribute_value(attributes: &[Attribute], name: KnownName) -> Option<&str> {+fn attribute_value(attributes: &[Attribute], name: KnownName) -> Option<Utf16View<'_>> {attributes.iter().find(|attribute| attribute.local_name == name)- .map(|attribute| attribute.value.as_str())+ .map(|attribute| attribute.value.as_slice())+}++/// The code units of an attribute value as bytes, to look for ASCII keywords in. A code unit that doesn't fit in a+/// byte becomes one that is in no keyword and isn't whitespace.+fn keyword_bytes(value: Utf16View<'_>) -> Cow<'_, [u8]> {+ match value {+ Utf16View::Latin1(code_units) => Cow::Borrowed(code_units),+ Utf16View::Utf16(code_units) => Cow::Owned(+ code_units+ .iter()+ .map(|&code_unit| u8::try_from(code_unit).unwrap_or(0xFF))+ .collect(),+ ),+ }}fn rel_contains_keyword(rel: &[u8], keyword: &[u8]) -> bool {@@ -527,8 +527,8 @@ fn rel_contains_keyword(rel: &[u8], keyword: &[u8]) -> bool {.any(|token| token.eq_ignore_ascii_case(keyword))}-fn translate_preload_destination(destination: Option<&str>) -> Option<RustFfiPreloadScannerDestination> {- Some(match destination?.as_bytes() {+fn translate_preload_destination(destination: Option<Utf16View<'_>>) -> Option<RustFfiPreloadScannerDestination> {+ Some(match &*keyword_bytes(destination?) {b"fetch" => RustFfiPreloadScannerDestination::None,b"font" => RustFfiPreloadScannerDestination::Font,b"image" => RustFfiPreloadScannerDestination::Image,@@ -539,12 +539,12 @@ fn translate_preload_destination(destination: Option<&str>) -> Option<RustFfiPre})}-fn translate_modulepreload_destination(destination: Option<&str>) -> Option<RustFfiPreloadScannerDestination> {+fn translate_modulepreload_destination(destination: Option<Utf16View<'_>>) -> Option<RustFfiPreloadScannerDestination> {let Some(destination) = destination else {return Some(RustFfiPreloadScannerDestination::Script);};- let destination = destination.as_bytes();+ let destination = &*keyword_bytes(destination);// A module preload destination is "json", "style", "text", or a script-like destination.if destination.eq_ignore_ascii_case(b"audioworklet") {@@ -608,7 +608,7 @@ fn cors_setting_from_attribute(attributes: &[Attribute]) -> RustFfiPreloadScannereturn RustFfiPreloadScannerCorsSetting::NoCors;};- if crossorigin.as_bytes().eq_ignore_ascii_case(b"use-credentials") {+ if crossorigin.eq_ignore_ascii_case("use-credentials") {RustFfiPreloadScannerCorsSetting::UseCredentials} else {RustFfiPreloadScannerCorsSetting::Anonymous@@ -634,10 +634,9 @@ mod tests {fn collect_with_scripting(input: &str, scripting_enabled: bool) -> Vec<ScannedEntry> {let mut entries = Vec::new();scan(input.as_bytes(), scripting_enabled, |entry| {- let url = unsafe { ak::slice_from_raw_parts(entry.url_ptr, entry.url_len) };entries.push(ScannedEntry {action: entry.action,- url: std::str::from_utf8(url).unwrap().to_string(),+ url: entry.url.to_test_string(),destination: entry.destination,cors_setting: entry.cors_setting,});@@ -650,10 +649,9 @@ mod tests {let input = input.encode_utf16().collect::<Vec<_>>();let mut entries = Vec::new();scan_utf16(&input, true, |entry| {- let url = unsafe { ak::slice_from_raw_parts(entry.url_ptr, entry.url_len) };entries.push(ScannedEntry {action: entry.action,- url: std::str::from_utf8(url).unwrap().to_string(),+ url: entry.url.to_test_string(),destination: entry.destination,cors_setting: entry.cors_setting,});@@ -902,17 +900,13 @@ mod tests {br#"<link rel="modulepreload" href="./module" nonce="abc" integrity="sha256-xyz" referrerpolicy="origin" fetchpriority="high" media="screen">"#,true,|entry| {- let string = |pointer, length| {- let bytes = unsafe { ak::slice_from_raw_parts(pointer, length) };- std::str::from_utf8(bytes).unwrap().to_string()- };options = Some((- string(entry.nonce_ptr, entry.nonce_len),- string(entry.integrity_ptr, entry.integrity_len),+ entry.nonce.to_test_string(),+ entry.integrity.to_test_string(),entry.integrity_present,- string(entry.referrer_policy_ptr, entry.referrer_policy_len),- string(entry.fetch_priority_ptr, entry.fetch_priority_len),- string(entry.media_ptr, entry.media_len),+ entry.referrer_policy.to_test_string(),+ entry.fetch_priority.to_test_string(),+ entry.media.to_test_string(),));true},@@ -1016,8 +1010,7 @@ mod tests {fn scan_urls(scanner: &mut RustFfiPreloadScanner) -> Vec<String> {let mut urls = Vec::new();scanner.scan(&mut |entry| {- let url = unsafe { ak::slice_from_raw_parts(entry.url_ptr, entry.url_len) };- urls.push(std::str::from_utf8(url).unwrap().to_string());+ urls.push(entry.url.to_test_string());true});urls@@ -1028,15 +1021,15 @@ mod tests {let mut scanner = RustFfiPreloadScanner::new(true);// The input runs out inside a tag, and then inside the text of a script.- scanner.append_input(InputSlice::Utf16(&code_units(r#"<img src="./a.png"><img sr"#)));+ scanner.append_input(Utf16View::Utf16(&code_units(r#"<img src="./a.png"><img sr"#)));assert_eq!(scan_urls(&mut scanner), vec!["./a.png"]);- scanner.append_input(InputSlice::Utf16(&code_units(+ scanner.append_input(Utf16View::Utf16(&code_units(r#"c="./b.png"><script>var trap = '<img src="./tr"#,)));assert_eq!(scan_urls(&mut scanner), vec!["./b.png"]);- scanner.append_input(InputSlice::Utf16(&code_units(+ scanner.append_input(Utf16View::Utf16(&code_units(r#"ap.png">';</script><img src="./c.png">"#,)));assert_eq!(scan_urls(&mut scanner), vec!["./c.png"]);@@ -1051,21 +1044,21 @@ mod tests {assert_eq!(input.to_utf16(), code_units("<img src=a>"));assert!(!continues);- parser_tokenizer.append_input(InputSlice::Utf16(&code_units("<img src=b>")));+ parser_tokenizer.append_input(Utf16View::Utf16(&code_units("<img src=b>")));let (input, continues) = parser_tokenizer.input_for_speculative_scan();assert_eq!(input.to_utf16(), code_units("<img src=b>"));assert!(continues);// Once the parser gets past the scanned input, the scan starts over where the parser is.while parser_tokenizer.next_token(false, false).is_some() {}- parser_tokenizer.append_input(InputSlice::Utf16(&code_units("<img src=c>")));+ parser_tokenizer.append_input(Utf16View::Utf16(&code_units("<img src=c>")));let (input, continues) = parser_tokenizer.input_for_speculative_scan();assert_eq!(input.to_utf16(), code_units("<img src=c>"));assert!(continues);- parser_tokenizer.append_input(InputSlice::Utf16(&code_units("<img src=d><img src=e>")));+ parser_tokenizer.append_input(Utf16View::Utf16(&code_units("<img src=d><img src=e>")));while parser_tokenizer.next_token(false, false).is_some() {}parser_tokenizer.parser_did_run();- parser_tokenizer.append_input(InputSlice::Utf16(&code_units("<img src=f>")));+ parser_tokenizer.append_input(Utf16View::Utf16(&code_units("<img src=f>")));let (input, continues) = parser_tokenizer.input_for_speculative_scan();assert_eq!(input.to_utf16(), code_units("<img src=f>"));assert!(!continues);@@ -1084,7 +1077,7 @@ mod tests {// Input that document.write() inserts at the insertion point comes before the scanned input, so the scan has// to take it in too.- parser_tokenizer.insert_input_at_insertion_point(InputSlice::Utf16(&code_units("<img src=w>")));+ parser_tokenizer.insert_input_at_insertion_point(Utf16View::Utf16(&code_units("<img src=w>")));let (input, continues) = parser_tokenizer.input_for_speculative_scan();assert_eq!(input.to_utf16(), code_units("<img src=w><img src=a>"));assert!(!continues);diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/token.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/token.rsindex 9398e1556d5..cbab7a4f200 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/token.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/token.rs@@ -4,8 +4,10 @@* SPDX-License-Identifier: BSD-2-Clause*/+use crate::code_units::CodeUnits;#[cfg(not(test))]use ak::Utf16StringUnits;+use ak::Utf16View;use std::cell::RefCell;/// Source position in the input.@@ -55,6 +57,14 @@ impl TagId {pub fn for_name(name: &str) -> Self {crate::known_names::tag_id_for_name(name.as_bytes())}++ pub fn for_code_units(name: Utf16View<'_>) -> Self {+ // NB: Every known tag name is ASCII, so a name with other code units in it is found to be none of them.+ match name {+ Utf16View::Latin1(name) => crate::known_names::tag_id_for_name(name),+ Utf16View::Utf16(_) => Self::UNKNOWN,+ }+ }}/// A set of known tag names.@@ -93,7 +103,7 @@ pub(crate) use tag_set;#[derive(Clone, Debug, Default)]pub struct Attribute {pub local_name: HtmlName,- pub value: String,+ pub value: CodeUnits,pub name_start_offset: SourceOffset,pub name_end_offset: SourceOffset,pub value_start_offset: SourceOffset,@@ -120,7 +130,7 @@ const MAX_SPARE_ATTRIBUTE_VALUE_CAPACITY: usize = 4096;thread_local! {// Dropped tag tokens leave their attribute lists and value buffers here for the next tag.static SPARE_ATTRIBUTE_LISTS: RefCell<Vec<Vec<Attribute>>> = const { RefCell::new(Vec::new()) };- static SPARE_ATTRIBUTE_VALUES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };+ static SPARE_ATTRIBUTE_VALUES: RefCell<Vec<CodeUnits>> = const { RefCell::new(Vec::new()) };}/// The attributes of a tag token, backed by a spare buffer when one is available.@@ -187,12 +197,12 @@ impl Drop for AttributeList {if spare_values.len() == MAX_SPARE_ATTRIBUTE_VALUES {break;}- let capacity = attribute.value.capacity();+ let mut value = attribute.value;+ value.clear();+ let capacity = value.capacity();if capacity == 0 || capacity > MAX_SPARE_ATTRIBUTE_VALUE_CAPACITY {continue;}- let mut value = attribute.value;- value.clear();spare_values.push(value);}});@@ -246,6 +256,21 @@ impl KnownName {}impl HtmlName {+ pub fn from_code_units(name: Utf16View<'_>) -> Self {+ #[cfg(not(test))]+ {+ match name.as_ascii() {+ // SAFETY: ASCII is valid UTF-8.+ Some(name) => Self(ak::Utf16FlyString::from_utf8(unsafe { str::from_utf8_unchecked(name) })),+ None => Self(ak::Utf16FlyString::from_utf16(&name.to_utf16())),+ }+ }+ #[cfg(test)]+ {+ Self(String::from_utf16_lossy(&name.to_utf16()))+ }+ }+pub fn from_utf8(name: &str) -> Self {#[cfg(not(test))]{@@ -407,9 +432,9 @@ impl std::fmt::Debug for HtmlName {/// Data specific to DOCTYPE tokens.#[derive(Clone, Debug, Default)]pub struct DoctypeData {- pub name: String,- pub public_identifier: String,- pub system_identifier: String,+ pub name: CodeUnits,+ pub public_identifier: CodeUnits,+ pub system_identifier: CodeUnits,pub missing_name: bool,pub missing_public_identifier: bool,pub missing_system_identifier: bool,@@ -444,7 +469,7 @@ pub enum TokenPayload {had_duplicate_attribute: bool,attributes: AttributeList,},- Comment(String),+ Comment(CodeUnits),Doctype(Box<DoctypeData>),}@@ -490,11 +515,11 @@ impl Token {}}- pub fn set_tag_name(&mut self, name: &str) {+ pub fn set_tag_name(&mut self, name: Utf16View<'_>) {match &mut self.payload {TokenPayload::Tag { tag_name, tag_id, .. } => {- *tag_name = HtmlName::from_utf8(name);- *tag_id = TagId::for_name(name);+ *tag_name = HtmlName::from_code_units(name);+ *tag_id = TagId::for_code_units(name);}_ => panic!("set_tag_name called on non-tag token"),}@@ -558,7 +583,7 @@ impl Token {}#[inline(always)]- pub fn set_comment_data(&mut self, data: String) {+ pub fn set_comment_data(&mut self, data: CodeUnits) {match &mut self.payload {TokenPayload::Comment(s) => *s = data,_ => panic!("set_comment_data called on non-comment token"),@@ -584,7 +609,7 @@ mod spare_buffer_tests {}fn spare_value_capacities() -> Vec<usize> {- SPARE_ATTRIBUTE_VALUES.with_borrow(|values| values.iter().map(String::capacity).collect())+ SPARE_ATTRIBUTE_VALUES.with_borrow(|values| values.iter().map(CodeUnits::capacity).collect())}fn spare_list_capacities() -> Vec<usize> {@@ -593,7 +618,7 @@ mod spare_buffer_tests {fn attribute_with_value_capacity(capacity: usize) -> Attribute {Attribute {- value: String::with_capacity(capacity),+ value: CodeUnits::Latin1(Vec::with_capacity(capacity)),..Default::default()}}diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rsindex 2723315bc5c..2dbf4af6281 100644--- a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs@@ -6,10 +6,9 @@use std::collections::VecDeque;+use crate::code_units::CodeUnits;+use crate::code_units::InputRun;use crate::entities::NamedCharacterReferenceMatcher;-use crate::input::Input;-use crate::input::InputRun;-use crate::input::InputSlice;use crate::scan;use crate::token::Attribute;use crate::token::DoctypeData;@@ -19,6 +18,7 @@ use crate::token::SourceOffset;use crate::token::Token;use crate::token::TokenPayload;use crate::token::TokenType;+use ak::Utf16View;/// Tokenizer states per the WHATWG HTML spec section 13.2.5.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -226,11 +226,11 @@ struct SourcePositions {pub struct HtmlTokenizer {pub state: State,return_state: State,- pub input: Input,+ pub input: CodeUnits,pub current_offset: usize,prev_offset: usize,current_token: Token,- current_builder: String,+ current_builder: CodeUnits,pub queued_tokens: VecDeque<Token>,temporary_buffer: Vec<u32>,character_reference_code: u32,@@ -339,24 +339,9 @@ fn is_ascii_lower_alpha(c: u32) -> bool {matches!(c, 0x61..=0x7A)}-/// Push a code point onto a `String` as UTF-8 without paying-/// `char::from_u32`'s surrogate check or `String::push`'s len_utf8 branch-/// for the common ASCII case. For `cp < 0x80` this is a single byte push-/// to the underlying Vec; for wider code points we fall back to the-/// normal slow path.-#[inline(always)]-fn push_code_point(buf: &mut String, cp: u32) {- if cp < 0x80 {- // SAFETY: ASCII is always valid UTF-8.- unsafe { buf.as_mut_vec().push(cp as u8) };- } else {- buf.push(char::from_u32(cp).unwrap_or('\u{FFFD}'));- }-}-impl HtmlTokenizer {/// Create a new tokenizer for the given input.- pub fn new(input: impl Into<Input>) -> Self {+ pub fn new(input: impl Into<CodeUnits>) -> Self {HtmlTokenizer {state: State::Data,return_state: State::Data,@@ -364,7 +349,7 @@ impl HtmlTokenizer {current_offset: 0,prev_offset: 0,current_token: Token::default(),- current_builder: String::new(),+ current_builder: CodeUnits::new(),queued_tokens: VecDeque::new(),temporary_buffer: Vec::new(),character_reference_code: 0,@@ -420,11 +405,11 @@ impl HtmlTokenizer {.is_some_and(|insertion_point| self.current_offset >= insertion_point)}- pub fn append_input(&mut self, code_units: InputSlice<'_>) {+ pub fn append_input(&mut self, code_units: Utf16View<'_>) {self.input.append(code_units);}- pub fn insert_input_at_insertion_point(&mut self, code_units: InputSlice<'_>) {+ pub fn insert_input_at_insertion_point(&mut self, code_units: Utf16View<'_>) {if let Some(ip) = self.insertion_point {let ip = ip.min(self.input.len());self.input.insert(ip, code_units);@@ -445,14 +430,14 @@ impl HtmlTokenizer {}}- pub fn unparsed_input(&self) -> InputSlice<'_> {+ pub fn unparsed_input(&self) -> Utf16View<'_> {self.input.slice_from(self.current_offset)}/// The input a speculative HTML parser's preload scanner hasn't been given yet, and whether the scanner can go on/// from where it stopped. It can't once this tokenizer has got past that point, or input was inserted before it;/// the input then runs from the current position, and the scanner has to start over there.- pub fn input_for_speculative_scan(&mut self) -> (InputSlice<'_>, bool) {+ pub fn input_for_speculative_scan(&mut self) -> (Utf16View<'_>, bool) {let (start, continues) = match self.speculative_scan_end {Some(end) if end >= self.current_offset => (end, true),_ => (self.current_offset, false),@@ -524,7 +509,7 @@ impl HtmlTokenizer {known_offset: 0,known_position: end_position,};- self.input = Input::default();+ self.input = CodeUnits::default();self.current_offset = 0;self.prev_offset = 0;}@@ -647,8 +632,8 @@ impl HtmlTokenizer {}let range = positions.known_offset..offset;positions.known_position = match &self.input {- Input::Latin1(code_units) => scan::position_after(positions.known_position, &code_units[range]),- Input::Utf16(code_units) => scan::position_after(positions.known_position, &code_units[range]),+ CodeUnits::Latin1(code_units) => scan::position_after(positions.known_position, &code_units[range]),+ CodeUnits::Utf16(code_units) => scan::position_after(positions.known_position, &code_units[range]),};positions.known_offset = offset;positions.known_position@@ -695,8 +680,8 @@ impl HtmlTokenizer {let start_offset = self.current_offset;let limit = self.fast_scan_limit();let scan::Run { length, is_ascii } = match &self.input {- Input::Latin1(code_units) => scan::data_run(&code_units[start_offset..limit]),- Input::Utf16(code_units) => scan::data_run(&code_units[start_offset..limit]),+ CodeUnits::Latin1(code_units) => scan::data_run(&code_units[start_offset..limit]),+ CodeUnits::Utf16(code_units) => scan::data_run(&code_units[start_offset..limit]),};debug_assert!(length > 0);let end_offset = start_offset + length;@@ -727,14 +712,14 @@ impl HtmlTokenizer {self.current_offset = offset;}- fn consume_current_builder(&mut self) -> String {- std::mem::take(&mut self.current_builder)+ fn consume_current_builder(&mut self) -> CodeUnits {+ self.current_builder.take()}/// Commit `current_builder` into `current_token.tag_name`.#[inline]fn commit_current_builder_as_tag_name(&mut self) {- self.current_token.set_tag_name(&self.current_builder);+ self.current_token.set_tag_name(self.current_builder.as_slice());self.current_builder.clear();}@@ -747,7 +732,7 @@ impl HtmlTokenizer {had_duplicate_attribute: false,attributes: crate::token::AttributeList::new(),},- TokenType::Comment => TokenPayload::Comment(String::new()),+ TokenType::Comment => TokenPayload::Comment(CodeUnits::new()),TokenType::Doctype => TokenPayload::Doctype(Box::default()),_ => TokenPayload::None,};@@ -857,7 +842,7 @@ impl HtmlTokenizer {for i in 0..self.temporary_buffer.len() {let code_point = self.temporary_buffer[i];if self.consumed_as_part_of_an_attribute() {- push_code_point(&mut self.current_builder, code_point);+ self.current_builder.push_code_point(code_point);} else {let mut token = Token::new_character(code_point);token.start_offset = self.offset();@@ -1165,12 +1150,9 @@ impl HtmlTokenizer {&& cp >= b'a' as u32&& cp <= b'z' as u32{- // SAFETY: pushing ASCII bytes into a String is- // always valid UTF-8. We drop into a tight- // inner loop that directly advances- // current_offset without- // going through skip(1) per character.- unsafe { self.current_builder.as_mut_vec().push(cp as u8) };+ // The inner loop below advances current_offset+ // directly, one code unit of the name at a time.+ self.current_builder.push_ascii(cp as u8);let start_offset = self.current_offset;let mut off = start_offset;let input_len = self.fast_scan_limit();@@ -1179,7 +1161,7 @@ impl HtmlTokenizer {if next < b'a' as u16 || next > b'z' as u16 {break;}- unsafe { self.current_builder.as_mut_vec().push(next as u8) };+ self.current_builder.push_ascii(next as u8);off += 1;}let consumed = off - start_offset;@@ -1206,11 +1188,11 @@ impl HtmlTokenizer {return self.emit_current_token_direct();}Some(cp) if is_ascii_upper_alpha(cp) => {- push_code_point(&mut self.current_builder, to_ascii_lowercase(cp));+ self.current_builder.push_code_point(to_ascii_lowercase(cp));continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}None => {@@ -1218,7 +1200,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}}@@ -1238,7 +1220,7 @@ impl HtmlTokenizer {self.current_token.attributes_mut().push(Attribute::with_spare_value_buffer());- self.current_builder.push('=');+ self.current_builder.push_ascii(b'=');self.state = State::AttributeName;continue;}@@ -1261,7 +1243,7 @@ impl HtmlTokenizer {|| cp == b'-' as u32|| cp == b'_' as u32;if is_name_char {- unsafe { self.current_builder.as_mut_vec().push(cp as u8) };+ self.current_builder.push_ascii(cp as u8);let start_offset = self.current_offset;let mut off = start_offset;let input_len = self.fast_scan_limit();@@ -1274,7 +1256,7 @@ impl HtmlTokenizer {if !ok {break;}- unsafe { self.current_builder.as_mut_vec().push(next as u8) };+ self.current_builder.push_ascii(next as u8);off += 1;}let consumed = off - start_offset;@@ -1302,20 +1284,20 @@ impl HtmlTokenizer {continue;}Some(cp) if is_ascii_upper_alpha(cp) => {- push_code_point(&mut self.current_builder, to_ascii_lowercase(cp));+ self.current_builder.push_code_point(to_ascii_lowercase(cp));continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}Some(cp @ (0x22 | 0x27 | 0x3C)) => {// '"', '\'', '<' - parse error- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}}@@ -1392,7 +1374,7 @@ impl HtmlTokenizer {&& cp != 0x22&& cp != 0x26{- unsafe { self.current_builder.as_mut_vec().push(cp as u8) };+ self.current_builder.push_ascii(cp as u8);let start_offset = self.current_offset;let mut off = start_offset;let input_len = self.fast_scan_limit();@@ -1401,7 +1383,7 @@ impl HtmlTokenizer {if !(0x20..0x80).contains(&next) || next == 0x22 || next == 0x26 {break;}- unsafe { self.current_builder.as_mut_vec().push(next as u8) };+ self.current_builder.push_ascii(next as u8);off += 1;}let consumed = off - start_offset;@@ -1423,7 +1405,7 @@ impl HtmlTokenizer {continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}None => {@@ -1431,7 +1413,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}}@@ -1450,7 +1432,7 @@ impl HtmlTokenizer {continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}None => {@@ -1458,7 +1440,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -1481,12 +1463,12 @@ impl HtmlTokenizer {return self.emit_current_token_direct();}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}Some(cp @ (0x22 | 0x27 | 0x3C | 0x3D | 0x60)) => {// parse error, treat as anything else- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}None => {@@ -1494,7 +1476,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -1567,11 +1549,11 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -1608,7 +1590,7 @@ impl HtmlTokenizer {self.state = State::CDATASection;} else {self.create_new_token(TokenType::Comment);- self.current_builder.push_str("[CDATA[");+ self.current_builder.push_ascii_str("[CDATA[");self.state = State::BogusComment;}continue;@@ -1667,7 +1649,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(_) => {- self.current_builder.push('-');+ self.current_builder.push_ascii(b'-');self.reconsume(State::Comment);continue;}@@ -1676,7 +1658,7 @@ impl HtmlTokenizer {// 13.2.5.45 Comment stateState::Comment => match current_input_character {Some(0x3C) => {- self.current_builder.push('<');+ self.current_builder.push_ascii(b'<');self.state = State::CommentLessThanSign;continue;}@@ -1685,7 +1667,7 @@ impl HtmlTokenizer {continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}None => {@@ -1697,7 +1679,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -1705,12 +1687,12 @@ impl HtmlTokenizer {// 13.2.5.46 Comment less-than sign stateState::CommentLessThanSign => match current_input_character {Some(0x21) => {- self.current_builder.push('!');+ self.current_builder.push_ascii(b'!');self.state = State::CommentLessThanSignBang;continue;}Some(0x3C) => {- self.current_builder.push('<');+ self.current_builder.push_ascii(b'<');continue;}_ => {@@ -1771,7 +1753,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(_) => {- self.current_builder.push('-');+ self.current_builder.push_ascii(b'-');self.reconsume(State::Comment);continue;}@@ -1792,7 +1774,7 @@ impl HtmlTokenizer {continue;}Some(0x2D) => {- self.current_builder.push('-');+ self.current_builder.push_ascii(b'-');continue;}None => {@@ -1804,7 +1786,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(_) => {- self.current_builder.push_str("--");+ self.current_builder.push_ascii_str("--");self.reconsume(State::Comment);continue;}@@ -1813,7 +1795,7 @@ impl HtmlTokenizer {// 13.2.5.52 Comment end bang stateState::CommentEndBang => match current_input_character {Some(0x2D) => {- self.current_builder.push_str("--!");+ self.current_builder.push_ascii_str("--!");self.state = State::CommentEndDash;continue;}@@ -1835,7 +1817,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(_) => {- self.current_builder.push_str("--!");+ self.current_builder.push_ascii_str("--!");self.reconsume(State::Comment);continue;}@@ -1883,7 +1865,7 @@ impl HtmlTokenizer {missing_system_identifier: true,..Default::default()};- push_code_point(&mut self.current_builder, to_ascii_lowercase(cp));+ self.current_builder.push_code_point(to_ascii_lowercase(cp));self.state = State::DOCTYPEName;continue;}@@ -1895,7 +1877,7 @@ impl HtmlTokenizer {missing_system_identifier: true,..Default::default()};- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);self.state = State::DOCTYPEName;continue;}@@ -1932,7 +1914,7 @@ impl HtmlTokenizer {missing_system_identifier: true,..Default::default()};- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);self.state = State::DOCTYPEName;continue;}@@ -1963,11 +1945,11 @@ impl HtmlTokenizer {return self.emit_current_token_direct();}Some(cp) if is_ascii_upper_alpha(cp) => {- push_code_point(&mut self.current_builder, to_ascii_lowercase(cp));+ self.current_builder.push_code_point(to_ascii_lowercase(cp));continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}None => {@@ -1981,7 +1963,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -2142,7 +2124,7 @@ impl HtmlTokenizer {continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}Some(0x3E) => {@@ -2170,7 +2152,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -2189,7 +2171,7 @@ impl HtmlTokenizer {continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}Some(0x3E) => {@@ -2217,7 +2199,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -2235,7 +2217,7 @@ impl HtmlTokenizer {Some(0x22) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierDoubleQuoted;@@ -2244,7 +2226,7 @@ impl HtmlTokenizer {Some(0x27) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierSingleQuoted;@@ -2278,7 +2260,7 @@ impl HtmlTokenizer {Some(0x22) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierDoubleQuoted;@@ -2287,7 +2269,7 @@ impl HtmlTokenizer {Some(0x27) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierSingleQuoted;@@ -2320,7 +2302,7 @@ impl HtmlTokenizer {Some(0x22) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierDoubleQuoted;@@ -2329,7 +2311,7 @@ impl HtmlTokenizer {Some(0x27) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierSingleQuoted;@@ -2367,7 +2349,7 @@ impl HtmlTokenizer {Some(0x22) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierDoubleQuoted;@@ -2376,7 +2358,7 @@ impl HtmlTokenizer {Some(0x27) => {{let dd = self.current_token.doctype_data_mut();- dd.system_identifier = String::new();+ dd.system_identifier = CodeUnits::new();dd.missing_system_identifier = false;}self.state = State::DOCTYPESystemIdentifierSingleQuoted;@@ -2420,7 +2402,7 @@ impl HtmlTokenizer {continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}Some(0x3E) => {@@ -2444,7 +2426,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -2461,7 +2443,7 @@ impl HtmlTokenizer {continue;}Some(0x00) => {- self.current_builder.push('\u{FFFD}');+ self.current_builder.push_code_point(0xFFFD);continue;}Some(0x3E) => {@@ -2485,7 +2467,7 @@ impl HtmlTokenizer {return self.queued_tokens.pop_front();}Some(cp) => {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;}},@@ -2688,7 +2670,7 @@ impl HtmlTokenizer {State::AmbiguousAmpersand => match current_input_character {Some(cp) if is_ascii_alphanumeric(cp) => {if self.consumed_as_part_of_an_attribute() {- push_code_point(&mut self.current_builder, cp);+ self.current_builder.push_code_point(cp);continue;} else {return self.return_character_token(cp);@@ -3274,9 +3256,9 @@ impl HtmlTokenizer {}fn set_attribute_name(&mut self) {- let name = crate::token::HtmlName::from_utf8(&self.current_builder);+ let name = crate::token::HtmlName::from_code_units(self.current_builder.as_slice());// NB: Every code point of a name is one code point of input, in as many code units.- let name_length: usize = self.current_builder.chars().map(char::len_utf16).sum();+ let name_length = self.current_builder.len();let name_end = self.offset_before_last_code_point();let name_start = SourceOffset::new(name_end.get().unwrap().saturating_sub(name_length));self.current_builder.clear();@@ -3336,11 +3318,11 @@ impl HtmlTokenizer {self.reconsume(fallback_state);}Some(cp) if is_ascii_upper_alpha(cp) => {- push_code_point(&mut self.current_builder, to_ascii_lowercase(cp));+ self.current_builder.push_code_point(to_ascii_lowercase(cp));self.temporary_buffer.push(cp);}Some(cp) if is_ascii_lower_alpha(cp) => {- self.current_builder.push(char::from_u32(cp).unwrap());+ self.current_builder.push_ascii(cp as u8);self.temporary_buffer.push(cp);}_ => {@@ -3378,7 +3360,7 @@ mod tests {assert_eq!(tokenizer.current_offset, tokenizer.input.len());assert_eq!(tokenizer.input.to_utf16(), code_units("<p a=\"&tw"));- tokenizer.append_input(InputSlice::Utf16(&code_units("s-checkout-success=4.1.0\">")));+ tokenizer.append_input(Utf16View::Utf16(&code_units("s-checkout-success=4.1.0\">")));tokenizer.set_input_stream_closed(true);let token = tokenizer.next_token(false, false).expect("start tag token");@@ -3404,7 +3386,7 @@ mod tests {tokens.push(token);}tokenizer.parser_did_run();- tokenizer.append_input(InputSlice::Utf16(&code_units(second)));+ tokenizer.append_input(Utf16View::Utf16(&code_units(second)));tokenizer.set_input_stream_closed(true);while let Some(token) = tokenizer.next_token(false, false) {tokens.push(token);diff --git a/Libraries/LibWeb/HTML/Parser/RustUtf16View.h b/Libraries/LibWeb/HTML/Parser/RustUtf16View.hnew file mode 100644index 00000000000..55bca277deb--- /dev/null+++ b/Libraries/LibWeb/HTML/Parser/RustUtf16View.h@@ -0,0 +1,25 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Utf16View.h>+#include <LibWeb/HTMLTokenizerRustFFI.h>++namespace Web::HTML {++// A view of code units the Rust HTML parser hands over, Latin-1 or UTF-16 as it stores them. They are only there+// until the call they were passed to returns.+inline Utf16View utf16_view_from_ffi(RustFfiHtmlUtf16View view)+{+ if (view.length == 0)+ return {};+ 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/HTML/Parser/SpeculativeHTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cppindex ffb4a8a2983..acc829c15c6 100644--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp@@ -21,6 +21,7 @@#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>#include <LibWeb/HTML/CORSSettingAttribute.h>#include <LibWeb/HTML/Parser/HTMLParser.h>+#include <LibWeb/HTML/Parser/RustUtf16View.h>#include <LibWeb/HTML/Parser/SpeculativeHTMLParser.h>#include <LibWeb/HTML/PotentialCORSRequest.h>#include <LibWeb/HTML/PreloadEntry.h>@@ -197,16 +198,14 @@ void issue_speculative_fetch(JS::Realm& realm, DOM::Document& document, URL::URL(void)Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));}-Utf16String utf16_string_from_preload_scanner(u8 const* pointer, size_t length)+Utf16String utf16_string_from_preload_scanner(RustFfiHtmlUtf16View view){- if (length == 0)- return {};- return Utf16String::from_utf8(ffi_string_view(pointer, length));+ return Utf16String::from_utf16(utf16_view_from_ffi(view));}bool media_attribute_matches_environment(DOM::Document const& document, RustFfiPreloadScannerEntry const& entry){- auto media = utf16_string_from_preload_scanner(entry.media_ptr, entry.media_len);+ auto media = utf16_string_from_preload_scanner(entry.media);return CSS::RustMediaList::parse(media).evaluate(document);}@@ -220,15 +219,15 @@ void issue_speculative_module_fetch(DOM::Document& document, URL::URL const& url{auto& settings_object = document.relevant_settings_object();auto integrity_metadata = entry.integrity_present- ? utf16_string_from_preload_scanner(entry.integrity_ptr, entry.integrity_len)+ ? utf16_string_from_preload_scanner(entry.integrity): resolve_a_module_integrity_metadata(url, settings_object);ScriptFetchOptions options {- .cryptographic_nonce = utf16_string_from_preload_scanner(entry.nonce_ptr, entry.nonce_len),+ .cryptographic_nonce = utf16_string_from_preload_scanner(entry.nonce),.integrity_metadata = move(integrity_metadata),.parser_metadata = parser_metadata,.credentials_mode = cors_settings_attribute_credentials_mode(cors_setting_from_preload_scanner(entry.cors_setting)),- .referrer_policy = ReferrerPolicy::from_string(utf16_string_from_preload_scanner(entry.referrer_policy_ptr, entry.referrer_policy_len)).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString),- .fetch_priority = Fetch::Infrastructure::request_priority_from_string(utf16_string_from_preload_scanner(entry.fetch_priority_ptr, entry.fetch_priority_len)).value_or(Fetch::Infrastructure::Request::Priority::Auto),+ .referrer_policy = ReferrerPolicy::from_string(utf16_string_from_preload_scanner(entry.referrer_policy)).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString),+ .fetch_priority = Fetch::Infrastructure::request_priority_from_string(utf16_string_from_preload_scanner(entry.fetch_priority)).value_or(Fetch::Infrastructure::Request::Priority::Auto),};// NB: A speculative fetch must not populate the module map. A CSP meta element can appear between the parser's@@ -276,8 +275,8 @@ void issue_speculative_module_script_fetch(DOM::Document& document, URL::URL convoid SpeculativeHTMLParser::process_preload_scanner_entry(RustFfiPreloadScannerEntry const& entry){- auto url_string = ffi_string_view(entry.url_ptr, entry.url_len);- if (url_string.is_empty())+ auto url_view = utf16_view_from_ffi(entry.url);+ if (url_view.is_empty())return;// https://html.spec.whatwg.org/multipage/parsing.html#speculative-fetch@@ -286,7 +285,7 @@ void SpeculativeHTMLParser::process_preload_scanner_entry(RustFfiPreloadScannerE// 1. If the speculative HTML parser encounters one of the following elements, then act as if that// element is processed for the purpose of its effect on subsequent speculative fetches.// - A base element.- if (auto parsed = m_document->encoding_parse_url(Utf16String::from_utf8(url_string)); parsed.has_value())+ if (auto parsed = m_document->encoding_parse_url(Utf16String::from_utf16(url_view)); parsed.has_value())m_base_url = parsed.release_value();return;@@ -308,7 +307,7 @@ void SpeculativeHTMLParser::process_preload_scanner_entry(RustFfiPreloadScannerE// We resolve URLs against the speculative parser's tracked base_url (which may have been updated// by an earlier speculative <base href>); this is why we use complete_url here rather than// document.encoding_parse_url, which would resolve against the document's base instead.- auto url = m_base_url.complete_url(url_string);+ auto url = m_base_url.complete_url(url_view.to_utf8_but_should_be_ported_to_utf16());if (!url.has_value())return;diff --git a/Tests/LibWeb/Crash/HTML/meta-charset-with-non-latin1-character-reference.html b/Tests/LibWeb/Crash/HTML/meta-charset-with-non-latin1-character-reference.htmlnew file mode 100644index 00000000000..59485ab1e5f--- /dev/null+++ b/Tests/LibWeb/Crash/HTML/meta-charset-with-non-latin1-character-reference.html@@ -0,0 +1,3 @@+<meta charset="—">+<meta http-equiv="content-type" content="text/html; charset=—">+<p>PASS if no crash</p>