Script: Change script/dom/{bluetooth,canvas,html} to not rely on Deref<str> for DOMString (#39480)

This is part of the future work of implementing LazyDOMString as
outlined in https://github.com/servo/servo/issues/39479.

We use str() method or direct implementations on DOMString for these
methods. We also change some types.

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


Testing: This is essentially just renaming a method and a type and
should not change functionality.

Signed-off-by: Narfinger <Narfinger@users.noreply.github.com>
This commit is contained in:
Narfinger 2025-09-25 17:53:21 +02:00 committed by GitHub
parent 1e471b9b41
commit a4c8ffe753
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 97 additions and 95 deletions

View file

@ -432,7 +432,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth
let mut map = HashMap::new(); let mut map = HashMap::new();
for (key, bdfi) in manufacturer_data_map.iter() { for (key, bdfi) in manufacturer_data_map.iter() {
// Step 7.1 - 7.2. // Step 7.1 - 7.2.
let manufacturer_id = match u16::from_str(key.as_ref()) { let manufacturer_id = match u16::from_str(key.str()) {
Ok(id) => id, Ok(id) => id,
Err(err) => { Err(err) => {
return Err(Type(format!("{} {} {}", KEY_CONVERSION_ERROR, key, err))); return Err(Type(format!("{} {} {}", KEY_CONVERSION_ERROR, key, err)));
@ -461,7 +461,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth
} }
let mut map = HashMap::new(); let mut map = HashMap::new();
for (key, bdfi) in service_data_map.iter() { for (key, bdfi) in service_data_map.iter() {
let service_name = match u32::from_str(key.as_ref()) { let service_name = match u32::from_str(key.str()) {
// Step 9.1. // Step 9.1.
Ok(number) => StringOrUnsignedLong::UnsignedLong(number), Ok(number) => StringOrUnsignedLong::UnsignedLong(number),
// Step 9.2. // Step 9.2.
@ -687,7 +687,7 @@ impl PermissionAlgorithm for Bluetooth {
continue; continue;
} }
} }
let device_id = String::from(allowed_device.deviceId.as_ref()); let device_id = String::from(allowed_device.deviceId.str());
// Step 6.2. // Step 6.2.
if let Some(ref filters) = descriptor.filters { if let Some(ref filters) = descriptor.filters {

View file

@ -153,7 +153,7 @@ impl BluetoothRemoteGATTCharacteristicMethods<crate::DomTypeHolder>
let p = Promise::new_in_current_realm(comp, can_gc); let p = Promise::new_in_current_realm(comp, can_gc);
// Step 1. // Step 1.
if uuid_is_blocklisted(self.uuid.as_ref(), Blocklist::Reads) { if uuid_is_blocklisted(self.uuid.str(), Blocklist::Reads) {
p.reject_error(Security, can_gc); p.reject_error(Security, can_gc);
return p; return p;
} }
@ -191,7 +191,7 @@ impl BluetoothRemoteGATTCharacteristicMethods<crate::DomTypeHolder>
let p = Promise::new_in_current_realm(comp, can_gc); let p = Promise::new_in_current_realm(comp, can_gc);
// Step 1. // Step 1.
if uuid_is_blocklisted(self.uuid.as_ref(), Blocklist::Writes) { if uuid_is_blocklisted(self.uuid.str(), Blocklist::Writes) {
p.reject_error(Security, can_gc); p.reject_error(Security, can_gc);
return p; return p;
} }
@ -242,7 +242,7 @@ impl BluetoothRemoteGATTCharacteristicMethods<crate::DomTypeHolder>
let p = Promise::new_in_current_realm(comp, can_gc); let p = Promise::new_in_current_realm(comp, can_gc);
// Step 1. // Step 1.
if uuid_is_blocklisted(self.uuid.as_ref(), Blocklist::Reads) { if uuid_is_blocklisted(self.uuid.str(), Blocklist::Reads) {
p.reject_error(Security, can_gc); p.reject_error(Security, can_gc);
return p; return p;
} }

View file

@ -101,7 +101,7 @@ impl BluetoothRemoteGATTDescriptorMethods<crate::DomTypeHolder> for BluetoothRem
let p = Promise::new_in_current_realm(comp, can_gc); let p = Promise::new_in_current_realm(comp, can_gc);
// Step 1. // Step 1.
if uuid_is_blocklisted(self.uuid.as_ref(), Blocklist::Reads) { if uuid_is_blocklisted(self.uuid.str(), Blocklist::Reads) {
p.reject_error(Security, can_gc); p.reject_error(Security, can_gc);
return p; return p;
} }
@ -138,7 +138,7 @@ impl BluetoothRemoteGATTDescriptorMethods<crate::DomTypeHolder> for BluetoothRem
let p = Promise::new_in_current_realm(comp, can_gc); let p = Promise::new_in_current_realm(comp, can_gc);
// Step 1. // Step 1.
if uuid_is_blocklisted(self.uuid.as_ref(), Blocklist::Writes) { if uuid_is_blocklisted(self.uuid.str(), Blocklist::Writes) {
p.reject_error(Security, can_gc); p.reject_error(Security, can_gc);
return p; return p;
} }

View file

@ -638,7 +638,7 @@ fn resolve_uuid_name(
StringOrUnsignedLong::String(dstring) => { StringOrUnsignedLong::String(dstring) => {
// Step 2. // Step 2.
let regex = Regex::new(VALID_UUID_REGEX).unwrap(); let regex = Regex::new(VALID_UUID_REGEX).unwrap();
if regex.is_match(&dstring) { if regex.is_match(dstring.str()) {
Ok(dstring) Ok(dstring)
} else { } else {
// Step 3. // Step 3.

View file

@ -1298,7 +1298,7 @@ impl CanvasState {
repetition.push_str("repeat"); repetition.push_str("repeat");
} }
if let Ok(rep) = RepetitionStyle::from_str(&repetition) { if let Ok(rep) = RepetitionStyle::from_str(repetition.str()) {
let size = snapshot.size(); let size = snapshot.size();
Ok(Some(CanvasPattern::new( Ok(Some(CanvasPattern::new(
global, global,
@ -1357,7 +1357,7 @@ impl CanvasState {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
pub(super) fn set_global_composite_operation(&self, op_str: DOMString) { pub(super) fn set_global_composite_operation(&self, op_str: DOMString) {
if let Ok(op) = CompositionOrBlending::from_str(&op_str) { if let Ok(op) = CompositionOrBlending::from_str(op_str.str()) {
self.state.borrow_mut().global_composition = op; self.state.borrow_mut().global_composition = op;
} }
} }
@ -2506,9 +2506,9 @@ impl UnshapedTextRun<'_> {
pub(super) fn parse_color( pub(super) fn parse_color(
canvas: Option<&HTMLCanvasElement>, canvas: Option<&HTMLCanvasElement>,
string: &str, string: &DOMString,
) -> Result<AbsoluteColor, ()> { ) -> Result<AbsoluteColor, ()> {
let mut input = ParserInput::new(string); let mut input = ParserInput::new(string.str());
let mut parser = Parser::new(&mut input); let mut parser = Parser::new(&mut input);
let url = Url::parse("about:blank").unwrap().into(); let url = Url::parse("about:blank").unwrap().into();
let context = ParserContext::new( let context = ParserContext::new(

View file

@ -297,7 +297,7 @@ impl OffscreenCanvasMethods<crate::DomTypeHolder> for OffscreenCanvas {
return Err(Error::InvalidState); return Err(Error::InvalidState);
} }
match &*id { match id.str() {
"2d" => Ok(self "2d" => Ok(self
.get_or_init_2d_context(can_gc) .get_or_init_2d_context(can_gc)
.map(RootedOffscreenRenderingContext::OffscreenCanvasRenderingContext2D)), .map(RootedOffscreenRenderingContext::OffscreenCanvasRenderingContext2D)),

View file

@ -304,7 +304,7 @@ impl HTMLAreaElement {
pub(crate) fn get_shape_from_coords(&self) -> Option<Area> { pub(crate) fn get_shape_from_coords(&self) -> Option<Area> {
let elem = self.upcast::<Element>(); let elem = self.upcast::<Element>();
let shape = elem.get_string_attribute(&"shape".into()); let shape = elem.get_string_attribute(&"shape".into());
let shp: Shape = match_ignore_ascii_case! { &shape, let shp: Shape = match_ignore_ascii_case! { shape.str(),
"circle" => Shape::Circle, "circle" => Shape::Circle,
"circ" => Shape::Circle, "circ" => Shape::Circle,
"rectangle" => Shape::Rectangle, "rectangle" => Shape::Rectangle,
@ -315,7 +315,7 @@ impl HTMLAreaElement {
}; };
if elem.has_attribute(&"coords".into()) { if elem.has_attribute(&"coords".into()) {
let attribute = elem.get_string_attribute(&"coords".into()); let attribute = elem.get_string_attribute(&"coords".into());
Area::parse(&attribute, shp) Area::parse(attribute.str(), shp)
} else { } else {
None None
} }

View file

@ -449,7 +449,7 @@ impl HTMLCanvasElementMethods<crate::DomTypeHolder> for HTMLCanvasElement {
return Err(Error::InvalidState); return Err(Error::InvalidState);
} }
Ok(match &*id { Ok(match id.str() {
"2d" => self "2d" => self
.get_or_init_2d_context(can_gc) .get_or_init_2d_context(can_gc)
.map(RootedRenderingContext::CanvasRenderingContext2D), .map(RootedRenderingContext::CanvasRenderingContext2D),

View file

@ -270,7 +270,9 @@ impl HTMLCollection {
classes: DOMString, classes: DOMString,
can_gc: CanGc, can_gc: CanGc,
) -> DomRoot<HTMLCollection> { ) -> DomRoot<HTMLCollection> {
let class_atoms = split_html_space_chars(&classes).map(Atom::from).collect(); let class_atoms = split_html_space_chars(classes.str())
.map(Atom::from)
.collect();
HTMLCollection::by_atomic_class_name(window, root, class_atoms, can_gc) HTMLCollection::by_atomic_class_name(window, root, class_atoms, can_gc)
} }

View file

@ -932,7 +932,7 @@ impl HTMLElement {
// returns Some if can infer direction by itself or from child nodes // returns Some if can infer direction by itself or from child nodes
// returns None if requires to go up to parent // returns None if requires to go up to parent
pub(crate) fn directionality(&self) -> Option<String> { pub(crate) fn directionality(&self) -> Option<String> {
let element_direction: &str = &self.Dir(); let element_direction = &self.Dir();
if element_direction == "ltr" { if element_direction == "ltr" {
return Some("ltr".to_owned()); return Some("ltr".to_owned());

View file

@ -177,12 +177,12 @@ impl HTMLFontElementLayoutHelpers for LayoutDom<'_, HTMLFontElement> {
} }
/// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size> /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size>
fn parse_size(mut input: &str) -> AttrValue { fn parse_size(input: &DOMString) -> AttrValue {
let original_input = input; let original_input = input;
// Steps 1 & 2 are not relevant // Steps 1 & 2 are not relevant
// Step 3 // Step 3
input = input.trim_matches(HTML_SPACE_CHARACTERS); let input = input.str().trim_matches(HTML_SPACE_CHARACTERS);
enum ParseMode { enum ParseMode {
RelativePlus, RelativePlus,
@ -192,7 +192,7 @@ fn parse_size(mut input: &str) -> AttrValue {
let mut input_chars = input.chars().peekable(); let mut input_chars = input.chars().peekable();
let parse_mode = match input_chars.peek() { let parse_mode = match input_chars.peek() {
// Step 4 // Step 4
None => return AttrValue::String(original_input.into()), None => return AttrValue::String(original_input.str().into()),
// Step 5 // Step 5
Some(&'+') => { Some(&'+') => {
@ -209,7 +209,7 @@ fn parse_size(mut input: &str) -> AttrValue {
// Steps 6, 7, 8 // Steps 6, 7, 8
let mut value = match read_numbers(input_chars) { let mut value = match read_numbers(input_chars) {
(Some(v), _) if v >= 0 => v, (Some(v), _) if v >= 0 => v,
_ => return AttrValue::String(original_input.into()), _ => return AttrValue::String(original_input.str().into()),
}; };
// Step 9 // Step 9
@ -220,5 +220,5 @@ fn parse_size(mut input: &str) -> AttrValue {
} }
// Steps 10, 11, 12 // Steps 10, 11, 12
AttrValue::UInt(original_input.into(), value as u32) AttrValue::UInt(original_input.str().into(), value as u32)
} }

View file

@ -685,8 +685,8 @@ impl HTMLFormElement {
.get_string_attribute(&local_name!("accept-charset")); .get_string_attribute(&local_name!("accept-charset"));
// Substep 2, 3, 4 // Substep 2, 3, 4
let mut candidate_encodings = let mut candidate_encodings = split_html_space_chars(input.str())
split_html_space_chars(&input).filter_map(|c| Encoding::for_label(c.as_bytes())); .filter_map(|c| Encoding::for_label(c.as_bytes()));
// Substep 5, 6 // Substep 5, 6
return candidate_encodings.next().unwrap_or(UTF_8); return candidate_encodings.next().unwrap_or(UTF_8);
@ -829,7 +829,7 @@ impl HTMLFormElement {
action = DOMString::from(base.as_str()); action = DOMString::from(base.as_str());
} }
// Step 12-13 // Step 12-13
let action_components = match base.join(&action) { let action_components = match base.join(action.str()) {
Ok(url) => url, Ok(url) => url,
Err(_) => return, Err(_) => return,
}; };
@ -940,7 +940,7 @@ impl HTMLFormElement {
&mut load_data.url, &mut load_data.url,
form_data form_data
.iter() .iter()
.map(|field| (&*field.name, field.replace_value(charset))), .map(|field| (field.name.str(), field.replace_value(charset))),
); );
self.plan_to_navigate(load_data, target); self.plan_to_navigate(load_data, target);
@ -969,7 +969,7 @@ impl HTMLFormElement {
&mut url, &mut url,
form_data form_data
.iter() .iter()
.map(|field| (&*field.name, field.replace_value(charset))), .map(|field| (field.name.str(), field.replace_value(charset))),
); );
url.query().unwrap_or("").to_string().into_bytes() url.query().unwrap_or("").to_string().into_bytes()
@ -1491,7 +1491,7 @@ impl FormSubmitterElement<'_> {
|f| f.Enctype(), |f| f.Enctype(),
), ),
}; };
match &*attr { match attr.str() {
"multipart/form-data" => FormEncType::MultipartFormData, "multipart/form-data" => FormEncType::MultipartFormData,
"text/plain" => FormEncType::TextPlain, "text/plain" => FormEncType::TextPlain,
// https://html.spec.whatwg.org/multipage/#attr-fs-enctype // https://html.spec.whatwg.org/multipage/#attr-fs-enctype
@ -1514,7 +1514,7 @@ impl FormSubmitterElement<'_> {
|f| f.Method(), |f| f.Method(),
), ),
}; };
match &*attr { match attr.str() {
"dialog" => FormMethod::Dialog, "dialog" => FormMethod::Dialog,
"post" => FormMethod::Post, "post" => FormMethod::Post,
_ => FormMethod::Get, _ => FormMethod::Get,
@ -1896,7 +1896,7 @@ pub(crate) fn encode_multipart_form_data(
let mut result = vec![]; let mut result = vec![];
// Newline replacement routine as described in Step 1 // Newline replacement routine as described in Step 1
fn clean_crlf(s: &str) -> DOMString { fn clean_crlf(s: &DOMString) -> DOMString {
let mut buf = "".to_owned(); let mut buf = "".to_owned();
let mut prev = ' '; let mut prev = ' ';
for ch in s.chars() { for ch in s.chars() {

View file

@ -620,7 +620,7 @@ impl HTMLIFrameElementMethods<crate::DomTypeHolder> for HTMLIFrameElement {
// Step 2: Set an attribute value given this, srcdoc's local name, and compliantString. // Step 2: Set an attribute value given this, srcdoc's local name, and compliantString.
element.set_attribute( element.set_attribute(
&local_name!("srcdoc"), &local_name!("srcdoc"),
AttrValue::String(value.as_ref().to_owned()), AttrValue::String(value.str().to_owned()),
can_gc, can_gc,
); );
Ok(()) Ok(())

View file

@ -1609,7 +1609,7 @@ fn get_correct_referrerpolicy_from_raw_token(token: &DOMString) -> DOMString {
// so it should remain unchanged. // so it should remain unchanged.
DOMString::new() DOMString::new()
} else { } else {
let policy = determine_policy_for_token(token); let policy = determine_policy_for_token(token.str());
if policy == ReferrerPolicy::EmptyString { if policy == ReferrerPolicy::EmptyString {
return DOMString::new(); return DOMString::new();

View file

@ -19,6 +19,7 @@ use embedder_traits::{
use encoding_rs::Encoding; use encoding_rs::Encoding;
use euclid::{Point2D, Rect, Size2D}; use euclid::{Point2D, Rect, Size2D};
use html5ever::{LocalName, Prefix, QualName, local_name, ns}; use html5ever::{LocalName, Prefix, QualName, local_name, ns};
use itertools::Itertools;
use js::jsapi::{ use js::jsapi::{
ClippedTime, DateGetMsecSinceEpoch, Handle, JS_ClearPendingException, JSObject, NewDateObject, ClippedTime, DateGetMsecSinceEpoch, Handle, JS_ClearPendingException, JSObject, NewDateObject,
NewUCRegExpObject, ObjectIsDate, RegExpFlag_UnicodeSets, RegExpFlags, NewUCRegExpObject, ObjectIsDate, RegExpFlag_UnicodeSets, RegExpFlags,
@ -34,7 +35,7 @@ use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
use servo_config::pref; use servo_config::pref;
use style::attr::AttrValue; use style::attr::AttrValue;
use style::selector_parser::PseudoElement; use style::selector_parser::PseudoElement;
use style::str::{split_commas, str_join}; use style::str::split_commas;
use stylo_atoms::Atom; use stylo_atoms::Atom;
use stylo_dom::ElementState; use stylo_dom::ElementState;
use time::{Month, OffsetDateTime, Time}; use time::{Month, OffsetDateTime, Time};
@ -1000,12 +1001,12 @@ impl HTMLInputElement {
match self.input_type() { match self.input_type() {
// https://html.spec.whatwg.org/multipage/#url-state-(type%3Durl)%3Asuffering-from-a-type-mismatch // https://html.spec.whatwg.org/multipage/#url-state-(type%3Durl)%3Asuffering-from-a-type-mismatch
InputType::Url => Url::parse(value).is_err(), InputType::Url => Url::parse(value.str()).is_err(),
// https://html.spec.whatwg.org/multipage/#e-mail-state-(type%3Demail)%3Asuffering-from-a-type-mismatch // https://html.spec.whatwg.org/multipage/#e-mail-state-(type%3Demail)%3Asuffering-from-a-type-mismatch
// https://html.spec.whatwg.org/multipage/#e-mail-state-(type%3Demail)%3Asuffering-from-a-type-mismatch-2 // https://html.spec.whatwg.org/multipage/#e-mail-state-(type%3Demail)%3Asuffering-from-a-type-mismatch-2
InputType::Email => { InputType::Email => {
if self.Multiple() { if self.Multiple() {
!split_commas(value).all(|string| string.is_valid_email_address_string()) !split_commas(value.str()).all(|string| string.is_valid_email_address_string())
} else { } else {
!value.str().is_valid_email_address_string() !value.str().is_valid_email_address_string()
} }
@ -1029,12 +1030,12 @@ impl HTMLInputElement {
let _ac = enter_realm(self); let _ac = enter_realm(self);
rooted!(in(*cx) let mut pattern = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut pattern = ptr::null_mut::<JSObject>());
if compile_pattern(cx, &pattern_str, pattern.handle_mut()) { if compile_pattern(cx, pattern_str.str(), pattern.handle_mut()) {
if self.Multiple() && self.does_multiple_apply() { if self.Multiple() && self.does_multiple_apply() {
!split_commas(value) !split_commas(value.str())
.all(|s| matches_js_regex(cx, pattern.handle(), s).unwrap_or(true)) .all(|s| matches_js_regex(cx, pattern.handle(), s).unwrap_or(true))
} else { } else {
!matches_js_regex(cx, pattern.handle(), value).unwrap_or(true) !matches_js_regex(cx, pattern.handle(), value.str()).unwrap_or(true)
} }
} else { } else {
// Element doesn't suffer from pattern mismatch if pattern is invalid. // Element doesn't suffer from pattern mismatch if pattern is invalid.
@ -1495,8 +1496,8 @@ impl<'dom> LayoutHTMLInputElementHelpers<'dom> for LayoutDom<'dom, HTMLInputElem
let sel = UTF8Bytes::unwrap_range(sorted_selection_offsets_range); let sel = UTF8Bytes::unwrap_range(sorted_selection_offsets_range);
// Translate indices from the raw value to indices in the replacement value. // Translate indices from the raw value to indices in the replacement value.
let char_start = text[..sel.start].chars().count(); let char_start = text.str()[..sel.start].chars().count();
let char_end = char_start + text[sel].chars().count(); let char_end = char_start + text.str()[sel].chars().count();
let bytes_per_char = PASSWORD_REPLACEMENT_CHAR.len_utf8(); let bytes_per_char = PASSWORD_REPLACEMENT_CHAR.len_utf8();
Some(char_start * bytes_per_char..char_end * bytes_per_char) Some(char_start * bytes_per_char..char_end * bytes_per_char)
@ -1666,7 +1667,7 @@ impl HTMLInputElementMethods<crate::DomTypeHolder> for HTMLInputElement {
Some(ref fl) => match fl.Item(0) { Some(ref fl) => match fl.Item(0) {
Some(ref f) => { Some(ref f) => {
path.push_str("C:\\fakepath\\"); path.push_str("C:\\fakepath\\");
path.push_str(f.name()); path.push_str(f.name().str());
path path
}, },
None => path, None => path,
@ -2373,7 +2374,7 @@ impl HTMLInputElement {
let opt_test_paths = opt_test_paths.map(|paths| { let opt_test_paths = opt_test_paths.map(|paths| {
paths paths
.iter() .iter()
.filter_map(|p| PathBuf::from_str(p).ok()) .filter_map(|p| PathBuf::from_str(p.str()).ok())
.collect() .collect()
}); });
@ -2559,15 +2560,14 @@ impl HTMLInputElement {
value.strip_newlines(); value.strip_newlines();
value.strip_leading_and_trailing_ascii_whitespace(); value.strip_leading_and_trailing_ascii_whitespace();
} else { } else {
let sanitized = str_join( let sanitized = split_commas(value.str())
split_commas(value).map(|token| { .map(|token| {
let mut token = DOMString::from_string(token.to_string()); let mut token = DOMString::from(token.to_string());
token.strip_newlines(); token.strip_newlines();
token.strip_leading_and_trailing_ascii_whitespace(); token.strip_leading_and_trailing_ascii_whitespace();
token token
}), })
",", .join(",");
);
value.clear(); value.clear();
value.push_str(sanitized.as_str()); value.push_str(sanitized.as_str());
} }
@ -2822,9 +2822,9 @@ impl HTMLInputElement {
); );
let current_value = self.Value(); let current_value = self.Value();
let current_color = RgbColor { let current_color = RgbColor {
red: u8::from_str_radix(&current_value[1..3], 16).unwrap(), red: u8::from_str_radix(&current_value.str()[1..3], 16).unwrap(),
green: u8::from_str_radix(&current_value[3..5], 16).unwrap(), green: u8::from_str_radix(&current_value.str()[3..5], 16).unwrap(),
blue: u8::from_str_radix(&current_value[5..7], 16).unwrap(), blue: u8::from_str_radix(&current_value.str()[5..7], 16).unwrap(),
}; };
document.send_to_embedder(EmbedderMsg::ShowFormControl( document.send_to_embedder(EmbedderMsg::ShowFormControl(
document.webview_id(), document.webview_id(),
@ -3573,7 +3573,7 @@ impl Activatable for HTMLInputElement {
// https://html.spec.whatwg.org/multipage/#attr-input-accept // https://html.spec.whatwg.org/multipage/#attr-input-accept
fn filter_from_accept(s: &DOMString) -> Vec<FilterPattern> { fn filter_from_accept(s: &DOMString) -> Vec<FilterPattern> {
let mut filter = vec![]; let mut filter = vec![];
for p in split_commas(s) { for p in split_commas(s.str()) {
let p = p.trim(); let p = p.trim();
if let Some('.') = p.chars().next() { if let Some('.') = p.chars().next() {
filter.push(FilterPattern(p[1..].to_string())); filter.push(FilterPattern(p[1..].to_string()));

View file

@ -1045,7 +1045,7 @@ impl HTMLMediaElement {
SrcObject::Blob(blob) => { SrcObject::Blob(blob) => {
let blob_url = URL::CreateObjectURL(&self.global(), blob); let blob_url = URL::CreateObjectURL(&self.global(), blob);
*self.blob_url.borrow_mut() = *self.blob_url.borrow_mut() =
Some(ServoUrl::parse(&blob_url).expect("infallible")); Some(ServoUrl::parse(blob_url.str()).expect("infallible"));
self.fetch_request(None, None); self.fetch_request(None, None);
}, },
SrcObject::MediaStream(stream) => { SrcObject::MediaStream(stream) => {
@ -1723,7 +1723,7 @@ impl HTMLMediaElement {
if let Some(servo_url) = self.resource_url.borrow().as_ref() { if let Some(servo_url) = self.resource_url.borrow().as_ref() {
let fragment = MediaFragmentParser::from(servo_url); let fragment = MediaFragmentParser::from(servo_url);
if let Some(id) = fragment.id() { if let Some(id) = fragment.id() {
if audio_track.id() == DOMString::from(id) { if audio_track.id() == id {
self.AudioTracks() self.AudioTracks()
.set_enabled(self.AudioTracks().len() - 1, true); .set_enabled(self.AudioTracks().len() - 1, true);
} }
@ -1784,7 +1784,7 @@ impl HTMLMediaElement {
if let Some(servo_url) = self.resource_url.borrow().as_ref() { if let Some(servo_url) = self.resource_url.borrow().as_ref() {
let fragment = MediaFragmentParser::from(servo_url); let fragment = MediaFragmentParser::from(servo_url);
if let Some(id) = fragment.id() { if let Some(id) = fragment.id() {
if track.id() == DOMString::from(id) { if track.id() == id {
self.VideoTracks().set_selected(0, true); self.VideoTracks().set_selected(0, true);
} }
} else if fragment.tracks().contains(&track.kind().into()) { } else if fragment.tracks().contains(&track.kind().into()) {
@ -2350,7 +2350,7 @@ impl HTMLMediaElementMethods<crate::DomTypeHolder> for HTMLMediaElement {
// https://html.spec.whatwg.org/multipage/#dom-navigator-canplaytype // https://html.spec.whatwg.org/multipage/#dom-navigator-canplaytype
fn CanPlayType(&self, type_: DOMString) -> CanPlayTypeResult { fn CanPlayType(&self, type_: DOMString) -> CanPlayTypeResult {
match ServoMedia::get().can_play_type(&type_) { match ServoMedia::get().can_play_type(type_.str()) {
SupportsMediaType::No => CanPlayTypeResult::_empty, SupportsMediaType::No => CanPlayTypeResult::_empty,
SupportsMediaType::Maybe => CanPlayTypeResult::Maybe, SupportsMediaType::Maybe => CanPlayTypeResult::Maybe,
SupportsMediaType::Probably => CanPlayTypeResult::Probably, SupportsMediaType::Probably => CanPlayTypeResult::Probably,

View file

@ -215,13 +215,13 @@ impl HTMLOptionElementMethods<crate::DomTypeHolder> for HTMLOptionElement {
if node.is::<Text>() { if node.is::<Text>() {
let characterdata = node.downcast::<CharacterData>().unwrap(); let characterdata = node.downcast::<CharacterData>().unwrap();
content.push_str(&characterdata.Data()); content.push_str(characterdata.Data().str());
} }
iterator.next(); iterator.next();
} }
DOMString::from(str_join(split_html_space_chars(&content), " ")) DOMString::from(str_join(split_html_space_chars(content.str()), " "))
} }
/// <https://html.spec.whatwg.org/multipage/#dom-option-text> /// <https://html.spec.whatwg.org/multipage/#dom-option-text>

View file

@ -707,7 +707,7 @@ impl HTMLScriptElement {
global, global,
element, element,
InlineCheckType::Script, InlineCheckType::Script,
&text, text.str(),
) )
{ {
warn!("Blocking inline script due to CSP"); warn!("Blocking inline script due to CSP");
@ -751,14 +751,13 @@ impl HTMLScriptElement {
let module_credentials_mode = match script_type { let module_credentials_mode = match script_type {
ScriptType::Classic => CredentialsMode::CredentialsSameOrigin, ScriptType::Classic => CredentialsMode::CredentialsSameOrigin,
ScriptType::Module | ScriptType::ImportMap => reflect_cross_origin_attribute(element) ScriptType::Module | ScriptType::ImportMap => reflect_cross_origin_attribute(element)
.map_or( .map_or(CredentialsMode::CredentialsSameOrigin, |attr| {
CredentialsMode::CredentialsSameOrigin, match attr.str() {
|attr| match &*attr {
"use-credentials" => CredentialsMode::Include, "use-credentials" => CredentialsMode::Include,
"anonymous" => CredentialsMode::CredentialsSameOrigin, "anonymous" => CredentialsMode::CredentialsSameOrigin,
_ => CredentialsMode::CredentialsSameOrigin, _ => CredentialsMode::CredentialsSameOrigin,
}, }
), }),
}; };
// Step 24. Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value. // Step 24. Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value.
@ -1385,7 +1384,7 @@ impl HTMLScriptElementMethods<crate::DomTypeHolder> for HTMLScriptElement {
)?; )?;
element.set_attribute( element.set_attribute(
local_name, local_name,
AttrValue::String(value.as_ref().to_owned()), AttrValue::String(value.str().to_owned()),
can_gc, can_gc,
); );
Ok(()) Ok(())

View file

@ -342,7 +342,7 @@ impl HTMLSelectElement {
.unwrap_or_default(); .unwrap_or_default();
// Replace newlines with whitespace, then collapse and trim whitespace // Replace newlines with whitespace, then collapse and trim whitespace
let displayed_text = itertools::join(selected_option_text.split_whitespace(), " "); let displayed_text = itertools::join(selected_option_text.str().split_whitespace(), " ");
shadow_tree shadow_tree
.selected_option .selected_option

View file

@ -121,7 +121,7 @@ impl HTMLStyleElement {
global, global,
self.upcast(), self.upcast(),
InlineCheckType::Style, InlineCheckType::Style,
&node.child_text_content(), node.child_text_content().str(),
) )
{ {
return; return;
@ -132,14 +132,14 @@ impl HTMLStyleElement {
.GetTextContent() .GetTextContent()
.expect("Element.textContent must be a string"); .expect("Element.textContent must be a string");
let shared_lock = node.owner_doc().style_shared_lock().clone(); let shared_lock = node.owner_doc().style_shared_lock().clone();
let mq = Arc::new(shared_lock.wrap(self.create_media_list(&self.Media()))); let mq = Arc::new(shared_lock.wrap(self.create_media_list(self.Media().str())));
let loader = StylesheetLoader::for_element(self.upcast()); let loader = StylesheetLoader::for_element(self.upcast());
let stylesheetcontents_create_callback = || { let stylesheetcontents_create_callback = || {
#[cfg(feature = "tracing")] #[cfg(feature = "tracing")]
let _span = tracing::trace_span!("ParseStylesheet", servo_profiling = true).entered(); let _span = tracing::trace_span!("ParseStylesheet", servo_profiling = true).entered();
StylesheetContents::from_str( StylesheetContents::from_str(
&data, data.str(),
UrlExtraData(window.get_url().get_arc()), UrlExtraData(window.get_url().get_arc()),
Origin::Author, Origin::Author,
&shared_lock, &shared_lock,
@ -156,7 +156,7 @@ impl HTMLStyleElement {
// stylo's `CascadeDataCache` can now be significantly improved. When shared `StylesheetContents` // stylo's `CascadeDataCache` can now be significantly improved. When shared `StylesheetContents`
// is modified, copy-on-write will occur, see `CSSStyleSheet::will_modify`. // is modified, copy-on-write will occur, see `CSSStyleSheet::will_modify`.
let (cache_key, contents) = StylesheetContentsCache::get_or_insert_with( let (cache_key, contents) = StylesheetContentsCache::get_or_insert_with(
&data, data.str(),
&shared_lock, &shared_lock,
UrlExtraData(window.get_url().get_arc()), UrlExtraData(window.get_url().get_arc()),
doc.quirks_mode(), doc.quirks_mode(),

View file

@ -88,7 +88,7 @@ impl<'dom> LayoutDom<'dom, HTMLTextAreaElement> {
} }
fn placeholder(self) -> &'dom str { fn placeholder(self) -> &'dom str {
unsafe { self.unsafe_get().placeholder.borrow_for_layout() } unsafe { self.unsafe_get().placeholder.borrow_for_layout().str() }
} }
} }
@ -530,7 +530,7 @@ impl VirtualMethods for HTMLTextAreaElement {
let mut placeholder = self.placeholder.borrow_mut(); let mut placeholder = self.placeholder.borrow_mut();
placeholder.clear(); placeholder.clear();
if let AttributeMutation::Set(_) = mutation { if let AttributeMutation::Set(_) = mutation {
placeholder.push_str(&attr.value()); placeholder.push_str(attr.value().as_ref());
} }
} }
self.update_placeholder_shown_state(); self.update_placeholder_shown_state();

View file

@ -217,12 +217,7 @@ impl IDBDatabaseMethods<crate::DomTypeHolder> for IDBDatabase {
} }
// Step 6 // Step 6
if self if self.object_store_names.borrow().contains(&name) {
.object_store_names
.borrow()
.iter()
.any(|store_name| store_name.to_string() == name.to_string())
{
return Err(Error::Constraint); return Err(Error::Constraint);
} }
@ -303,19 +298,14 @@ impl IDBDatabaseMethods<crate::DomTypeHolder> for IDBDatabase {
} }
// Step 4 // Step 4
if !self if !self.object_store_names.borrow().contains(&name) {
.object_store_names
.borrow()
.iter()
.any(|store_name| store_name.to_string() == name.to_string())
{
return Err(Error::NotFound(None)); return Err(Error::NotFound(None));
} }
// Step 5 // Step 5
self.object_store_names self.object_store_names
.borrow_mut() .borrow_mut()
.retain(|store_name| store_name.to_string() != name.to_string()); .retain(|store_name| *store_name != name);
// Step 6 // Step 6
// FIXME:(arihant2math) Remove from index set ... // FIXME:(arihant2math) Remove from index set ...

View file

@ -212,6 +212,10 @@ impl DOMString {
&self.0 &self.0
} }
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Appends a given string slice onto the end of this String. /// Appends a given string slice onto the end of this String.
pub fn push_str(&mut self, string: &str) { pub fn push_str(&mut self, string: &str) {
self.0.push_str(string) self.0.push_str(string)
@ -311,10 +315,6 @@ impl DOMString {
self.0.len() self.0.len()
} }
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn chars(&self) -> Chars<'_> { pub fn chars(&self) -> Chars<'_> {
self.0.chars() self.0.chars()
} }
@ -433,7 +433,6 @@ impl Default for DOMString {
impl Deref for DOMString { impl Deref for DOMString {
type Target = str; type Target = str;
#[inline] #[inline]
fn deref(&self) -> &str { fn deref(&self) -> &str {
&self.0 &self.0
@ -456,13 +455,13 @@ impl AsRef<str> for DOMString {
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 {
fmt::Display::fmt(&**self, f) fmt::Display::fmt(self.str(), f)
} }
} }
impl PartialEq<str> for DOMString { impl PartialEq<str> for DOMString {
fn eq(&self, other: &str) -> bool { fn eq(&self, other: &str) -> bool {
&**self == other self.str() == other
} }
} }
@ -474,7 +473,19 @@ impl PartialEq<DOMString> for str {
impl<'a> PartialEq<&'a str> for DOMString { impl<'a> PartialEq<&'a str> for DOMString {
fn eq(&self, other: &&'a str) -> bool { fn eq(&self, other: &&'a str) -> bool {
&**self == *other self.str() == *other
}
}
impl PartialEq<DOMString> for String {
fn eq(&self, other: &DOMString) -> bool {
*other.0 == *self
}
}
impl PartialEq<String> for DOMString {
fn eq(&self, other: &String) -> bool {
self.0 == *other
} }
} }