Script: Remove last instances of Deref<str> and DerefMut<str> used for DOMString (#39504)

This removes the last instances of Deref<str> and DerefMut<str> used for
DOMString.
The goal is outlined in https://github.com/servo/servo/issues/39479.

Signed-off-by: Narfinger <Narfinger@users.noreply.github.com>

Testing: Compilation is the test as it just changes function names
essentially.

---------

Signed-off-by: Narfinger <Narfinger@users.noreply.github.com>
This commit is contained in:
Narfinger 2025-09-27 03:48:24 +02:00 committed by GitHub
parent 89293995f0
commit 18a1da0d80
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 85 additions and 84 deletions

View file

@ -255,7 +255,7 @@ pub(crate) fn handle_get_stylesheet_style(
.filter_map(move |i| { .filter_map(move |i| {
let rule = list.Item(i, can_gc)?; let rule = list.Item(i, can_gc)?;
let style = rule.downcast::<CSSStyleRule>()?; let style = rule.downcast::<CSSStyleRule>()?;
if *selector != *style.SelectorText() { if *selector != style.SelectorText() {
return None; return None;
}; };
Some(style.Style(can_gc)) Some(style.Style(can_gc))

View file

@ -419,7 +419,7 @@ impl consoleMethods<crate::DomTypeHolder> for Console {
// https://console.spec.whatwg.org/#timelog // https://console.spec.whatwg.org/#timelog
fn TimeLog(_cx: JSContext, global: &GlobalScope, label: DOMString, data: Vec<HandleValue>) { fn TimeLog(_cx: JSContext, global: &GlobalScope, label: DOMString, data: Vec<HandleValue>) {
if let Ok(delta) = global.time_log(label.str()) { if let Ok(delta) = global.time_log(&label) {
let message = format!("{label}: {delta}ms {}", stringify_handle_values(&data)); let message = format!("{label}: {delta}ms {}", stringify_handle_values(&data));
Console::send_string_message(global, LogLevel::Log, message.clone()); Console::send_string_message(global, LogLevel::Log, message.clone());
@ -428,7 +428,7 @@ impl consoleMethods<crate::DomTypeHolder> for Console {
// https://console.spec.whatwg.org/#timeend // https://console.spec.whatwg.org/#timeend
fn TimeEnd(global: &GlobalScope, label: DOMString) { fn TimeEnd(global: &GlobalScope, label: DOMString) {
if let Ok(delta) = global.time_end(label.str()) { if let Ok(delta) = global.time_end(&label) {
let message = format!("{label}: {delta}ms"); let message = format!("{label}: {delta}ms");
Console::send_string_message(global, LogLevel::Log, message.clone()); Console::send_string_message(global, LogLevel::Log, message.clone());

View file

@ -1534,7 +1534,7 @@ impl Document {
title.map(|title| { title.map(|title| {
// Steps 3-4. // Steps 3-4.
let value = title.child_text_content(); let value = title.child_text_content();
DOMString::from(str_join(split_html_space_chars(&value), " ")) DOMString::from(str_join(value.split_html_space_characters(), " "))
}) })
} }
@ -4740,7 +4740,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
) -> Fallible<DomRoot<Element>> { ) -> Fallible<DomRoot<Element>> {
// Step 1. If localName is not a valid element local name, // Step 1. If localName is not a valid element local name,
// then throw an "InvalidCharacterError" DOMException. // then throw an "InvalidCharacterError" DOMException.
if !is_valid_element_local_name(&local_name) { if !is_valid_element_local_name(local_name.str()) {
debug!("Not a valid element name"); debug!("Not a valid element name");
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -4759,7 +4759,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
let is = match options { let is = match options {
StringOrElementCreationOptions::String(_) => None, StringOrElementCreationOptions::String(_) => None,
StringOrElementCreationOptions::ElementCreationOptions(options) => { StringOrElementCreationOptions::ElementCreationOptions(options) => {
options.is.as_ref().map(|is| LocalName::from(&**is)) options.is.as_ref().map(|is| LocalName::from(is.str()))
}, },
}; };
Ok(Element::create( Ok(Element::create(
@ -4793,7 +4793,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
let is = match options { let is = match options {
StringOrElementCreationOptions::String(_) => None, StringOrElementCreationOptions::String(_) => None,
StringOrElementCreationOptions::ElementCreationOptions(options) => { StringOrElementCreationOptions::ElementCreationOptions(options) => {
options.is.as_ref().map(|is| LocalName::from(&**is)) options.is.as_ref().map(|is| LocalName::from(is.str()))
}, },
}; };
@ -4813,7 +4813,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
fn CreateAttribute(&self, mut local_name: DOMString, can_gc: CanGc) -> Fallible<DomRoot<Attr>> { fn CreateAttribute(&self, mut local_name: DOMString, can_gc: CanGc) -> Fallible<DomRoot<Attr>> {
// Step 1. If localName is not a valid attribute local name, // Step 1. If localName is not a valid attribute local name,
// then throw an "InvalidCharacterError" DOMException // then throw an "InvalidCharacterError" DOMException
if !is_valid_attribute_local_name(&local_name) { if !is_valid_attribute_local_name(local_name.str()) {
debug!("Not a valid attribute name"); debug!("Not a valid attribute name");
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -4904,7 +4904,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
can_gc: CanGc, can_gc: CanGc,
) -> Fallible<DomRoot<ProcessingInstruction>> { ) -> Fallible<DomRoot<ProcessingInstruction>> {
// Step 1. If target does not match the Name production, then throw an "InvalidCharacterError" DOMException. // Step 1. If target does not match the Name production, then throw an "InvalidCharacterError" DOMException.
if !matches_name_production(&target) { if !matches_name_production(target.str()) {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -4956,7 +4956,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
// https://dom.spec.whatwg.org/#dom-document-createevent // https://dom.spec.whatwg.org/#dom-document-createevent
fn CreateEvent(&self, mut interface: DOMString, can_gc: CanGc) -> Fallible<DomRoot<Event>> { fn CreateEvent(&self, mut interface: DOMString, can_gc: CanGc) -> Fallible<DomRoot<Event>> {
interface.make_ascii_lowercase(); interface.make_ascii_lowercase();
match &*interface { match interface.str() {
"beforeunloadevent" => Ok(DomRoot::upcast(BeforeUnloadEvent::new_uninitialized( "beforeunloadevent" => Ok(DomRoot::upcast(BeforeUnloadEvent::new_uninitialized(
&self.window, &self.window,
can_gc, can_gc,
@ -5842,7 +5842,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
// Servo only API to get an instance of the controls of a specific // Servo only API to get an instance of the controls of a specific
// media element matching the given id. // media element matching the given id.
fn ServoGetMediaControls(&self, id: DOMString) -> Fallible<DomRoot<ShadowRoot>> { fn ServoGetMediaControls(&self, id: DOMString) -> Fallible<DomRoot<ShadowRoot>> {
match self.media_controls.borrow().get(&*id) { match self.media_controls.borrow().get(id.str()) {
Some(m) => Ok(DomRoot::from_ref(m)), Some(m) => Ok(DomRoot::from_ref(m)),
None => Err(Error::InvalidAccess), None => Err(Error::InvalidAccess),
} }

View file

@ -62,7 +62,8 @@ impl DOMTokenList {
self.element.get_attribute(&ns!(), &self.local_name) self.element.get_attribute(&ns!(), &self.local_name)
} }
fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> { fn check_token_exceptions(&self, token: &DOMString) -> Fallible<Atom> {
let token = token.str();
match token { match token {
"" => Err(Error::Syntax(None)), "" => Err(Error::Syntax(None)),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter), slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter),
@ -234,7 +235,7 @@ impl DOMTokenListMethods<crate::DomTypeHolder> for DOMTokenList {
/// <https://dom.spec.whatwg.org/#dom-domtokenlist-supports> /// <https://dom.spec.whatwg.org/#dom-domtokenlist-supports>
fn Supports(&self, token: DOMString) -> Fallible<bool> { fn Supports(&self, token: DOMString) -> Fallible<bool> {
self.validation_steps(&token) self.validation_steps(token.str())
} }
// check-tidy: no specs after this line // check-tidy: no specs after this line

View file

@ -732,7 +732,8 @@ impl Element {
pub(crate) fn is_translate_enabled(&self) -> bool { pub(crate) fn is_translate_enabled(&self) -> bool {
let name = &local_name!("translate"); let name = &local_name!("translate");
if self.has_attribute(name) { if self.has_attribute(name) {
match_ignore_ascii_case! { &*self.get_string_attribute(name), let attribute = self.get_string_attribute(name);
match_ignore_ascii_case! { attribute.str(),
"yes" | "" => return true, "yes" | "" => return true,
"no" => return false, "no" => return false,
_ => {}, _ => {},
@ -1542,7 +1543,7 @@ impl Element {
/// Element branch of <https://dom.spec.whatwg.org/#locate-a-namespace> /// Element branch of <https://dom.spec.whatwg.org/#locate-a-namespace>
pub(crate) fn locate_namespace(&self, prefix: Option<DOMString>) -> Namespace { pub(crate) fn locate_namespace(&self, prefix: Option<DOMString>) -> Namespace {
let namespace_prefix = prefix.clone().map(|s| Prefix::from(&*s)); let namespace_prefix = prefix.clone().map(|s| Prefix::from(s.str()));
// Step 1. If prefix is "xml", then return the XML namespace. // Step 1. If prefix is "xml", then return the XML namespace.
if namespace_prefix == Some(namespace_prefix!("xml")) { if namespace_prefix == Some(namespace_prefix!("xml")) {
@ -1554,7 +1555,7 @@ impl Element {
return ns!(xmlns); return ns!(xmlns);
} }
let prefix = prefix.map(|s| LocalName::from(&*s)); let prefix = prefix.map(|s| LocalName::from(s.str()));
let inclusive_ancestor_elements = self let inclusive_ancestor_elements = self
.upcast::<Node>() .upcast::<Node>()
@ -1990,7 +1991,7 @@ impl Element {
can_gc: CanGc, can_gc: CanGc,
) -> ErrorResult { ) -> ErrorResult {
// Step 1. // Step 1.
if !matches_name_production(&name) { if !matches_name_production(name.str()) {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -2938,7 +2939,7 @@ impl ElementMethods<crate::DomTypeHolder> for Element {
) -> Fallible<bool> { ) -> Fallible<bool> {
// Step 1. If qualifiedName is not a valid attribute local name, // Step 1. If qualifiedName is not a valid attribute local name,
// then throw an "InvalidCharacterError" DOMException. // then throw an "InvalidCharacterError" DOMException.
if !is_valid_attribute_local_name(&name) { if !is_valid_attribute_local_name(name.str()) {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -2987,7 +2988,7 @@ impl ElementMethods<crate::DomTypeHolder> for Element {
) -> ErrorResult { ) -> ErrorResult {
// Step 1. If qualifiedName does not match the Name production in XML, // Step 1. If qualifiedName does not match the Name production in XML,
// then throw an "InvalidCharacterError" DOMException. // then throw an "InvalidCharacterError" DOMException.
if !is_valid_attribute_local_name(&name) { if !is_valid_attribute_local_name(name.str()) {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -3111,7 +3112,7 @@ impl ElementMethods<crate::DomTypeHolder> for Element {
HTMLCollection::by_qualified_name( HTMLCollection::by_qualified_name(
&window, &window,
self.upcast(), self.upcast(),
LocalName::from(&*localname), LocalName::from(localname.str()),
can_gc, can_gc,
) )
} }
@ -3733,7 +3734,7 @@ impl ElementMethods<crate::DomTypeHolder> for Element {
let doc = self.owner_document(); let doc = self.owner_document();
let url = doc.url(); let url = doc.url();
let selectors = match SelectorParser::parse_author_origin_no_namespace( let selectors = match SelectorParser::parse_author_origin_no_namespace(
&selectors, selectors.str(),
&UrlExtraData(url.get_arc()), &UrlExtraData(url.get_arc()),
) { ) {
Err(_) => return Err(Error::Syntax(None)), Err(_) => return Err(Error::Syntax(None)),
@ -3760,7 +3761,7 @@ impl ElementMethods<crate::DomTypeHolder> for Element {
let doc = self.owner_document(); let doc = self.owner_document();
let url = doc.url(); let url = doc.url();
let selectors = match SelectorParser::parse_author_origin_no_namespace( let selectors = match SelectorParser::parse_author_origin_no_namespace(
&selectors, selectors.str(),
&UrlExtraData(url.get_arc()), &UrlExtraData(url.get_arc()),
) { ) {
Err(_) => return Err(Error::Syntax(None)), Err(_) => return Err(Error::Syntax(None)),
@ -5477,12 +5478,12 @@ pub(crate) fn reflect_referrer_policy_attribute(element: &Element) -> DOMString
pub(crate) fn referrer_policy_for_element(element: &Element) -> ReferrerPolicy { pub(crate) fn referrer_policy_for_element(element: &Element) -> ReferrerPolicy {
element element
.get_attribute_by_name(DOMString::from_string(String::from("referrerpolicy"))) .get_attribute_by_name(DOMString::from_string(String::from("referrerpolicy")))
.map(|attribute: DomRoot<Attr>| determine_policy_for_token(&attribute.Value())) .map(|attribute: DomRoot<Attr>| determine_policy_for_token(attribute.Value().str()))
.unwrap_or(element.owner_document().get_referrer_policy()) .unwrap_or(element.owner_document().get_referrer_policy())
} }
pub(crate) fn cors_setting_for_element(element: &Element) -> Option<CorsSettings> { pub(crate) fn cors_setting_for_element(element: &Element) -> Option<CorsSettings> {
reflect_cross_origin_attribute(element).and_then(|attr| match &*attr { reflect_cross_origin_attribute(element).and_then(|attr| match attr.str() {
"anonymous" => Some(CorsSettings::Anonymous), "anonymous" => Some(CorsSettings::Anonymous),
"use-credentials" => Some(CorsSettings::UseCredentials), "use-credentials" => Some(CorsSettings::UseCredentials),
_ => unreachable!(), _ => unreachable!(),

View file

@ -567,7 +567,7 @@ impl EventSourceMethods<crate::DomTypeHolder> for EventSource {
// Step 3 Let urlRecord be the result of encoding-parsing a URL given url, // Step 3 Let urlRecord be the result of encoding-parsing a URL given url,
// relative to settings. // relative to settings.
let base_url = global.api_base_url(); let base_url = global.api_base_url();
let url_record = match base_url.join(&url) { let url_record = match base_url.join(url.str()) {
Ok(u) => u, Ok(u) => u,
// Step 4 If urlRecord is failure, then throw a "SyntaxError" DOMException. // Step 4 If urlRecord is failure, then throw a "SyntaxError" DOMException.
Err(_) => return Err(Error::Syntax(None)), Err(_) => return Err(Error::Syntax(None)),

View file

@ -136,7 +136,7 @@ impl FileMethods<crate::DomTypeHolder> for File {
.map(|modified| OffsetDateTime::UNIX_EPOCH + Duration::milliseconds(modified)) .map(|modified| OffsetDateTime::UNIX_EPOCH + Duration::milliseconds(modified))
.map(Into::into); .map(Into::into);
let type_string = normalize_type_string(blobPropertyBag.type_.as_ref()); let type_string = normalize_type_string(blobPropertyBag.type_.str());
Ok(File::new_with_proto( Ok(File::new_with_proto(
global, global,
proto, proto,

View file

@ -74,7 +74,7 @@ pub struct FontFace {
fn parse_font_face_descriptors( fn parse_font_face_descriptors(
global: &GlobalScope, global: &GlobalScope,
family_name: &DOMString, family_name: &DOMString,
sources: Option<&str>, sources: Option<&DOMString>,
input_descriptors: &FontFaceDescriptors, input_descriptors: &FontFaceDescriptors,
) -> Fallible<FontFaceRule> { ) -> Fallible<FontFaceRule> {
let window = global.as_window(); // TODO: Support calling FontFace APIs from Worker let window = global.as_window(); // TODO: Support calling FontFace APIs from Worker

View file

@ -39,7 +39,7 @@ impl FormData {
let data = match form_datums { let data = match form_datums {
Some(data) => data Some(data) => data
.iter() .iter()
.map(|datum| (NoTrace(LocalName::from(datum.name.as_ref())), datum.clone())) .map(|datum| (NoTrace(LocalName::from(datum.name.str())), datum.clone()))
.collect::<Vec<(NoTrace<LocalName>, FormDatum)>>(), .collect::<Vec<(NoTrace<LocalName>, FormDatum)>>(),
None => Vec::new(), None => Vec::new(),
}; };

View file

@ -2423,7 +2423,7 @@ impl GlobalScope {
/// Computes the delta time since a label has been created /// Computes the delta time since a label has been created
/// ///
/// Returns an error if the label does not exist. /// Returns an error if the label does not exist.
pub(crate) fn time_log(&self, label: &str) -> Result<u64, ()> { pub(crate) fn time_log(&self, label: &DOMString) -> Result<u64, ()> {
self.console_timers self.console_timers
.borrow() .borrow()
.get(label) .get(label)
@ -2435,7 +2435,7 @@ impl GlobalScope {
/// tracking the label. /// tracking the label.
/// ///
/// Returns an error if the label does not exist. /// Returns an error if the label does not exist.
pub(crate) fn time_end(&self, label: &str) -> Result<u64, ()> { pub(crate) fn time_end(&self, label: &DOMString) -> Result<u64, ()> {
self.console_timers self.console_timers
.borrow_mut() .borrow_mut()
.remove(label) .remove(label)
@ -2849,7 +2849,7 @@ impl GlobalScope {
compiled_script.set(Compile1( compiled_script.set(Compile1(
*cx, *cx,
options.ptr, options.ptr,
&mut transform_str_to_source_text(text_code), &mut transform_str_to_source_text(text_code.str()),
)); ));
if compiled_script.is_null() { if compiled_script.is_null() {

View file

@ -265,7 +265,7 @@ impl KeyboardEventMethods<crate::DomTypeHolder> for KeyboardEvent {
/// <https://w3c.github.io/uievents/#dom-keyboardevent-getmodifierstate> /// <https://w3c.github.io/uievents/#dom-keyboardevent-getmodifierstate>
fn GetModifierState(&self, key_arg: DOMString) -> bool { fn GetModifierState(&self, key_arg: DOMString) -> bool {
self.modifiers.get().contains(match &*key_arg { self.modifiers.get().contains(match key_arg.str() {
"Alt" => Modifiers::ALT, "Alt" => Modifiers::ALT,
"AltGraph" => Modifiers::ALT_GRAPH, "AltGraph" => Modifiers::ALT_GRAPH,
"CapsLock" => Modifiers::CAPS_LOCK, "CapsLock" => Modifiers::CAPS_LOCK,

View file

@ -164,7 +164,7 @@ impl MediaListMethods<crate::DomTypeHolder> for MediaList {
let mut guard = self.shared_lock().write(); let mut guard = self.shared_lock().write();
let media_queries_borrowed = self.media_queries.borrow(); let media_queries_borrowed = self.media_queries.borrow();
let media_queries = media_queries_borrowed.write_with(&mut guard); let media_queries = media_queries_borrowed.write_with(&mut guard);
*media_queries = Self::parse_media_list(&value, global.as_window()); *media_queries = Self::parse_media_list(value.str(), global.as_window());
self.parent_stylesheet.notify_invalidations(); self.parent_stylesheet.notify_invalidations();
} }
@ -198,7 +198,7 @@ impl MediaListMethods<crate::DomTypeHolder> for MediaList {
fn AppendMedium(&self, medium: DOMString) { fn AppendMedium(&self, medium: DOMString) {
// Step 1 // Step 1
let global = self.global(); let global = self.global();
let m = Self::parse_media_query(&medium, global.as_window()); let m = Self::parse_media_query(medium.str(), global.as_window());
// Step 2 // Step 2
if m.is_err() { if m.is_err() {
return; return;
@ -233,7 +233,7 @@ impl MediaListMethods<crate::DomTypeHolder> for MediaList {
fn DeleteMedium(&self, medium: DOMString) { fn DeleteMedium(&self, medium: DOMString) {
// Step 1 // Step 1
let global = self.global(); let global = self.global();
let m = Self::parse_media_query(&medium, global.as_window()); let m = Self::parse_media_query(medium.str(), global.as_window());
// Step 2 // Step 2
if m.is_err() { if m.is_err() {
return; return;

View file

@ -141,7 +141,7 @@ impl MediaStreamMethods<crate::DomTypeHolder> for MediaStream {
self.tracks self.tracks
.borrow() .borrow()
.iter() .iter()
.find(|x| x.id().id().to_string() == *id) .find(|x| x.id().id().to_string() == id)
.map(|x| DomRoot::from_ref(&**x)) .map(|x| DomRoot::from_ref(&**x))
} }

View file

@ -562,7 +562,7 @@ impl MouseEventMethods<crate::DomTypeHolder> for MouseEvent {
/// <https://w3c.github.io/uievents/#dom-mouseevent-getmodifierstate> /// <https://w3c.github.io/uievents/#dom-mouseevent-getmodifierstate>
fn GetModifierState(&self, key_arg: DOMString) -> bool { fn GetModifierState(&self, key_arg: DOMString) -> bool {
self.modifiers.get().contains(match &*key_arg { self.modifiers.get().contains(match key_arg.str() {
"Alt" => Modifiers::ALT, "Alt" => Modifiers::ALT,
"AltGraph" => Modifiers::ALT_GRAPH, "AltGraph" => Modifiers::ALT_GRAPH,
"CapsLock" => Modifiers::CAPS_LOCK, "CapsLock" => Modifiers::CAPS_LOCK,

View file

@ -138,7 +138,7 @@ impl MutationObserver {
.options .options
.attribute_filter .attribute_filter
.iter() .iter()
.any(|s| **s == **name) .any(|s| *s == **name)
{ {
continue; continue;
} }

View file

@ -396,7 +396,7 @@ impl NavigatorMethods<crate::DomTypeHolder> for Navigator {
// since it lowercases `charset=UTF-8`: https://github.com/hyperium/mime/issues/116 // since it lowercases `charset=UTF-8`: https://github.com/hyperium/mime/issues/116
headers.insert( headers.insert(
header::CONTENT_TYPE, header::CONTENT_TYPE,
HeaderValue::from_str(content_type).unwrap(), HeaderValue::from_str(content_type.str()).unwrap(),
); );
} }
request_body = Some(extracted_body.into_net_request_body().0); request_body = Some(extracted_body.into_net_request_body().0);

View file

@ -1128,7 +1128,7 @@ impl Node {
// Step 1. // Step 1.
let doc = self.owner_doc(); let doc = self.owner_doc();
match SelectorParser::parse_author_origin_no_namespace( match SelectorParser::parse_author_origin_no_namespace(
&selectors, selectors.str(),
&UrlExtraData(doc.url().get_arc()), &UrlExtraData(doc.url().get_arc()),
) { ) {
// Step 2. // Step 2.
@ -1165,7 +1165,7 @@ impl Node {
// Step 1. // Step 1.
let url = self.owner_doc().url(); let url = self.owner_doc().url();
match SelectorParser::parse_author_origin_no_namespace( match SelectorParser::parse_author_origin_no_namespace(
&selectors, selectors.str(),
&UrlExtraData(url.get_arc()), &UrlExtraData(url.get_arc()),
) { ) {
// Step 2. // Step 2.
@ -3076,7 +3076,7 @@ impl Node {
let mut content = String::new(); let mut content = String::new();
for node in iterator { for node in iterator {
if let Some(text) = node.downcast::<Text>() { if let Some(text) = node.downcast::<Text>() {
content.push_str(&text.upcast::<CharacterData>().data()); content.push_str(text.upcast::<CharacterData>().data().str());
} }
} }
DOMString::from(content) DOMString::from(content)
@ -3663,7 +3663,7 @@ impl NodeMethods<crate::DomTypeHolder> for Node {
.move_to_text_child_at(self, index as u32, &node, length); .move_to_text_child_at(self, index as u32, &node, length);
let sibling_cdata = sibling.downcast::<CharacterData>().unwrap(); let sibling_cdata = sibling.downcast::<CharacterData>().unwrap();
length += sibling_cdata.Length(); length += sibling_cdata.Length();
cdata.append_data(&sibling_cdata.data()); cdata.append_data(sibling_cdata.data().str());
Node::remove(&sibling, self, SuppressObserver::Unsuppressed, can_gc); Node::remove(&sibling, self, SuppressObserver::Unsuppressed, can_gc);
} }
} else { } else {

View file

@ -99,7 +99,7 @@ impl PerformanceEntryList {
entry_type: DOMString, entry_type: DOMString,
) { ) {
self.entries.retain(|e| { self.entries.retain(|e| {
*e.entry_type() != *entry_type || name.as_ref().is_some_and(|name_| *e.name() != *name_) *e.entry_type() != entry_type || name.as_ref().is_some_and(|name_| e.name() != name_)
}); });
} }
@ -111,7 +111,7 @@ impl PerformanceEntryList {
self.entries self.entries
.iter() .iter()
.rev() .rev()
.find(|e| *e.entry_type() == *entry_type && *e.name() == *name) .find(|e| *e.entry_type() == entry_type && *e.name() == name)
.and_then(|entry| entry.start_time()) .and_then(|entry| entry.start_time())
} }
} }
@ -489,7 +489,7 @@ impl PerformanceMethods<crate::DomTypeHolder> for Performance {
fn Mark(&self, mark_name: DOMString, can_gc: CanGc) -> Fallible<()> { fn Mark(&self, mark_name: DOMString, can_gc: CanGc) -> Fallible<()> {
let global = self.global(); let global = self.global();
// Step 1. // Step 1.
if global.is::<Window>() && INVALID_ENTRY_NAMES.contains(&mark_name.as_ref()) { if global.is::<Window>() && INVALID_ENTRY_NAMES.contains(&mark_name.str()) {
return Err(Error::Syntax(None)); return Err(Error::Syntax(None));
} }

View file

@ -197,7 +197,7 @@ impl PerformanceObserverMethods<crate::DomTypeHolder> for PerformanceObserver {
// Steps 6.1 - 6.2 // Steps 6.1 - 6.2
let entry_types = entry_types let entry_types = entry_types
.iter() .iter()
.filter(|e| VALID_ENTRY_TYPES.contains(&e.as_ref())) .filter(|e| VALID_ENTRY_TYPES.contains(&e.str()))
.cloned() .cloned()
.collect::<Vec<DOMString>>(); .collect::<Vec<DOMString>>();
@ -219,7 +219,7 @@ impl PerformanceObserverMethods<crate::DomTypeHolder> for PerformanceObserver {
Ok(()) Ok(())
} else if let Some(entry_type) = &options.type_ { } else if let Some(entry_type) = &options.type_ {
// Step 7.2 // Step 7.2
if !VALID_ENTRY_TYPES.contains(&entry_type.as_ref()) { if !VALID_ENTRY_TYPES.contains(&entry_type.str()) {
Console::internal_warn( Console::internal_warn(
&self.global(), &self.global(),
DOMString::from("No valid entry type provided to observe()."), DOMString::from("No valid entry type provided to observe()."),

View file

@ -1077,12 +1077,13 @@ impl RangeMethods<crate::DomTypeHolder> for Range {
// Step 3. // Step 3.
s.push_str( s.push_str(
&char_data char_data
.SubstringData( .SubstringData(
self.start_offset(), self.start_offset(),
char_data.Length() - self.start_offset(), char_data.Length() - self.start_offset(),
) )
.unwrap(), .unwrap()
.str(),
); );
} }
@ -1094,14 +1095,14 @@ impl RangeMethods<crate::DomTypeHolder> for Range {
for child in iter { for child in iter {
if self.contains(child.upcast()) { if self.contains(child.upcast()) {
s.push_str(&child.upcast::<CharacterData>().Data()); s.push_str(child.upcast::<CharacterData>().Data().str());
} }
} }
// Step 5. // Step 5.
if let Some(text_node) = end_node.downcast::<Text>() { if let Some(text_node) = end_node.downcast::<Text>() {
let char_data = text_node.upcast::<CharacterData>(); let char_data = text_node.upcast::<CharacterData>();
s.push_str(&char_data.SubstringData(0, self.end_offset()).unwrap()); s.push_str(char_data.SubstringData(0, self.end_offset()).unwrap().str());
} }
// Step 6. // Step 6.

View file

@ -152,7 +152,7 @@ impl SendReportsToEndpoints for GlobalScope {
let mut origin_map: HashMap<ImmutableOrigin, Vec<&Report>> = HashMap::new(); let mut origin_map: HashMap<ImmutableOrigin, Vec<&Report>> = HashMap::new();
// Step 3.2. For each report in report list: // Step 3.2. For each report in report list:
for report in report_list { for report in report_list {
let Ok(url) = ServoUrl::parse(&report.url) else { let Ok(url) = ServoUrl::parse(report.url.str()) else {
continue; continue;
}; };
// Step 3.2.1. Let origin be the origin of reports url. // Step 3.2.1. Let origin be the origin of reports url.

View file

@ -96,7 +96,7 @@ impl StylePropertyMapReadOnlyMethods<crate::DomTypeHolder> for StylePropertyMapR
} else { } else {
Ordering::Greater Ordering::Greater
} }
} else if custom_properties::parse_name(key2).is_ok() { } else if custom_properties::parse_name(key2.str()).is_ok() {
Ordering::Less Ordering::Less
} else { } else {
key1.cmp(key2) key1.cmp(key2)

View file

@ -3791,7 +3791,7 @@ impl JsonWebKeyExt for JsonWebKey {
fn get_usages_from_key_ops(&self) -> Result<Vec<KeyUsage>, Error> { fn get_usages_from_key_ops(&self) -> Result<Vec<KeyUsage>, Error> {
let mut usages = vec![]; let mut usages = vec![];
for op in self.key_ops.as_ref().ok_or(Error::Data)? { for op in self.key_ops.as_ref().ok_or(Error::Data)? {
usages.push(KeyUsage::from_str(op).map_err(|_| Error::Data)?); usages.push(KeyUsage::from_str(op.str()).map_err(|_| Error::Data)?);
} }
Ok(usages) Ok(usages)
} }

View file

@ -383,7 +383,7 @@ impl WebGLProgram {
.active_attribs .active_attribs
.borrow() .borrow()
.iter() .iter()
.find(|attrib| *attrib.name == *name) .find(|attrib| *attrib.name == name)
.and_then(|attrib| attrib.location.map(|l| l as i32)) .and_then(|attrib| attrib.location.map(|l| l as i32))
.unwrap_or(-1); .unwrap_or(-1);
Ok(location) Ok(location)

View file

@ -492,7 +492,7 @@ unsafe extern "C" fn code_for_eval_gets(
let script_string = trusted_script.data(); let script_string = trusted_script.data();
let new_string = JS_NewStringCopyN( let new_string = JS_NewStringCopyN(
*cx, *cx,
script_string.as_ptr() as *const libc::c_char, script_string.str().as_ptr() as *const libc::c_char,
script_string.len(), script_string.len(),
); );
code_for_eval.set(new_string); code_for_eval.set(new_string);

View file

@ -474,7 +474,7 @@ impl<T: ClipboardProvider> TextInput<T> {
f(&mut acc, &self.lines[start.line].str()[start_offset..]); f(&mut acc, &self.lines[start.line].str()[start_offset..]);
for line in &self.lines[start.line + 1..end.line] { for line in &self.lines[start.line + 1..end.line] {
f(&mut acc, "\n"); f(&mut acc, "\n");
f(&mut acc, line); f(&mut acc, line.str());
} }
f(&mut acc, "\n"); f(&mut acc, "\n");
f(&mut acc, &self.lines[end.line].str()[..end_offset]) f(&mut acc, &self.lines[end.line].str()[..end_offset])
@ -784,11 +784,11 @@ impl<T: ClipboardProvider> TextInput<T> {
Direction::Backward => { Direction::Backward => {
let input: &str; let input: &str;
if current_index == UTF8Bytes::zero() && current_line > 0 { if current_index == UTF8Bytes::zero() && current_line > 0 {
input = &self.lines[current_line - 1]; input = self.lines[current_line - 1].str();
newline_adjustment = UTF8Bytes::one(); newline_adjustment = UTF8Bytes::one();
} else { } else {
let UTF8Bytes(remaining) = current_index; let UTF8Bytes(remaining) = current_index;
input = &self.lines[current_line][..remaining]; input = &self.lines[current_line].str()[..remaining];
} }
let mut iter = input.split_word_bounds().rev(); let mut iter = input.split_word_bounds().rev();
@ -809,11 +809,11 @@ impl<T: ClipboardProvider> TextInput<T> {
let remaining = self.current_line_length().saturating_sub(current_index); let remaining = self.current_line_length().saturating_sub(current_index);
if remaining == UTF8Bytes::zero() && self.lines.len() > self.edit_point.line + 1 if remaining == UTF8Bytes::zero() && self.lines.len() > self.edit_point.line + 1
{ {
input = &self.lines[current_line + 1]; input = self.lines[current_line + 1].str();
newline_adjustment = UTF8Bytes::one(); newline_adjustment = UTF8Bytes::one();
} else { } else {
let UTF8Bytes(current_offset) = current_index; let UTF8Bytes(current_offset) = current_index;
input = &self.lines[current_line][current_offset..]; input = &self.lines[current_line].str()[current_offset..];
} }
let mut iter = input.split_word_bounds(); let mut iter = input.split_word_bounds();
@ -1123,6 +1123,7 @@ impl<T: ClipboardProvider> TextInput<T> {
self.lines = if self.multiline { self.lines = if self.multiline {
// https://html.spec.whatwg.org/multipage/#textarea-line-break-normalisation-transformation // https://html.spec.whatwg.org/multipage/#textarea-line-break-normalisation-transformation
content content
.str()
.replace("\r\n", "\n") .replace("\r\n", "\n")
.split(['\n', '\r']) .split(['\n', '\r'])
.map(DOMString::from) .map(DOMString::from)

View file

@ -8,7 +8,7 @@ use std::default::Default;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::str::{Chars, EncodeUtf16, FromStr}; use std::str::{CharIndices, Chars, EncodeUtf16, FromStr};
use std::sync::LazyLock; use std::sync::LazyLock;
use std::{fmt, ops, slice, str}; use std::{fmt, ops, slice, str};
@ -358,6 +358,24 @@ impl DOMString {
pub fn contains_html_space_characters(&self) -> bool { pub fn contains_html_space_characters(&self) -> bool {
self.0.contains(HTML_SPACE_CHARACTERS) self.0.contains(HTML_SPACE_CHARACTERS)
} }
pub fn split_html_space_characters(&self) -> impl Iterator<Item = &str> {
self.0
.split(HTML_SPACE_CHARACTERS)
.filter(|s| !s.is_empty())
}
pub fn char_indices(&self) -> CharIndices<'_> {
self.0.char_indices()
}
pub fn strip_prefix(&self, pattern: &str) -> Option<&str> {
self.0.strip_prefix(pattern)
}
pub fn split(&self, c: char) -> impl Iterator<Item = &str> {
self.0.split(c)
}
} }
/// Because this converts to a DOMString it becomes UTF-8 encoded which is closer to /// Because this converts to a DOMString it becomes UTF-8 encoded which is closer to
@ -431,27 +449,6 @@ impl Default for DOMString {
} }
} }
impl Deref for DOMString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&self.0
}
}
impl DerefMut for DOMString {
#[inline]
fn deref_mut(&mut self) -> &mut str {
&mut self.0
}
}
impl AsRef<str> for DOMString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for DOMString { impl fmt::Display for DOMString {
#[inline] #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {