Truly independent web browser
LibWeb: Use Utf16String for text in the Rust CSSOM
Andreas Klinge281389e652a
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css.rsindex 4a0a5a8f631..e6a784fa2fa 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css.rs@@ -13,6 +13,7 @@ use core::ffi::c_void;use ak::Utf16String;use libweb_rust::typed_om::{self, RegisteredSyntax, RetainedStyleValue};+use super::css_rule::RuleText;use super::css_unit_value::CSSUnitValue;use super::highlight_registry::HighlightRegistry;use crate::bindings::interface::{Ref, cell_from_abi};@@ -95,10 +96,10 @@ impl CSS {// 2. Otherwise, If conditionText, wrapped in parentheses and then parsed and evaluated as a// <supports-condition>, would return true, return true.- let mut wrapped_condition_text = vec![u16::from(b'(')];- wrapped_condition_text.extend_from_slice(condition_text.to_utf16().as_ref());- wrapped_condition_text.push(u16::from(b')'));- if typed_om::supports_condition_matches(&Utf16String::from_utf16(&wrapped_condition_text)) {+ let mut wrapped_condition_text = RuleText::new("(");+ wrapped_condition_text.push(&condition_text);+ wrapped_condition_text.push_str(")");+ if typed_om::supports_condition_matches(&wrapped_condition_text.finish()) {return Ok(true);}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_counter_style_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_counter_style_rule.rsindex 0bbbcabd1d8..62da981dfc1 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_counter_style_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_counter_style_rule.rs@@ -53,11 +53,7 @@ impl CSSCounterStyleRule {}fn set_descriptor(&self, name: &str, value: &Utf16String) {- if self- .rule- .native_rule()- .set_counter_style_descriptor(name, &value.to_utf16())- {+ if self.rule.native_rule().set_counter_style_descriptor(name, value) {self.changed();}}@@ -69,7 +65,7 @@ impl CSSCounterStyleRule {// https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-namepub(crate) fn set_name(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {- if self.rule.native_rule().set_counter_style_name(&value.to_utf16()) {+ if self.rule.native_rule().set_counter_style_name(&value) {self.changed();}Ok(())@@ -188,7 +184,7 @@ impl CSSCounterStyleRule {pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {let native_rule = self.rule.native_rule();let mut text = RuleText::new("@counter-style ");- text.push(&serialize_identifier(&native_rule.counter_style_name().to_utf16()));+ text.push(&serialize_identifier(&native_rule.counter_style_name()));text.push_str(" {");for name in ["system",diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rsindex fdb35dcdf71..77f23de5086 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rs@@ -68,7 +68,7 @@ impl CSSFontFeatureValuesMap {}}- fn entries(&self) -> Vec<(Vec<u16>, Vec<u32>)> {+ fn entries(&self) -> Vec<(Utf16String, Vec<u32>)> {self.parent_rule.rule().native_rule()@@ -114,11 +114,10 @@ impl CSSFontFeatureValuesMap {));}- self.parent_rule.rule().native_rule().set_font_feature_value(- self.kind,- &feature_value_name.to_utf16(),- values.clone(),- );+ self.parent_rule+ .rule()+ .native_rule()+ .set_font_feature_value(self.kind, &feature_value_name, values.clone());self.parent_rule.clear_caches();self.map_entries.for_each_live(cx.vm(), |map| {set_map_entry(&context_of_map(cx, map), map, &feature_value_name, &values);@@ -132,7 +131,7 @@ impl Maplike for CSSFontFeatureValuesMap {self.map_entries.get_or_create(cx, || {let map = Map::create(cx.vm(), cx.realm());for (name, values) in self.entries() {- set_map_entry(cx, map, &Utf16String::from_utf16(&name), &values);+ set_map_entry(cx, map, &name, &values);}map})@@ -140,10 +139,9 @@ impl Maplike for CSSFontFeatureValuesMap {/// NB: Each get() converts the sequence of the entry to a new JS array.fn map_value(&self, cx: &CallContext, key: &Utf16String) -> Option<Value> {- let key = key.to_utf16();self.entries().into_iter()- .find(|(name, _)| name.as_slice() == key.as_ref())+ .find(|(name, _)| name == key).map(|(_, values)| create_map_value(cx, &values))}}@@ -158,7 +156,7 @@ impl WritableMaplike for CSSFontFeatureValuesMap {.parent_rule.rule().native_rule()- .remove_font_feature_value(self.kind, &key.to_utf16());+ .remove_font_feature_value(self.kind, key);if removed {self.parent_rule.clear_caches();self.map_entries.for_each_live(cx.vm(), |map| {diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_rule.rsindex 28a36f74d3d..e2916305d12 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_rule.rs@@ -90,9 +90,9 @@ impl CSSFontFeatureValuesRule {}let units = family.to_utf16();if units.iter().any(|unit| is_ascii_whitespace(*unit)) {- text.push(&serialize_string_value(&units));+ text.push(&serialize_string_value(family));} else {- text.push(&serialize_identifier(&units));+ text.push(&serialize_identifier(family));}}text.finish()@@ -118,7 +118,7 @@ impl CSSFontFeatureValuesRule {.iter().rposition(|unit| !is_ascii_whitespace(*unit)).map_or(start, |end| end + 1);- family[start..end].to_vec()+ Utf16String::from_utf16(&family[start..end])}).collect();self.rule.native_rule().set_font_feature_values_families(families);diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rsindex 6f8bda03966..1c3b5b9449c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs@@ -194,7 +194,7 @@ impl CSSImportRule {let media = native_rule.media_list();if media.length() != 0 {text.push_str(" ");- text.push(&Utf16String::from_utf16(&media.media_text()));+ text.push(&media.media_text());}// 4. The string ";", i.e., SEMICOLON (U+003B).diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframes_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframes_rule.rsindex ff48c9a802d..3f31d89cea2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframes_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframes_rule.rs@@ -112,7 +112,7 @@ impl CSSKeyframesRule {let cell = self.rule.object().cell();// SAFETY: The cell is that of this object, which is live.unsafe { web_css_keyframes_rule_will_rename(cell) };- native_rule.set_keyframes_name(&value.to_utf16());+ native_rule.set_keyframes_name(&value);// SAFETY: The cell is that of this object, which is live.unsafe { web_css_keyframes_rule_renamed(cell) };Ok(())@@ -160,7 +160,7 @@ impl CSSKeyframesRule {// The deleteRule method deletes the last declared CSSKeyframeRule matching the specified keyframe selector. If// no matching rule exists, the method does nothing.let native_rule = self.rule.native_rule();- let Some(index) = native_rule.find_keyframe(&select.to_utf16()) else {+ let Some(index) = native_rule.find_keyframe(&select) else {return Ok(());};if let Some(rules) = self.existing_css_rules() {@@ -183,7 +183,7 @@ impl CSSKeyframesRule {) -> WebIdlResult<Option<Ref<CSSKeyframeRule>>> {// The findRule returns the last declared CSSKeyframeRule matching the specified keyframe selector. If no// matching rule exists, the method does nothing.- let index = self.rule.native_rule().find_keyframe(&select.to_utf16());+ let index = self.rule.native_rule().find_keyframe(&select);Ok(index.and_then(|index| self.keyframe(cx.vm(), index)))}@@ -194,10 +194,10 @@ impl CSSKeyframesRule {// When serialized, the value is serialized as an <ident> unless it’s a disallowed keyword, in which case// it’s serialized as a <string>.let name = self.rule.native_rule().keyframes_name();- if is_valid_animation_name(&name.to_utf16()) {- text.push(&serialize_identifier(&name.to_utf16()));+ if is_valid_animation_name(&name) {+ text.push(&serialize_identifier(&name));} else {- text.push(&serialize_string_value(&name.to_utf16()));+ text.push(&serialize_string_value(&name));}text.push_str(" { ");diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_media_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_media_rule.rsindex 237a48b069b..59bb135fbc2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_media_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_media_rule.rs@@ -71,7 +71,7 @@ impl CSSMediaRule {}pub(crate) fn serialized_condition_text(&self) -> Utf16String {- Utf16String::from_utf16(&self.rule().native_rule().media_list().media_text())+ self.rule().native_rule().media_list().media_text()}// https://drafts.csswg.org/cssom-1/#serialize-a-css-rulediff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_namespace_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_namespace_rule.rsindex 6cada241b72..176e4ee0a30 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_namespace_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_namespace_rule.rs@@ -62,14 +62,14 @@ impl CSSNamespaceRule {// followed by the serialization as an identifier of the prefix attribute (if any),let prefix = native_rule.namespace_prefix();if !prefix.is_empty() {- text.push(&serialize_identifier(&prefix.to_utf16()));+ text.push(&serialize_identifier(&prefix));// followed by a single SPACE (U+0020) if there is a prefix,text.push_str(" ");}// followed by the serialization as URL of the namespaceURI attribute,text.push_str("url(");- text.push(&serialize_string_value(&native_rule.namespace_uri().to_utf16()));+ text.push(&serialize_string_value(&native_rule.namespace_uri()));text.push_str(")");// followed the character ";" (U+003B).diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rsindex 726131cdedb..7465d733bd3 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs@@ -57,7 +57,7 @@ impl CSSPageRule {// 1. Run the parse a list of CSS page selectors algorithm on the given value.// 2. If the algorithm returns a non-null value replace the associated selector list with the returned value.// 3. Otherwise, if the algorithm returns a null value, do nothing.- self.rule().native_rule().set_page_selector_text(&value.to_utf16());+ self.rule().native_rule().set_page_selector_text(&value);Ok(())}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_position_try_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_position_try_rule.rsindex 16ee690e730..58eb398ccec 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_position_try_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_position_try_rule.rs@@ -46,7 +46,7 @@ impl CSSPositionTryRule {fn serialized_name(&self) -> Utf16String {// Its name attribute represents the name declared in the rule's prelude.// INTEROP: Other browsers return the name serialized as an identifier.- serialize_identifier(&self.rule.native_rule().at_rule_name().to_utf16())+ serialize_identifier(&self.rule.native_rule().at_rule_name())}// https://drafts.csswg.org/css-anchor-position-1/#dom-csspositiontryrule-namediff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_property_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_property_rule.rsindex cf8ec8ca119..6a2e96fe886 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_property_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_property_rule.rs@@ -71,7 +71,7 @@ impl CSSPropertyRule {// 1. The string "@property" followed by a single SPACE (U+0020).// 2. The result of performing serialize an identifier on the rule’s name, followed by a single SPACE (U+0020).let mut text = RuleText::new("@property ");- text.push(&serialize_identifier(&native_rule.property_name().to_utf16()));+ text.push(&serialize_identifier(&native_rule.property_name()));text.push_str(" ");// 3. The string "{ ", i.e., a single LEFT CURLY BRACKET (U+007B), followed by a SPACE (U+0020).@@ -81,7 +81,7 @@ impl CSSPropertyRule {// 5. The result of performing serialize a string on the rule’s syntax, followed by a single SEMICOLON (U+003B),// followed by a SPACE (U+0020).text.push_str("syntax: ");- text.push(&serialize_string_value(&native_rule.property_syntax().to_utf16()));+ text.push(&serialize_string_value(&native_rule.property_syntax()));text.push_str("; ");// 6. The string "inherits:", followed by a single SPACE (U+0020).diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rsindex 9553c822a1c..b5314337d51 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs@@ -13,7 +13,7 @@ use std::rc::Rc;use ak::Utf16String;use libjs_rust::api::{Gc, GcRefCell, Object, ThrowCompletionOr, Trace, Value, Vm};-use libweb_rust::{NativeRule, NativeRuleList, NativeRuleType};+use libweb_rust::{NativeRule, NativeRuleList, NativeRuleType, TextSink};use super::css_condition_rule::CSSConditionRule;use super::css_container_rule::CSSContainerRule;@@ -401,7 +401,7 @@ pub(crate) fn serialized_rules(vm: &Vm, rules: Ref<CSSRuleList>) -> Vec<Utf16Str/// A string that grows by what the rules serialize to.#[derive(Default)]-pub(crate) struct RuleText(Vec<u16>);+pub(crate) struct RuleText(TextSink);impl RuleText {pub(crate) fn new(text: &str) -> Self {@@ -411,15 +411,19 @@ impl RuleText {}pub(crate) fn push_str(&mut self, text: &str) {- self.0.extend(text.encode_utf16());+ text.encode_utf16().for_each(|unit| self.0.push_code_unit(unit));}pub(crate) fn push(&mut self, text: &Utf16String) {- self.0.extend_from_slice(&text.to_utf16());+ self.0.push_string(text);+ }++ pub(crate) fn push_units(&mut self, units: &[u16]) {+ units.iter().for_each(|&unit| self.0.push_code_unit(unit));}pub(crate) fn finish(self) -> Utf16String {- Utf16String::from_utf16(&self.0)+ self.0.into_utf16_string()}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rsindex 98e26641100..0905ccee735 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs@@ -72,12 +72,12 @@ impl CSSStyleRule {// https://drafts.csswg.org/cssom-1/#dom-cssstylerule-selectortextpub(crate) fn set_selector_text(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {- self.replace_selectors(&value.to_utf16());+ self.replace_selectors(&value);Ok(())}// https://drafts.csswg.org/cssom-1/#dom-cssstylerule-selectortext- pub(crate) fn replace_selectors(&self, value: &[u16]) {+ pub(crate) fn replace_selectors(&self, value: &Utf16String) {// 1. Run the parse a group of selectors algorithm on the given value.let sheet = self.rule().parent_sheet();let sheet_rules = sheet.as_ref().map(native_rules_of_sheet);diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rsindex bcd16643f96..b2621bde193 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs@@ -15,7 +15,7 @@ use libjs_rust::api::{Trace, Vm};use libweb_rust::{NativeRule, NativeRuleList, NativeRuleType, NativeStyleSheetFlag};use super::css_grouping_rule::{insertion_error, validate_rule_removal};-use super::css_rule::AnyCSSRule;+use super::css_rule::{AnyCSSRule, RuleText};use super::css_rule_list::CSSRuleList;use super::exports::rule_from_abi;use super::media_list::MediaList;@@ -266,19 +266,20 @@ impl CSSStyleSheet {) -> WebIdlResult<i32> {// 1. Let rule be an empty string.// 2. Append selector to rule.- let mut rule = selector.to_utf16().into_owned();+ let mut rule = RuleText::default();+ rule.push(&selector);// 3. Append " { " to rule.- rule.extend(" { ".encode_utf16());+ rule.push_str(" { ");// 4. If block is not empty, append block, followed by a space, to rule.if !style.is_empty() {- rule.extend_from_slice(&style.to_utf16());- rule.extend(" ".encode_utf16());+ rule.push(&style);+ rule.push_str(" ");}// 5. Append "}" to rule- rule.extend("}".encode_utf16());+ rule.push_str("}");// 6. Let index be optionalIndex if provided, or the number of CSS rules in the stylesheet otherwise.let index = index.unwrap_or_else(|| {@@ -286,7 +287,7 @@ impl CSSStyleSheet {});// 7. Call insertRule(), with rule and index as arguments.- self.insert_rule(cx, Utf16String::from_utf16(&rule), index)?;+ self.insert_rule(cx, rule.finish(), index)?;// 8. Return -1.Ok(-1)diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_unparsed_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_unparsed_value.rsindex 16ab2321360..2017fdfd841 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_unparsed_value.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_unparsed_value.rs@@ -10,6 +10,7 @@ use ak::Utf16String;use libjs_rust::api::{GcRefCell, MarkedVec, Trace, Vm};use libweb_rust::typed_om::{RetainedStyleValue, unresolved_style_value};+use super::css_rule::RuleText;use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue};use super::css_variable_reference_value::CSSVariableReferenceValue;use crate::bindings::conversions::UsvString;@@ -130,7 +131,7 @@ impl CSSUnparsedValue {// To serialize a CSSUnparsedValue this:// 1. Let s initially be the empty string.- let mut s = Vec::new();+ let mut s = RuleText::default();// 2. For each item in this’s [[tokens]] internal slot:for item in self.tokens.borrow().iter() {@@ -138,14 +139,14 @@ impl CSSUnparsedValue {// serialize_a_series_of_component_values(). See https://github.com/w3c/css-houdini-drafts/issues/1148match item {// 1. If item is a USVString, append it to s.- CSSUnparsedSegment::USVString(string) => s.extend_from_slice(&string.to_utf16()),+ CSSUnparsedSegment::USVString(string) => s.push_units(&string.to_utf16()),// 2. Otherwise, item is a CSSVariableReferenceValue. Serialize it, then append the result to s.CSSUnparsedSegment::CSSVariableReferenceValue(variable) => variable.serialize(&mut s),}}// 3. Return s.- Utf16String::from_utf16(&s)+ s.finish()}// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representationdiff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_variable_reference_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_variable_reference_value.rsindex bd4f6f53287..eef1c9248bd 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_variable_reference_value.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_variable_reference_value.rs@@ -12,6 +12,7 @@ use ak::Utf16String;use libjs_rust::api::{GcRefCell, Trace, Vm};use libweb_rust::typed_om::is_a_custom_property_name_string;+use super::css_rule::RuleText;use super::css_unparsed_value::CSSUnparsedValue;use super::typed_om;use crate::bindings::conversions::UsvString;@@ -94,24 +95,24 @@ impl CSSVariableReferenceValue {}// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssvariablereferencevalue- pub(crate) fn serialize(&self, s: &mut Vec<u16>) {+ pub(crate) fn serialize(&self, s: &mut RuleText) {// To serialize a CSSVariableReferenceValue this:// 1. Let s initially be "var(".- s.extend("var(".encode_utf16());+ s.push_str("var(");// 2. Append this’s variable internal slot to s.- s.extend_from_slice(&self.variable.borrow().to_utf16());+ s.push(&self.variable.borrow());// 3. If this’s fallback internal slot is not null, append ", " to s, then serialize the fallback internal slot// and append it to s.if let Some(fallback) = self.raw_fallback() {// AD-HOC: Tested behaviour requires we append "," without the space.// https://github.com/w3c/css-houdini-drafts/issues/1148- s.push(u16::from(b','));- s.extend_from_slice(&fallback.serialize().to_utf16());+ s.push_str(",");+ s.push(&fallback.serialize());}// 4. Append ")" to s and return s.- s.push(u16::from(b')'));+ s.push_str(")");}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rsindex 8b02a221b33..cce09761f30 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs@@ -1078,7 +1078,7 @@ pub unsafe extern "C" fn web_css_import_rule_import(rule: *mut c_void) -> *mut cpub unsafe extern "C" fn web_css_style_rule_set_selector_text(rule: *mut c_void, text: usize) {// SAFETY: The caller passes a live cell of a CSSStyleRule, and hands over the string.let (rule, text): (Ref<CSSStyleRule>, _) = unsafe { (cell_from_abi(rule), Utf16String::from_raw_owned(text)) };- rule.replace_selectors(&text.to_utf16());+ rule.replace_selectors(&text);}/// A new CSSStyleSheet for the cell that holds the state of the sheet.diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/media_list.rs b/Libraries/LibWeb/Bindings/Rust/src/css/media_list.rsindex 60f37286f2b..b332be815f1 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/media_list.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/media_list.rs@@ -72,7 +72,7 @@ impl MediaList {// https://drafts.csswg.org/cssom/#dom-medialist-mediatextpub(crate) fn media_text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {- Ok(Utf16String::from_utf16(&self.media.media_text()))+ Ok(self.media.media_text())}// https://drafts.csswg.org/cssom/#dom-medialist-mediatext@@ -89,10 +89,7 @@ impl MediaList {// https://drafts.csswg.org/cssom/#dom-medialist-itempub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Utf16String>> {- Ok(self- .media- .item(index as usize)- .map(|text| Utf16String::from_utf16(&text)))+ Ok(self.media.item(index as usize))}// https://drafts.csswg.org/cssom/#dom-medialist-appendmediumdiff --git a/Libraries/LibWeb/Bindings/Rust/src/css/media_query_list.rs b/Libraries/LibWeb/Bindings/Rust/src/css/media_query_list.rsindex 4376dd46384..d468aee87e7 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/media_query_list.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/media_query_list.rs@@ -121,7 +121,7 @@ impl MediaQueryList {composed: false,},matches: now_matches,- media: Utf16String::from_utf16(&self.media.media_text()),+ media: self.media.media_text(),};let event =MediaQueryListEvent::create(vm, self.realm, &Utf16String::from_ascii(CHANGE.as_bytes()), event_init);@@ -132,7 +132,7 @@ impl MediaQueryList {// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-mediapub(crate) fn media(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {- Ok(Utf16String::from_utf16(&self.media.media_text()))+ Ok(self.media.media_text())}// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matchesdiff --git a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs b/Libraries/LibWeb/Rust/src/css/font_feature_values.rsindex 17ed18e38d5..049dca6d3f4 100644--- a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs+++ b/Libraries/LibWeb/Rust/src/css/font_feature_values.rs@@ -80,8 +80,11 @@ impl FontFeatureValuesRule {.collect()}- pub(crate) fn set_families_text(&self, families: Vec<Vec<u16>>) {- let families = families.iter().map(|family| CssString::from_utf16(family)).collect();+ pub(crate) fn set_families_text(&self, families: Vec<ak::Utf16String>) {+ let families = families+ .iter()+ .map(|family| CssString::from_utf16(&family.to_utf16()))+ .collect();Arc::make_mut(&mut self.data.borrow_mut()).families = families;}@@ -112,12 +115,12 @@ impl FontFeatureValuesRule {}}- pub(crate) fn entries_of(&self, kind: FontFeatureValuesRuleKind) -> Vec<(Vec<u16>, Vec<u32>)> {+ pub(crate) fn entries_of(&self, kind: FontFeatureValuesRuleKind) -> Vec<(ak::Utf16String, Vec<u32>)> {let data = self.data.borrow();data.maps[kind as usize].entries.iter()- .map(|entry| (entry.name.to_vec(), entry.values.clone()))+ .map(|entry| (ak::Utf16String::from_utf16(&entry.name), entry.values.clone())).collect()}diff --git a/Libraries/LibWeb/Rust/src/css/media_list.rs b/Libraries/LibWeb/Rust/src/css/media_list.rsindex e14e082d440..9b1312308b7 100644--- a/Libraries/LibWeb/Rust/src/css/media_list.rs+++ b/Libraries/LibWeb/Rust/src/css/media_list.rs@@ -12,6 +12,7 @@ use crate::css::parser::query_parser::{FfiMediaEnvironment, FfiQueryHandle, MediaEnvironment, MediaQuery, VisitQuerySerialization, invalid_media_query,media_query_handle, parse_media_query_list, resolve_query_feature,};+use crate::css::serialize::TextSink;use crate::css::thin_slice::ThinSlice;use std::cell::RefCell;use std::ffi::c_void;@@ -69,26 +70,29 @@ impl MediaList {}/// The serialization of the collection of media queries.- pub fn media_text(&self) -> Vec<u16> {+ pub fn media_text(&self) -> ak::Utf16String {let state = self.owner.borrow();- let mut text = Vec::new();+ let mut text = TextSink::new();for (index, query) in state.data.queries.iter().enumerate() {if index != 0 {- text.extend([u16::from(b','), u16::from(b' ')]);+ text.push_ascii(", ");}- text.extend(query.media_text());+ query+ .media_text()+ .into_iter()+ .for_each(|unit| text.push_code_unit(unit));}- text+ text.into_utf16_string()}/// The serialization of the media query at the index of the collection of media queries, if it has one there.- pub fn item(&self, index: usize) -> Option<Vec<u16>> {+ pub fn item(&self, index: usize) -> Option<ak::Utf16String> {self.owner.borrow().data.queries.get(index)- .map(|query| query.media_text())+ .map(|query| ak::Utf16String::from_utf16(&query.media_text()))}/// Replaces the collection of media queries with the result of parsing the text.@@ -229,7 +233,8 @@ pub unsafe extern "C" fn rust_media_list_serialize(visit: VisitQuerySerialization,) {let text = list.media_text();- unsafe { visit(context, text.as_ptr(), text.len()) };+ let units = text.to_utf16();+ unsafe { visit(context, units.as_ptr(), units.len()) };}#[unsafe(no_mangle)]@@ -242,7 +247,8 @@ pub unsafe extern "C" fn rust_media_list_item(let Some(text) = list.item(index) else {return false;};- unsafe { visit(context, text.as_ptr(), text.len()) };+ let units = text.to_utf16();+ unsafe { visit(context, units.as_ptr(), units.len()) };true}diff --git a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rsindex 1be657526e8..2889db537d2 100644--- a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs@@ -3080,13 +3080,13 @@ pub(crate) unsafe fn evaluate_container_query(}/// The text of a retained query condition.-pub(crate) fn serialized_query_condition(handle: &FfiQueryHandle) -> Vec<u16> {+pub(crate) fn serialized_query_condition(handle: &FfiQueryHandle) -> ak::Utf16String {let QueryTree::Expression { expression, kind } = &handle.tree else {unreachable!("the condition of a rule is an expression")};let mut sink = TextSink::new();serialize_expression(&mut sink, expression, *kind);- sink.into_utf16()+ sink.into_utf16_string()}/// Whether a retained supports condition matches.diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax.rsindex 5e3fd0fd7ac..a6bd71ed211 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs@@ -527,10 +527,8 @@ impl SyntaxNode {rust_syntax_is_single_component(self)}- pub(crate) fn serialize_to_utf16(&self) -> Vec<u16> {- let mut sink = TextSink::new();- serialize_syntax(self, &mut sink);- sink.into_utf16()+ pub(crate) fn serialize_to(&self, sink: &mut TextSink) {+ serialize_syntax(self, sink);}}diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rsindex 0aed1e2b19b..7b9c77235b4 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs@@ -54,6 +54,7 @@ use crate::css::selector_arena::{NestingTarget, RuleOrdinal};use crate::css::selector_parser::{RustParsedSelectorList, SelectorType, StyleNestingParent, parse_selector_list_from_component_values,};+use crate::css::serialize::TextSink;use crate::css::serialize::serialize_component_values_to_utf16;use crate::css::style_compute::value_is_computationally_independent;use crate::css::style_rule::StyleRule;@@ -4382,18 +4383,19 @@ pub unsafe extern "C" fn rust_page_selector_list_serialize(visit: crate::css::parser::query_parser::VisitQuerySerialization,) {let text = serialized_page_selectors(list);- unsafe { visit(context, text.as_ptr(), text.len()) };+ let units = text.to_utf16();+ unsafe { visit(context, units.as_ptr(), units.len()) };}/// The text of a list of page selectors.-pub(crate) fn serialized_page_selectors(list: &PageSelectorList) -> Vec<u16> {- let mut text = Vec::new();+pub(crate) fn serialized_page_selectors(list: &PageSelectorList) -> ak::Utf16String {+ let mut text = TextSink::new();for (index, selector) in list.selectors.iter().enumerate() {if index != 0 {- text.extend([u16::from(b','), u16::from(b' ')]);+ text.push_ascii(", ");}if let Some(name) = &selector.name {- text.extend_from_slice(name);+ name.iter().for_each(|&unit| text.push_code_unit(unit));}for pseudo_class in &selector.pseudo_classes {let name = match pseudo_class {@@ -4402,10 +4404,10 @@ pub(crate) fn serialized_page_selectors(list: &PageSelectorList) -> Vec<u16> {PagePseudoClass::First => ":first",PagePseudoClass::Blank => ":blank",};- text.extend(name.bytes().map(u16::from));+ text.push_ascii(name);}}- text+ text.into_utf16_string()}/// Retains a normalized declaration block from parsed block contents, ignoring rules.diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rsindex c19959c009c..f1b3d078077 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs@@ -319,8 +319,11 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {let children = &*rust_rule_children(&frames);let originals = &*rust_rule_children(&original_frames);let owners = RULE_OWNER_ALLOCATIONS.get();- assert_eq!(frames.find_keyframe(&utf16("from, 50%")), Some(0));- assert_eq!(frames.find_keyframe(&utf16("50%")), None);+ assert_eq!(+ frames.find_keyframe(&ak::Utf16String::from_utf16(&utf16("from, 50%"))),+ Some(0)+ );+ assert_eq!(frames.find_keyframe(&ak::Utf16String::from_utf16(&utf16("50%"))), None);assert_eq!(RULE_OWNER_ALLOCATIONS.get(), owners);let mut early = declarations_at(children, 1);let later = children.rule_at(1);@@ -348,7 +351,7 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {serialize_style_value_to_utf16(&snapshot.properties().get(0).unwrap().value),utf16("31px"));- frames.set_keyframes_name(&utf16("新しい名前"));+ frames.set_keyframes_name(&ak::Utf16String::from_utf16(&utf16("新しい名前")));assert_eq!(rust_rule_payload(&retained).name.to_utf16().unwrap(),utf16("新しい名前")@@ -364,7 +367,10 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {rust_rule_list_remove(children, 0);assert_eq!(rust_rule_list_count(&*rust_rule_children(&retained)), 1);assert_eq!(first_value(&later_declarations), utf16("23px"));- assert_eq!(retained.find_keyframe(&utf16("to")), Some(0));+ assert_eq!(+ retained.find_keyframe(&ak::Utf16String::from_utf16(&utf16("to"))),+ Some(0)+ );assert_eq!(first_value(&exposed_declarations), utf16("29px"));}}diff --git a/Libraries/LibWeb/Rust/src/css/rule/cssom.rs b/Libraries/LibWeb/Rust/src/css/rule/cssom.rsindex 2f67a388024..54e0017c74c 100644--- a/Libraries/LibWeb/Rust/src/css/rule/cssom.rs+++ b/Libraries/LibWeb/Rust/src/css/rule/cssom.rs@@ -39,54 +39,57 @@ fn css_utf16(string: &CssString) -> Utf16String {utf16(string.units())}-fn sink_to_string(sink: TextSink) -> Utf16String {- utf16(&sink.into_utf16())+fn string_units(string: &Utf16String) -> StringUnits<'_> {+ match string.as_units() {+ ak::Utf16StringUnits::Ascii(bytes) | ak::Utf16StringUnits::Latin1(bytes) => StringUnits::Ascii(bytes),+ ak::Utf16StringUnits::Utf16(units) => StringUnits::Utf16(units),+ }}/// https://drafts.csswg.org/cssom/#serialize-an-identifier-pub fn serialize_identifier(units: &[u16]) -> Utf16String {+pub fn serialize_identifier(identifier: &Utf16String) -> Utf16String {let mut sink = TextSink::new();- serialize_an_identifier(&mut sink, &StringUnits::Utf16(units));- sink_to_string(sink)+ serialize_an_identifier(&mut sink, &string_units(identifier));+ sink.into_utf16_string()}/// https://drafts.csswg.org/cssom/#serialize-a-string-pub fn serialize_string_value(units: &[u16]) -> Utf16String {+pub fn serialize_string_value(string: &Utf16String) -> Utf16String {let mut sink = TextSink::new();- serialize_a_string(&mut sink, &StringUnits::Utf16(units));- sink_to_string(sink)+ serialize_a_string(&mut sink, &string_units(string));+ sink.into_utf16_string()}fn value_text(value: &StyleValueArc) -> Utf16String {let mut sink = TextSink::new();serialize_style_value(&mut sink, value, SerializationMode::Normal);- sink_to_string(sink)+ sink.into_utf16_string()}fn syntax_text(syntax: &SyntaxNode) -> Utf16String {- utf16(&syntax.serialize_to_utf16())+ let mut sink = TextSink::new();+ syntax.serialize_to(&mut sink);+ sink.into_utf16_string()}/// https://drafts.csswg.org/css-mixins-1/#serialize-a-css-type-fn serialize_a_css_type(syntax: &SyntaxNode) -> Vec<u16> {+fn serialize_a_css_type(sink: &mut TextSink, syntax: &SyntaxNode) {// To serialize a CSS type, return the concatenation of the following:- let text = syntax.serialize_to_utf16();-// If the <css-type> consists of a single <syntax-component>, return the corresponding syntax string.if syntax.is_single_component() {- return text;+ syntax.serialize_to(sink);+ return;}// Otherwise, return the concatenation of the following:// The string "type(", i.e. "type" followed by a single LEFT PARENTHESIS (U+0028).- let mut result: Vec<u16> = "type(".encode_utf16().collect();+ sink.push_ascii("type(");// The corresponding syntax string.- result.extend(text);+ syntax.serialize_to(sink);// The string ")", i.e. a single RIGHT PARENTHESIS (U+0029).- result.push(u16::from(b')'));- result+ sink.push_ascii(")");}/// The name, type and default value of a parameter of a custom function, https://drafts.csswg.org/css-mixins-1/#dictdef-functionparameter@@ -114,8 +117,8 @@ pub const FONT_FEATURE_VALUES_KINDS: [(FontFeatureValuesRuleKind, &str); 7] = [];/// Whether the name of a @keyframes rule serializes as an identifier, and not as a string.-pub fn is_valid_animation_name(name: &[u16]) -> bool {- crate::css::parser::value_parser::is_valid_animation_name(TokenizerInput::from(name))+pub fn is_valid_animation_name(name: &Utf16String) -> bool {+ crate::css::parser::value_parser::is_valid_animation_name(name.as_units().into())}impl NativeRule {@@ -150,8 +153,8 @@ impl NativeRule {super::rust_rule_external_memory_size(self)}- pub fn cssom_set_selector_text(&self, text: &[u16], sheet_rules: Option<&NativeRuleList>) -> bool {- self.set_selector_text(TokenizerInput::from(text), sheet_rules)+ pub fn cssom_set_selector_text(&self, text: &Utf16String, sheet_rules: Option<&NativeRuleList>) -> bool {+ self.set_selector_text(text.as_units().into(), sheet_rules)}/// Whether the rule has an empty block of declarations or descriptors.@@ -191,16 +194,16 @@ impl NativeRule {css_utf16(&name.borrow())}- pub fn set_keyframes_name(&self, name: &[u16]) {+ pub fn set_keyframes_name(&self, name: &Utf16String) {let RulePayload::Keyframes(current) = &self.payload else {unreachable!("expected a @keyframes rule")};- *current.borrow_mut() = CssString::from_utf16(name);+ *current.borrow_mut() = CssString::from_utf16(&name.to_utf16());}/// The index of the last keyframe with the selector.- pub fn find_keyframe(&self, selector: &[u16]) -> Option<usize> {- let selectors = parse_keyframe_selector_list(TokenizerInput::from(selector))?;+ pub fn find_keyframe(&self, selector: &Utf16String) -> Option<usize> {+ let selectors = parse_keyframe_selector_list(selector.as_units().into())?;let matches = |frame: &Self| {let RulePayload::Keyframe(frame) = &frame.payload else {unreachable!("a @keyframes rule holds keyframes")@@ -232,15 +235,15 @@ impl NativeRule {let RulePayload::Page { selectors, .. } = &self.payload else {unreachable!("expected a @page rule")};- utf16(&serialized_page_selectors(&selectors.borrow()))+ serialized_page_selectors(&selectors.borrow())}/// Replaces the selectors of a @page rule with what the text parses to, and returns whether it parsed.- pub fn set_page_selector_text(&self, text: &[u16]) -> bool {+ pub fn set_page_selector_text(&self, text: &Utf16String) -> bool {let RulePayload::Page { selectors, .. } = &self.payload else {unreachable!("expected a @page rule")};- let Some(parsed) = parse_page_selector_list(TokenizerInput::from(text)) else {+ let Some(parsed) = parse_page_selector_list(TokenizerInput::from(text.as_units())) else {return false;};*selectors.borrow_mut() = Arc::new(PageSelectorList::new(parsed));@@ -372,9 +375,7 @@ impl NativeRule {if !parameter.syntax.is_universal() {// - A single SPACE (U+0020), followed by the result of performing serialize a CSS type on that type.sink.push_ascii(" ");- for unit in serialize_a_css_type(¶meter.syntax) {- sink.push_code_unit(unit);- }+ serialize_a_css_type(&mut sink, ¶meter.syntax);}// If the function parameter has a default value:@@ -395,11 +396,9 @@ impl NativeRule {sink.push_ascii(" returns ");// - The result of performing serialize a CSS type on that type.- for unit in serialize_a_css_type(&signature.return_type) {- sink.push_code_unit(unit);- }+ serialize_a_css_type(&mut sink, &signature.return_type);}- sink_to_string(sink)+ sink.into_utf16_string()}fn supports_handle(&self) -> &FfiQueryHandle {@@ -410,7 +409,7 @@ impl NativeRule {}pub fn supports_condition_text(&self) -> Utf16String {- utf16(&serialized_query_condition(self.supports_handle()))+ serialized_query_condition(self.supports_handle())}pub fn supports_condition_matches(&self) -> bool {@@ -423,7 +422,7 @@ impl NativeRule {};data.supports.as_ref()- .map(|supports| utf16(&serialized_query_condition(supports)))+ .map(|supports| serialized_query_condition(supports))}pub fn import_layer(&self) -> Option<Utf16String> {@@ -444,11 +443,11 @@ impl NativeRule {name: condition.name.as_ref()- .map_or_else(|| utf16(&[]), |name| serialize_identifier(name.units())),+ .map_or_else(|| utf16(&[]), |name| serialize_identifier(&css_utf16(name))),query: condition.query.as_ref()- .map_or_else(|| utf16(&[]), |query| utf16(&serialized_query_condition(query))),+ .map_or_else(|| utf16(&[]), |query| serialized_query_condition(query)),}).collect()}@@ -492,8 +491,8 @@ impl NativeRule {}/// Sets the name of a @counter-style rule, and returns whether the name is valid.- pub fn set_counter_style_name(&self, name: &[u16]) -> bool {- self.counter_style().set_name_text(name)+ pub fn set_counter_style_name(&self, name: &Utf16String) -> bool {+ self.counter_style().set_name_text(&name.to_utf16())}/// The descriptor of a @counter-style rule, serialized, or the empty string if the rule does not have it.@@ -504,10 +503,10 @@ impl NativeRule {/// https://drafts.csswg.org/css-counter-styles-3/#the-csscounterstylerule-interface/// Sets the descriptor to the value that the text parses to, and returns whether it did.- pub fn set_counter_style_descriptor(&self, name: &str, text: &[u16]) -> bool {+ pub fn set_counter_style_descriptor(&self, name: &str, text: &Utf16String) -> bool {// 1. parse the given value as the descriptor associated with the attribute.let name_units: Vec<u16> = name.encode_utf16().collect();- let Some(value) = parse_descriptor_text(COUNTER_STYLE_AT_RULE, &name_units, text) else {+ let Some(value) = parse_descriptor_text(COUNTER_STYLE_AT_RULE, &name_units, &text.to_utf16()) else {// 2. If the result is invalid according to the given descriptor’s grammar, or would cause the// @counter-style rule to not define a counter style, do nothing and abort these steps. (For example,// some systems require the symbols descriptor to contain two values.)@@ -536,7 +535,7 @@ impl NativeRule {self.font_feature_values().families_text()}- pub fn set_font_feature_values_families(&self, families: Vec<Vec<u16>>) {+ pub fn set_font_feature_values_families(&self, families: Vec<Utf16String>) {self.font_feature_values().set_families_text(families);}@@ -547,12 +546,12 @@ impl NativeRule {values}- pub fn set_font_feature_value(&self, kind: FontFeatureValuesRuleKind, name: &[u16], values: Vec<u32>) {- self.font_feature_values().set_value(kind, name, values);+ pub fn set_font_feature_value(&self, kind: FontFeatureValuesRuleKind, name: &Utf16String, values: Vec<u32>) {+ self.font_feature_values().set_value(kind, &name.to_utf16(), values);}- pub fn remove_font_feature_value(&self, kind: FontFeatureValuesRuleKind, name: &[u16]) -> bool {- self.font_feature_values().remove_value(kind, name)+ pub fn remove_font_feature_value(&self, kind: FontFeatureValuesRuleKind, name: &Utf16String) -> bool {+ self.font_feature_values().remove_value(kind, &name.to_utf16())}pub fn clear_font_feature_values(&self, kind: FontFeatureValuesRuleKind) {@@ -560,7 +559,7 @@ impl NativeRule {}/// The name and the values of each feature value of the kind, in the order of the map.- pub fn font_feature_values_entries(&self, kind: FontFeatureValuesRuleKind) -> Vec<(Vec<u16>, Vec<u32>)> {+ pub fn font_feature_values_entries(&self, kind: FontFeatureValuesRuleKind) -> Vec<(Utf16String, Vec<u32>)> {self.font_feature_values().entries_of(kind)}}diff --git a/Libraries/LibWeb/Rust/src/css/serialize.rs b/Libraries/LibWeb/Rust/src/css/serialize.rsindex 4cce0a8185a..7b79c0850e2 100644--- a/Libraries/LibWeb/Rust/src/css/serialize.rs+++ b/Libraries/LibWeb/Rust/src/css/serialize.rs@@ -102,14 +102,20 @@ pub(crate) fn for_each_code_point_utf16(units: &[u16], mut f: impl FnMut(u32)) {}/// An ASCII-until-proven-otherwise text accumulator with the shape AK::Utf16String wants.-pub(crate) struct TextSink {+pub struct TextSink {ascii: Vec<u8>,utf16: Vec<u16>,is_ascii: bool,}+impl Default for TextSink {+ fn default() -> Self {+ Self::new()+ }+}+impl TextSink {- pub(crate) fn new() -> Self {+ pub fn new() -> Self {Self {ascii: Vec::new(),utf16: Vec::new(),@@ -142,7 +148,7 @@ impl TextSink {}}- pub(crate) fn push_code_unit(&mut self, unit: u16) {+ pub fn push_code_unit(&mut self, unit: u16) {if self.is_ascii {if unit < 0x80 {self.ascii.push(unit as u8);@@ -153,6 +159,23 @@ impl TextSink {self.utf16.push(unit);}+ pub fn push_string(&mut self, text: &ak::Utf16String) {+ match text.as_units() {+ ak::Utf16StringUnits::Ascii(bytes) | ak::Utf16StringUnits::Latin1(bytes) => {+ bytes.iter().for_each(|&byte| self.push_code_unit(u16::from(byte)));+ }+ ak::Utf16StringUnits::Utf16(units) => units.iter().for_each(|&unit| self.push_code_unit(unit)),+ }+ }++ pub fn into_utf16_string(self) -> ak::Utf16String {+ if self.is_ascii {+ ak::Utf16String::from_ascii(&self.ascii)+ } else {+ ak::Utf16String::from_utf16(&self.utf16)+ }+ }+pub(crate) fn into_utf16(self) -> Vec<u16> {if self.is_ascii {self.ascii.into_iter().map(u16::from).collect()@@ -3623,25 +3646,19 @@ pub(crate) fn sink_into_raw(sink: TextSink) -> usize {string.into_raw()}-/// Serializes a style value into native ASCII-or-UTF-16 storage.-fn utf16_units_of(view: crate::css::ffi_support::FfiUtf16View<'_>) -> Vec<u16> {- let mut units = Vec::new();- if let Some(input) = view.units() {- units.reserve(input.len());- input.append_to(&mut units);- }- units+fn with_view_units<R>(view: crate::css::ffi_support::FfiUtf16View<'_>, f: impl FnOnce(StringUnits) -> R) -> R {+ with_fly_string_units(view.units().unwrap_or(TokenizerInput::Latin1(&[])), f)}fn raw_string_of(sink: TextSink) -> usize {- ak::Utf16String::from_utf16(&sink.into_utf16()).into_raw()+ sink.into_utf16_string().into_raw()}/// https://drafts.csswg.org/cssom/#serialize-an-identifier#[unsafe(no_mangle)]pub extern "C" fn rust_serialize_an_identifier(ident: crate::css::ffi_support::FfiUtf16View<'_>) -> usize {let mut sink = TextSink::new();- serialize_an_identifier(&mut sink, &StringUnits::Utf16(&utf16_units_of(ident)));+ with_view_units(ident, |units| serialize_an_identifier(&mut sink, &units));raw_string_of(sink)}@@ -3649,7 +3666,7 @@ pub extern "C" fn rust_serialize_an_identifier(ident: crate::css::ffi_support::F#[unsafe(no_mangle)]pub extern "C" fn rust_serialize_a_string(string: crate::css::ffi_support::FfiUtf16View<'_>) -> usize {let mut sink = TextSink::new();- serialize_a_string(&mut sink, &StringUnits::Utf16(&utf16_units_of(string)));+ with_view_units(string, |units| serialize_a_string(&mut sink, &units));raw_string_of(sink)}@@ -3660,7 +3677,7 @@ pub extern "C" fn rust_serialize_a_url(url: crate::css::ffi_support::FfiUtf16Vie// string, followed by ")".let mut sink = TextSink::new();sink.push_ascii("url(");- serialize_a_string(&mut sink, &StringUnits::Utf16(&utf16_units_of(url)));+ with_view_units(url, |units| serialize_a_string(&mut sink, &units));sink.push_ascii(")");raw_string_of(sink)}diff --git a/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs b/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rsindex 31b2fdca5b0..c5e279ab254 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs@@ -90,8 +90,22 @@ extern "C" fn web_css_style_inheritance_parent(#[unsafe(no_mangle)]extern "C" fn ladybird_utf16_string_unref(_raw: usize) {}#[unsafe(no_mangle)]-extern "C" fn ladybird_utf16_string_create_uninitialized(_length: usize, _has_latin1_storage: bool) -> usize {- unreachable!("no unit test makes a string the host owns");+extern "C" fn ladybird_utf16_string_create_uninitialized(length: usize, has_latin1_storage: bool) -> usize {+ // The unref stub above is a no-op, so this allocation lives until the test process exits.+ let unit_size = if has_latin1_storage { 1 } else { size_of::<u16>() };+ let bytes = size_of::<ak::Utf16StringDataHeader>() + length * unit_size;+ let storage = Box::leak(vec![0_u64; bytes.div_ceil(size_of::<u64>())].into_boxed_slice());+ let header = storage.as_mut_ptr().cast::<ak::Utf16StringDataHeader>();+ unsafe {+ header.write(ak::Utf16StringDataHeader {+ reference_count: std::sync::atomic::AtomicU32::new(1),+ length_in_code_units: u32::try_from(length).unwrap(),+ length_in_code_points: std::sync::atomic::AtomicU32::new(u32::MAX),+ hash: std::sync::atomic::AtomicU32::new(0),+ flags: std::sync::atomic::AtomicU32::new(if has_latin1_storage { 0 } else { ak::HAS_UTF16_STORAGE }),+ });+ }+ header as usize}#[unsafe(no_mangle)]unsafe extern "C" fn ladybird_utf16_fly_string_from_utf8(data: *const u8, length: usize) -> usize {diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rsindex d763e4ea8f0..e0534a2a94b 100644--- a/Libraries/LibWeb/Rust/src/css/typed_om.rs+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs@@ -917,8 +917,7 @@ pub fn calculated_style_value(/// The value of the text for the property, with no document to parse it for.pub fn parse_value_for_property(property_id: u16, css_text: &ak::Utf16String) -> Option<RetainedStyleValue> {- let units = css_text.to_utf16();- if units.is_empty() {+ if css_text.is_empty() {return None;}let value_context = FfiValueParsingContext {@@ -939,7 +938,7 @@ pub fn parse_value_for_property(property_id: u16, css_text: &ak::Utf16String) ->rust_parse_css_value(Some(&context),property_id,- FfiUtf16View::from_utf16(units.as_ref()),+ FfiUtf16View::from_input(css_text.as_units().into()),Some(&mut status),)};@@ -1007,8 +1006,7 @@ pub fn style_value_list(values: Vec<RetainedStyleValue>, comma: bool) -> Retaine// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parsepub fn parse_a_numeric_value(css_text: &ak::Utf16String) -> Option<RetainedStyleValue> {- let units = css_text.to_utf16();- if units.is_empty() {+ if css_text.is_empty() {return None;}let random_function_index = RandomFunctionIndex::new(0);@@ -1034,7 +1032,7 @@ pub fn parse_a_numeric_value(css_text: &ak::Utf16String) -> Option<RetainedStylerust_parse_entire_css_primitive_from_source(Some(&context),value_type,- FfiUtf16View::from_utf16(units.as_ref()),+ FfiUtf16View::from_input(css_text.as_units().into()),f32::MIN as f64,f32::MAX as f64,)@@ -1074,8 +1072,7 @@ pub struct RegisteredSyntax(*const core::ffi::c_void);impl RegisteredSyntax {/// https://drafts.css-houdini.org/css-properties-values-api/#consume-syntax-definitionpub fn parse(syntax: &ak::Utf16String) -> Option<Self> {- let units = syntax.to_utf16();- let parsed = rust_parse_syntax(FfiUtf16View::from_utf16(units.as_ref()), true);+ let parsed = rust_parse_syntax(FfiUtf16View::from_input(syntax.as_units().into()), true);(!parsed.is_null()).then(|| Self(parsed))}@@ -1140,8 +1137,7 @@ pub fn font_family_names(font: &ak::Utf16String) -> Option<Vec<ak::Utf16String>>/// Whether the text matches as a <supports-condition>, with no document to parse it for.pub fn supports_condition_matches(condition_text: &ak::Utf16String) -> bool {- let units = condition_text.to_utf16();- if units.is_empty() {+ if condition_text.is_empty() {return false;}let random_function_index = RandomFunctionIndex::new(0);@@ -1150,7 +1146,12 @@ pub fn supports_condition_matches(condition_text: &ak::Utf16String) -> bool {..Default::default()};// SAFETY: The context and the text are live through the call.- let handle = unsafe { rust_parse_supports_condition(FfiUtf16View::from_utf16(units.as_ref()), Some(&context)) };+ let handle = unsafe {+ rust_parse_supports_condition(+ FfiUtf16View::from_input(condition_text.as_units().into()),+ Some(&context),+ )+ };if handle.is_null() {return false;}diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rsindex 14b03d8cc55..10f533a34df 100644--- a/Libraries/LibWeb/Rust/src/lib.rs+++ b/Libraries/LibWeb/Rust/src/lib.rs@@ -45,6 +45,7 @@ pub fn css_property_names() -> impl Iterator<Item = &'static str> {.iter().map(|(name, _)| *name)}+pub use css::serialize::TextSink;pub use css::typed_om;pub use svg::gfx_path_from_path_data;