Use DOMString for internal data of Trusted Types (#37472)

This avoids various conversions back and forth between DOMString and
String. By using DOMString consistently, we avoid these
double-conversions. The only caveat are the USVString which are
initially passed into
TrustedScriptURL.

Part of #36258

Signed-off-by: Tim van der Lippe <tvanderlippe@gmail.com>
This commit is contained in:
Tim van der Lippe 2025-06-15 16:12:33 +02:00 committed by GitHub
parent dfbd5b7d21
commit 576c7445b8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 72 additions and 70 deletions

View file

@ -24,11 +24,11 @@ use crate::script_runtime::CanGc;
pub struct TrustedHTML {
reflector_: Reflector,
data: String,
data: DOMString,
}
impl TrustedHTML {
fn new_inherited(data: String) -> Self {
fn new_inherited(data: DOMString) -> Self {
Self {
reflector_: Reflector::new(),
data,
@ -36,7 +36,7 @@ impl TrustedHTML {
}
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
pub(crate) fn new(data: String, global: &GlobalScope, can_gc: CanGc) -> DomRoot<Self> {
pub(crate) fn new(data: DOMString, global: &GlobalScope, can_gc: CanGc) -> DomRoot<Self> {
reflect_dom_object(Box::new(Self::new_inherited(data)), global, can_gc)
}
@ -46,21 +46,21 @@ impl TrustedHTML {
containing_class: &str,
field: &str,
can_gc: CanGc,
) -> Fallible<String> {
) -> Fallible<DOMString> {
match value {
TrustedHTMLOrString::String(value) => {
let sink = format!("{} {}", containing_class, field);
TrustedTypePolicyFactory::get_trusted_type_compliant_string(
TrustedType::TrustedHTML,
global,
value.as_ref().to_owned(),
value,
&sink,
"'script'",
can_gc,
)
},
TrustedHTMLOrString::TrustedHTML(trusted_html) => Ok(trusted_html.to_string()),
TrustedHTMLOrString::TrustedHTML(trusted_html) => Ok(trusted_html.data.clone()),
}
}
}
@ -75,12 +75,12 @@ impl fmt::Display for TrustedHTML {
impl TrustedHTMLMethods<crate::DomTypeHolder> for TrustedHTML {
/// <https://www.w3.org/TR/trusted-types/#trustedhtml-stringification-behavior>
fn Stringifier(&self) -> DOMString {
DOMString::from(&*self.data)
self.data.clone()
}
/// <https://www.w3.org/TR/trusted-types/#dom-trustedhtml-tojson>
fn ToJSON(&self) -> DOMString {
DOMString::from(&*self.data)
self.data.clone()
}
}