1#![allow(clippy::non_canonical_partial_ord_impl)]
6use std::borrow::{Cow, ToOwned};
7use std::cell::{Ref, RefCell, RefMut};
8use std::default::Default;
9use std::ops::{Deref, DerefMut};
10use std::ptr::{self, NonNull};
11use std::str::FromStr;
12use std::sync::LazyLock;
13use std::{fmt, slice, str};
14
15use html5ever::{LocalName, Namespace};
16use js::context::{JSContext, NoGC};
17use js::conversions::{ToJSValConvertible, jsstr_to_string};
18use js::gc::{HandleValue, MutableHandleValue};
19use js::jsapi::{Heap, JS_GetLatin1StringCharsAndLength, JSString};
20use js::jsval::StringValue;
21use js::rust::{Runtime, Trace};
22use malloc_size_of::MallocSizeOfOps;
23use num_traits::{ToPrimitive, Zero};
24use regex::Regex;
25use servo_base::text::{AssumeUnder4GB, Utf8CodeUnits, Utf16CodeUnits};
26use style::Atom;
27use style::str::HTML_SPACE_CHARACTERS;
28use zeroize::Zeroize;
29
30use crate::trace::RootedTraceableBox;
31
32const ASCII_END: u8 = 0x7E;
33const ASCII_CAPITAL_A: u8 = 0x41;
34const ASCII_CAPITAL_Z: u8 = 0x5A;
35const ASCII_LOWERCASE_A: u8 = 0x61;
36const ASCII_LOWERCASE_Z: u8 = 0x7A;
37const ASCII_TAB: u8 = 0x09;
38const ASCII_NEWLINE: u8 = 0x0A;
39const ASCII_FORMFEED: u8 = 0x0C;
40const ASCII_CR: u8 = 0x0D;
41const ASCII_SPACE: u8 = 0x20;
42
43unsafe fn get_latin1_string_bytes(string: &Heap<*mut JSString>) -> &[u8] {
54 debug_assert!(!string.get().is_null());
55 let mut length = 0;
56 unsafe {
57 let chars = JS_GetLatin1StringCharsAndLength(
58 Runtime::get().expect("JS runtime has shut down").as_ptr(),
59 ptr::null(),
60 string.get(),
61 &mut length,
62 );
63 assert!(!chars.is_null());
64 slice::from_raw_parts(chars, length)
65 }
66}
67
68pub enum EncodedBytes<'a> {
70 Latin1((&'a NoGC, Ref<'a, [u8]>)),
72 Utf8((&'a NoGC, Ref<'a, [u8]>)),
74}
75
76impl EncodedBytes<'_> {
77 pub fn bytes(&self) -> &[u8] {
80 match self {
81 Self::Latin1(bytes) => &bytes.1,
82 Self::Utf8(bytes) => &bytes.1,
83 }
84 }
85
86 pub fn is_empty(&self) -> bool {
88 self.bytes().is_empty()
89 }
90}
91
92#[derive(Clone, Debug)]
93enum AtomTypes {
94 LocalName(LocalName),
95 Stylo(stylo_atoms::Atom),
96 Namespace(web_atoms::Namespace),
97 Prefix(web_atoms::Prefix),
98}
99
100impl From<LocalName> for AtomTypes {
101 fn from(value: LocalName) -> Self {
102 AtomTypes::LocalName(value)
103 }
104}
105
106impl From<stylo_atoms::Atom> for AtomTypes {
107 fn from(value: stylo_atoms::Atom) -> Self {
108 AtomTypes::Stylo(value)
109 }
110}
111
112impl From<web_atoms::Namespace> for AtomTypes {
113 fn from(value: web_atoms::Namespace) -> Self {
114 AtomTypes::Namespace(value)
115 }
116}
117
118impl From<web_atoms::Prefix> for AtomTypes {
119 fn from(value: web_atoms::Prefix) -> Self {
120 AtomTypes::Prefix(value)
121 }
122}
123
124impl AsRef<str> for AtomTypes {
125 fn as_ref(&self) -> &str {
126 match self {
127 AtomTypes::LocalName(atom) => atom.as_str(),
128 AtomTypes::Stylo(atom) => atom.as_str(),
129 AtomTypes::Namespace(atom) => atom.as_str(),
130 AtomTypes::Prefix(atom) => atom.as_str(),
131 }
132 }
133}
134
135#[derive(Zeroize)]
136#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
137enum DOMStringType {
138 Rust(String),
140 #[zeroize(skip)]
142 JSString(Box<Heap<*mut JSString>>),
143 #[cfg(test)]
144 Latin1Vec(Vec<u8>),
147 #[zeroize(skip)] RustStatic(&'static str),
149 #[zeroize(skip)]
150 Atom(AtomTypes),
151}
152
153impl Clone for DOMStringType {
154 fn clone(&self) -> Self {
155 match self {
156 Self::Rust(arg0) => Self::Rust(arg0.clone()),
157 Self::JSString(rooted_box) => Self::JSString(Heap::boxed(rooted_box.get())),
158 #[cfg(test)]
159 Self::Latin1Vec(arg0) => Self::Latin1Vec(arg0.clone()),
160 Self::RustStatic(arg0) => Self::RustStatic(arg0),
161 Self::Atom(atom) => Self::Atom(atom.clone()),
162 }
163 }
164}
165
166impl Default for DOMStringType {
167 fn default() -> Self {
168 Self::Rust(Default::default())
169 }
170}
171
172impl DOMStringType {
173 unsafe fn as_raw_bytes(&self) -> &[u8] {
183 match self {
184 DOMStringType::Rust(s) => s.as_bytes(),
185 DOMStringType::JSString(rooted_traceable_box) => unsafe {
186 get_latin1_string_bytes(rooted_traceable_box)
187 },
188 #[cfg(test)]
189 DOMStringType::Latin1Vec(items) => items,
190 DOMStringType::RustStatic(s) => s.as_bytes(),
191 DOMStringType::Atom(s) => s.as_ref().as_bytes(),
192 }
193 }
194
195 fn ensure_rust_string(&mut self) -> &mut String {
196 let new_string = match self {
197 DOMStringType::Rust(string) => return string,
198 DOMStringType::JSString(rooted_traceable_box) => {
199 let cx = unsafe { JSContext::get_from_thread() };
200 let cx = cx.as_ref().expect("JS runtime has shut down");
201 unsafe { jsstr_to_string(cx, NonNull::new(rooted_traceable_box.get()).unwrap()) }
202 },
203 #[cfg(test)]
204 DOMStringType::Latin1Vec(items) => {
205 let mut v = vec![0; items.len() * 2];
206 let real_size =
207 encoding_rs::mem::convert_latin1_to_utf8(items.as_slice(), v.as_mut_slice());
208 v.truncate(real_size);
209
210 unsafe { String::from_utf8_unchecked(v) }
213 },
214 DOMStringType::RustStatic(s) => s.to_owned(),
216 DOMStringType::Atom(s) => s.as_ref().to_owned(),
217 };
218 *self = DOMStringType::Rust(new_string);
219 self.ensure_rust_string()
220 }
221}
222
223#[derive(Debug)]
226pub struct StringView<'a>(Ref<'a, str>);
227
228impl StringView<'_> {
229 pub fn split_html_space_characters(&self) -> impl Iterator<Item = &str> {
230 self.split(HTML_SPACE_CHARACTERS)
231 .filter(|string| !string.is_empty())
232 }
233}
234
235impl From<StringView<'_>> for String {
236 fn from(string_view: StringView<'_>) -> Self {
237 string_view.0.to_string()
238 }
239}
240
241impl Deref for StringView<'_> {
242 type Target = str;
243 fn deref(&self) -> &str {
244 &(self.0)
245 }
246}
247
248impl AsRef<str> for StringView<'_> {
249 fn as_ref(&self) -> &str {
250 &(self.0)
251 }
252}
253
254impl PartialEq for StringView<'_> {
255 fn eq(&self, other: &Self) -> bool {
256 self.0.eq(&*(other.0))
257 }
258}
259
260impl PartialEq<&str> for StringView<'_> {
261 fn eq(&self, other: &&str) -> bool {
262 self.0.eq(*other)
263 }
264}
265
266impl Eq for StringView<'_> {}
267
268impl PartialOrd for StringView<'_> {
269 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
270 self.0.partial_cmp(&**other)
271 }
272}
273
274impl Ord for StringView<'_> {
275 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
276 self.0.cmp(other)
277 }
278}
279
280unsafe impl Trace for DOMStringType {
286 unsafe fn trace(&self, tracer: *mut js::jsapi::JSTracer) {
287 unsafe {
288 match self {
289 DOMStringType::Rust(_s) => {},
290 DOMStringType::JSString(rooted_traceable_box) => rooted_traceable_box.trace(tracer),
291 #[cfg(test)]
292 DOMStringType::Latin1Vec(_s) => {},
293 DOMStringType::RustStatic(_) => {},
294 DOMStringType::Atom(_) => {},
295 }
296 }
297 }
298}
299
300impl malloc_size_of::MallocSizeOf for DOMStringType {
301 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
302 match self {
303 DOMStringType::Rust(s) => s.size_of(ops),
304 DOMStringType::JSString(_rooted_traceable_box) => {
305 0
307 },
308 #[cfg(test)]
309 DOMStringType::Latin1Vec(s) => s.size_of(ops),
310 DOMStringType::RustStatic(_s) => 0,
311 DOMStringType::Atom(_) => 0,
312 }
313 }
314}
315
316impl std::fmt::Debug for DOMStringType {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 match self {
319 DOMStringType::Rust(s) => f.debug_struct("DOMString").field("rust_string", s).finish(),
320 DOMStringType::JSString(_rooted_traceable_box) => f.debug_struct("DOMString").finish(),
321 #[cfg(test)]
322 DOMStringType::Latin1Vec(s) => f
323 .debug_struct("DOMString")
324 .field("latin1_string", s)
325 .finish(),
326 DOMStringType::RustStatic(s) => f
327 .debug_struct("DOMString")
328 .field("static_string", s)
329 .finish(),
330 DOMStringType::Atom(s) => f.debug_struct("DOMString").field("atom", s).finish(),
331 }
332 }
333}
334
335#[repr(transparent)]
373#[derive(Clone, Debug, Default, MallocSizeOf, JSTraceable)]
374#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
375pub struct TracedDOMString(RefCell<DOMStringType>);
376
377#[derive(Default, MallocSizeOf, JSTraceable)]
379pub struct DOMString(RootedTraceableBox<TracedDOMString>);
380
381impl std::fmt::Debug for DOMString {
382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 f.debug_tuple("DOMString").field(&*self.0).finish()
384 }
385}
386
387impl DerefMut for DOMString {
388 fn deref_mut(&mut self) -> &mut Self::Target {
389 &mut self.0
390 }
391}
392
393impl Deref for DOMString {
394 type Target = TracedDOMString;
395
396 fn deref(&self) -> &Self::Target {
397 &self.0
398 }
399}
400
401impl Clone for DOMString {
402 fn clone(&self) -> Self {
403 self.0.clone().root()
404 }
405}
406
407impl DOMString {
408 pub fn new() -> DOMString {
410 TracedDOMString::default().root()
411 }
412
413 pub fn from_js_string(
418 cx: &mut JSContext,
419 value: HandleValue,
420 ) -> Result<DOMString, DOMStringErrorType> {
421 rooted!(&in(cx) let string_ptr = unsafe { js::rust::ToString(cx, value) });
432 unsafe { DOMString::from_raw_js_string(cx, *string_ptr) }
433 }
434
435 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
442 pub unsafe fn from_raw_js_string(
443 cx: &JSContext,
444 string_ptr: *mut JSString,
445 ) -> Result<DOMString, DOMStringErrorType> {
446 if string_ptr.is_null() {
447 debug!("ToString failed");
448 Err(DOMStringErrorType::JSConversionError)
449 } else {
450 let latin1 = unsafe { js::jsapi::JS_DeprecatedStringHasLatin1Chars(string_ptr) };
451 let inner = if latin1 {
452 let h = Heap::boxed(string_ptr);
453 DOMStringType::JSString(h)
454 } else {
455 DOMStringType::Rust(unsafe {
457 jsstr_to_string(cx, NonNull::new(string_ptr).unwrap())
458 })
459 };
460 Ok(TracedDOMString(RefCell::new(inner)).root())
461 }
462 }
463
464 pub fn from_static(s: &'static str) -> DOMString {
466 TracedDOMString(RefCell::new(DOMStringType::RustStatic(s))).root()
467 }
468
469 pub fn traced(self) -> TracedDOMString {
470 *self.0.into_box()
471 }
472
473 pub fn str(&self) -> StringView<'_> {
474 self.0.str()
475 }
476}
477
478#[derive(Debug)]
479pub enum DOMStringErrorType {
480 JSConversionError,
481}
482
483impl From<String> for TracedDOMString {
484 fn from(string: String) -> Self {
485 TracedDOMString(RefCell::new(DOMStringType::Rust(string)))
486 }
487}
488
489impl TracedDOMString {
490 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
491 pub fn root(self) -> DOMString {
492 DOMString(RootedTraceableBox::from_box(Box::new(self)))
493 }
494
495 fn ensure_rust_string(&self) -> RefMut<'_, String> {
498 let inner = self.0.borrow_mut();
499 RefMut::map(inner, |inner| inner.ensure_rust_string())
500 }
501
502 #[expect(unused)]
504 fn debug_js(&self, cx: &JSContext) {
505 match *self.0.borrow() {
506 DOMStringType::Rust(ref s) => info!("Rust String ({})", s),
507 DOMStringType::JSString(ref rooted_traceable_box) => {
508 let s = unsafe {
509 jsstr_to_string(cx, NonNull::new(rooted_traceable_box.get()).unwrap())
510 };
511 info!("JSString ({})", s);
512 },
513 #[cfg(test)]
514 DOMStringType::Latin1Vec(ref items) => info!("Latin1 string"),
515 DOMStringType::RustStatic(s) => info!("Static Rust String ({})", s),
516 DOMStringType::Atom(ref s) => info!("Atom String ({:?})", s),
517 }
518 }
519
520 pub fn str(&self) -> StringView<'_> {
522 {
523 let inner = self.0.borrow();
524 if matches!(&*inner, DOMStringType::Rust(..)) {
525 return StringView(Ref::map(inner, |inner| match inner {
526 DOMStringType::Rust(string) => string.as_str(),
527 _ => unreachable!("Guaranteed by condition above"),
528 }));
529 }
530 }
531
532 self.ensure_rust_string();
533 self.str()
534 }
535
536 pub fn encoded_bytes<'a>(&'a self, no_gc: &'a NoGC) -> EncodedBytes<'a> {
539 let inner = self.0.borrow();
540 match &*inner {
542 DOMStringType::Rust(..) | DOMStringType::RustStatic(..) => EncodedBytes::Utf8((
543 no_gc,
544 Ref::map(inner, |inner| unsafe { inner.as_raw_bytes() }),
545 )),
546 DOMStringType::JSString(..) => EncodedBytes::Latin1((
547 no_gc,
548 Ref::map(inner, |inner| unsafe { inner.as_raw_bytes() }),
549 )),
550 #[cfg(test)]
551 DOMStringType::Latin1Vec(..) => EncodedBytes::Latin1((
552 no_gc,
553 Ref::map(inner, |inner| unsafe { inner.as_raw_bytes() }),
554 )),
555 DOMStringType::Atom(_) => EncodedBytes::Utf8((
556 no_gc,
557 Ref::map(inner, |inner| unsafe { inner.as_raw_bytes() }),
558 )),
559 }
560 }
561
562 pub fn clear(&mut self) {
563 let mut inner = self.0.borrow_mut();
564 let DOMStringType::Rust(string) = &mut *inner else {
565 *inner = DOMStringType::Rust(String::new());
566 return;
567 };
568 string.clear();
569 }
570
571 pub fn is_empty(&self) -> bool {
572 let no_gc = unsafe { NoGC::new() };
574 self.encoded_bytes(&no_gc).is_empty()
575 }
576
577 pub fn len_utf8(&self) -> Utf8CodeUnits {
584 let no_gc = unsafe { NoGC::new() };
587 Utf8CodeUnits(match self.encoded_bytes(&no_gc) {
588 EncodedBytes::Utf8(bytes) => bytes.1.len() as u32,
589 EncodedBytes::Latin1(bytes) => bytes
590 .1
591 .iter()
592 .map(|&byte| if byte < 128 { 1 } else { 2 })
595 .sum::<u32>(),
596 })
597 }
598
599 pub fn len_utf8_or_latin1(&self) -> usize {
601 let no_gc = unsafe { NoGC::new() };
603 match self.encoded_bytes(&no_gc) {
604 EncodedBytes::Utf8(bytes) => bytes.1.len(),
605 EncodedBytes::Latin1(bytes) => bytes.1.len(),
606 }
607 }
608
609 pub fn len_utf16(&self) -> Utf16CodeUnits {
614 let no_gc = unsafe { NoGC::new() };
616 match self.encoded_bytes(&no_gc) {
617 EncodedBytes::Latin1(bytes) => Utf16CodeUnits(bytes.1.len() as u32),
619 EncodedBytes::Utf8(bytes) => Utf16CodeUnits::length_of(AssumeUnder4GB, unsafe {
622 str::from_utf8_unchecked(&bytes.1)
623 }),
624 }
625 }
626
627 pub fn make_ascii_lowercase(&mut self) {
630 self.0
631 .borrow_mut()
632 .ensure_rust_string()
633 .make_ascii_lowercase();
634 }
635
636 pub fn push_str(&mut self, string_to_push: &str) {
637 self.0
638 .borrow_mut()
639 .ensure_rust_string()
640 .push_str(string_to_push);
641 }
642
643 pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) {
645 if self.is_empty() {
646 return;
647 }
648
649 let mut inner = self.0.borrow_mut();
650 let string = inner.ensure_rust_string();
651 let trailing_whitespace_len = string
652 .trim_end_matches(|character: char| character.is_ascii_whitespace())
653 .len();
654 string.truncate(trailing_whitespace_len);
655 if string.is_empty() {
656 return;
657 }
658
659 let first_non_whitespace = string
660 .find(|character: char| !character.is_ascii_whitespace())
661 .unwrap();
662 string.replace_range(0..first_non_whitespace, "");
663 }
664
665 pub fn is_valid_floating_point_number_string(&self) -> bool {
667 is_valid_floating_point_number_string(self.0.borrow_mut().ensure_rust_string()) &&
668 self.parse_floating_point_number().is_some()
669 }
670
671 pub fn parse<T: FromStr>(&self) -> Result<T, <T as FromStr>::Err> {
672 self.str().parse::<T>()
673 }
674
675 pub fn parse_floating_point_number(&self) -> Option<f64> {
677 parse_floating_point_number(&self.str())
678 }
679
680 pub fn set_best_representation_of_the_floating_point_number(&mut self) {
682 if let Some(val) = self.parse_floating_point_number() {
683 let parsed_value = if val.is_zero() { 0.0_f64 } else { val };
685
686 *self.0.borrow_mut() = DOMStringType::Rust(parsed_value.to_string());
687 }
688 }
689
690 pub fn to_lowercase(&self) -> String {
691 self.str().to_lowercase()
692 }
693
694 pub fn to_uppercase(&self) -> String {
695 self.str().to_uppercase()
696 }
697
698 pub fn strip_newlines(&mut self) {
699 self.0
702 .borrow_mut()
703 .ensure_rust_string()
704 .retain(|character| character != '\r' && character != '\n');
705 }
706
707 pub fn normalize_newlines(&mut self) {
709 let mut inner = self.0.borrow_mut();
713 let string = inner.ensure_rust_string();
714 *string = string.replace("\r\n", "\n").replace("\r", "\n")
715 }
716
717 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
718 pub fn replace(self, needle: &str, replace_char: &str) -> DOMString {
719 let new_string = self.str().to_owned();
720 TracedDOMString(RefCell::new(DOMStringType::Rust(
721 new_string.replace(needle, replace_char),
722 )))
723 .root()
724 }
725
726 pub fn starts_with(&self, c: char) -> bool {
728 if !c.is_ascii() {
729 self.str().starts_with(c)
730 } else {
731 let no_gc = unsafe { NoGC::new() };
735 self.encoded_bytes(&no_gc).bytes().starts_with(&[c as u8])
736 }
737 }
738
739 pub fn starts_with_str(&self, needle: &str) -> bool {
740 self.str().starts_with(needle)
741 }
742
743 pub fn ends_with_str(&self, needle: &str) -> bool {
744 self.str().ends_with(needle)
745 }
746
747 pub fn contains(&self, needle: &str) -> bool {
748 self.str().contains(needle)
749 }
750
751 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
756 if other.is_ascii() {
757 let no_gc = unsafe { NoGC::new() };
759 self.encoded_bytes(&no_gc)
760 .bytes()
761 .eq_ignore_ascii_case(other.as_bytes())
762 } else {
763 self.str().eq_ignore_ascii_case(other)
764 }
765 }
766
767 pub fn to_ascii_lowercase(&self) -> String {
768 let no_gc = unsafe { NoGC::new() };
770 let conversion = match self.encoded_bytes(&no_gc) {
771 EncodedBytes::Latin1(bytes) => {
772 if bytes.1.iter().all(|c| *c <= ASCII_END) {
773 Some(unsafe {
775 String::from_utf8_unchecked(
776 bytes
777 .1
778 .iter()
779 .map(|c| {
780 if *c >= ASCII_CAPITAL_A && *c <= ASCII_CAPITAL_Z {
781 c + 32
782 } else {
783 *c
784 }
785 })
786 .collect(),
787 )
788 })
789 } else {
790 None
791 }
792 },
793 EncodedBytes::Utf8(bytes) => unsafe {
794 Some(str::from_utf8_unchecked(&bytes.1).to_ascii_lowercase())
796 },
797 };
798 if let Some(conversion) = conversion {
800 conversion
801 } else {
802 self.str().to_ascii_lowercase()
803 }
804 }
805
806 fn contains_space_characters(
807 &self,
808 latin1_characters: &'static [u8],
809 utf8_characters: &'static [char],
810 ) -> bool {
811 let no_gc = unsafe { NoGC::new() };
813 match self.encoded_bytes(&no_gc) {
814 EncodedBytes::Latin1(items) => {
815 latin1_characters.iter().any(|byte| items.1.contains(byte))
816 },
817 EncodedBytes::Utf8(bytes) => {
818 let s = unsafe { str::from_utf8_unchecked(&bytes.1) };
820 s.contains(utf8_characters)
821 },
822 }
823 }
824
825 pub fn contains_tab_or_newline(&self) -> bool {
827 const LATIN_TAB_OR_NEWLINE: [u8; 3] = [ASCII_TAB, ASCII_NEWLINE, ASCII_CR];
828 const UTF8_TAB_OR_NEWLINE: [char; 3] = ['\u{0009}', '\u{000a}', '\u{000d}'];
829
830 self.contains_space_characters(&LATIN_TAB_OR_NEWLINE, &UTF8_TAB_OR_NEWLINE)
831 }
832
833 pub fn contains_html_space_characters(&self) -> bool {
835 const SPACE_BYTES: [u8; 5] = [
836 ASCII_TAB,
837 ASCII_NEWLINE,
838 ASCII_FORMFEED,
839 ASCII_CR,
840 ASCII_SPACE,
841 ];
842 self.contains_space_characters(&SPACE_BYTES, HTML_SPACE_CHARACTERS)
843 }
844
845 pub fn as_bytes<'a>(&'a self, no_gc: &'a NoGC) -> BytesView<'a> {
847 if self.is_ascii() {
851 BytesView {
852 _no_gc: no_gc,
853 inner: self.0.borrow(),
854 }
855 } else {
856 self.ensure_rust_string();
857 BytesView {
858 _no_gc: no_gc,
859 inner: self.0.borrow(),
860 }
861 }
862 }
863
864 pub fn is_ascii_lowercase(&self) -> bool {
866 let no_gc = unsafe { NoGC::new() };
868 match self.encoded_bytes(&no_gc) {
869 EncodedBytes::Latin1(items) => items
870 .1
871 .iter()
872 .all(|c| (ASCII_LOWERCASE_A..=ASCII_LOWERCASE_Z).contains(c)),
873 EncodedBytes::Utf8(bytes) => bytes
874 .1
875 .iter()
876 .map(|c| c.to_u8().unwrap_or(ASCII_LOWERCASE_A - 1))
877 .all(|c| (ASCII_LOWERCASE_A..=ASCII_LOWERCASE_Z).contains(&c)),
878 }
879 }
880
881 pub fn is_ascii(&self) -> bool {
883 let no_gc = unsafe { NoGC::new() };
885 self.encoded_bytes(&no_gc).bytes().is_ascii()
886 }
887
888 pub fn is_valid_for_cookie(&self) -> bool {
892 let no_gc = unsafe { NoGC::new() };
894 match self.encoded_bytes(&no_gc) {
895 EncodedBytes::Latin1(items) | EncodedBytes::Utf8(items) => !items
896 .1
897 .iter()
898 .any(|c| *c == 0x7f || (*c <= 0x1f && *c != 0x09)),
899 }
900 }
901
902 fn with_str_reference<Result>(&self, callback: fn(&str) -> Result) -> Result {
905 let no_gc = unsafe { NoGC::new() };
908 match self.encoded_bytes(&no_gc) {
909 EncodedBytes::Latin1(latin1_bytes) => {
911 if latin1_bytes.1.iter().all(|character| character.is_ascii()) {
912 return callback(unsafe { str::from_utf8_unchecked(&latin1_bytes.1) });
915 }
916 },
917 EncodedBytes::Utf8(utf8_bytes) => {
918 return callback(unsafe { str::from_utf8_unchecked(&utf8_bytes.1) });
921 },
922 };
923 callback(self.str().deref())
924 }
925
926 pub fn normalize_crlf(&self) -> String {
934 let s = self.str();
935 let mut buf = String::new();
936 let mut prev = ' ';
937 for ch in s.chars() {
938 match ch {
939 '\n' if prev != '\r' => {
940 buf.push('\r');
941 buf.push('\n');
942 },
943 '\n' => {
944 buf.push('\n');
945 },
946 _ if prev == '\r' => {
949 buf.push('\n');
950 buf.push(ch);
951 },
952 _ => buf.push(ch),
953 };
954 prev = ch;
955 }
956 if prev == '\r' {
958 buf.push('\n');
959 }
960 buf
961 }
962}
963
964pub fn parse_floating_point_number(input: &str) -> Option<f64> {
966 input.trim().parse::<f64>().ok().filter(|value| {
972 !(value.is_infinite() || value.is_nan() || input.ends_with('.') || input.starts_with('+'))
975 })
976}
977
978pub struct BytesView<'a> {
979 _no_gc: &'a NoGC,
980 inner: Ref<'a, DOMStringType>,
981}
982
983impl Deref for BytesView<'_> {
984 type Target = [u8];
985
986 fn deref(&self) -> &Self::Target {
987 unsafe { self.inner.as_raw_bytes() }
989 }
990}
991
992impl Ord for TracedDOMString {
993 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
994 self.str().cmp(&other.str())
995 }
996}
997
998impl PartialOrd for TracedDOMString {
999 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1000 self.str().partial_cmp(&other.str())
1001 }
1002}
1003
1004impl PartialOrd for DOMString {
1005 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1006 self.0.partial_cmp(&other.0)
1007 }
1008}
1009
1010impl Extend<char> for TracedDOMString {
1011 fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
1012 self.0.borrow_mut().ensure_rust_string().extend(iter)
1013 }
1014}
1015
1016impl ToJSValConvertible for TracedDOMString {
1017 fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
1018 let val = self.0.borrow();
1019 match *val {
1020 DOMStringType::Rust(ref s) => s.to_jsval(cx, rval),
1021 DOMStringType::JSString(ref rooted_traceable_box) => unsafe {
1022 rval.set(StringValue(&*rooted_traceable_box.get()));
1023 },
1024 #[cfg(test)]
1025 DOMStringType::Latin1Vec(ref items) => {
1026 let mut v = vec![0; items.len() * 2];
1027 let real_size =
1028 encoding_rs::mem::convert_latin1_to_utf8(items.as_slice(), v.as_mut_slice());
1029 v.truncate(real_size);
1030
1031 String::from_utf8(v)
1032 .expect("Error in constructin test string")
1033 .to_jsval(cx, rval);
1034 },
1035 DOMStringType::RustStatic(s) => s.to_jsval(cx, rval),
1036 DOMStringType::Atom(ref atom) => atom.as_ref().to_jsval(cx, rval),
1037 };
1038 }
1039}
1040
1041impl ToJSValConvertible for DOMString {
1042 fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue) {
1043 self.0.to_jsval(cx, rval);
1044 }
1045}
1046
1047impl std::hash::Hash for TracedDOMString {
1048 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1049 self.str().hash(state);
1050 }
1051}
1052
1053impl std::hash::Hash for DOMString {
1054 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1055 self.str().hash(state);
1056 }
1057}
1058
1059impl std::fmt::Display for TracedDOMString {
1060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1061 fmt::Display::fmt(self.str().deref(), f)
1062 }
1063}
1064
1065impl std::fmt::Display for DOMString {
1066 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1067 fmt::Display::fmt(self.str().deref(), f)
1068 }
1069}
1070
1071impl std::cmp::PartialEq<str> for TracedDOMString {
1072 fn eq(&self, other: &str) -> bool {
1073 if other.is_ascii() {
1074 let no_gc = unsafe { NoGC::new() };
1076 *other.as_bytes() == *self.encoded_bytes(&no_gc).bytes()
1077 } else {
1078 self.str().deref() == other
1079 }
1080 }
1081}
1082
1083impl std::cmp::PartialEq<str> for DOMString {
1084 fn eq(&self, other: &str) -> bool {
1085 self.0.eq(other)
1086 }
1087}
1088
1089impl std::cmp::PartialEq<&str> for TracedDOMString {
1090 fn eq(&self, other: &&str) -> bool {
1091 self.eq(*other)
1092 }
1093}
1094
1095impl std::cmp::PartialEq<&str> for DOMString {
1096 fn eq(&self, other: &&str) -> bool {
1097 self.0.eq(*other)
1098 }
1099}
1100
1101impl std::cmp::PartialEq<String> for TracedDOMString {
1102 fn eq(&self, other: &String) -> bool {
1103 self.eq(other.as_str())
1104 }
1105}
1106
1107impl std::cmp::PartialEq<String> for DOMString {
1108 fn eq(&self, other: &String) -> bool {
1109 self.0.eq(other.as_str())
1110 }
1111}
1112
1113impl std::cmp::PartialEq<TracedDOMString> for String {
1114 fn eq(&self, other: &TracedDOMString) -> bool {
1115 other.eq(self)
1116 }
1117}
1118
1119impl std::cmp::PartialEq<DOMString> for String {
1120 fn eq(&self, other: &DOMString) -> bool {
1121 other.0.eq(self)
1122 }
1123}
1124
1125impl std::cmp::PartialEq<TracedDOMString> for str {
1126 fn eq(&self, other: &TracedDOMString) -> bool {
1127 other.eq(self)
1128 }
1129}
1130
1131impl std::cmp::PartialEq<DOMString> for str {
1132 fn eq(&self, other: &DOMString) -> bool {
1133 other.0.eq(self)
1134 }
1135}
1136
1137impl std::cmp::PartialEq for TracedDOMString {
1138 fn eq(&self, other: &TracedDOMString) -> bool {
1139 let no_gc = unsafe { NoGC::new() };
1140 let result = match (self.encoded_bytes(&no_gc), other.encoded_bytes(&no_gc)) {
1141 (EncodedBytes::Latin1(bytes), EncodedBytes::Latin1(other_bytes)) => {
1142 Some(*bytes.1 == *other_bytes.1)
1143 },
1144 (EncodedBytes::Latin1(bytes), EncodedBytes::Utf8(other_bytes))
1145 if other_bytes.1.is_ascii() =>
1146 {
1147 Some(*bytes.1 == *other_bytes.1)
1148 },
1149 (EncodedBytes::Utf8(bytes), EncodedBytes::Latin1(other_bytes))
1150 if bytes.1.is_ascii() =>
1151 {
1152 Some(*bytes.1 == *other_bytes.1)
1153 },
1154 (EncodedBytes::Utf8(bytes), EncodedBytes::Utf8(other_bytes)) => {
1155 Some(*bytes.1 == *other_bytes.1)
1156 },
1157 _ => None,
1158 };
1159
1160 if let Some(eq_result) = result {
1161 return eq_result;
1162 }
1163
1164 *self.str() == *other.str()
1165 }
1166}
1167
1168impl std::cmp::PartialEq for DOMString {
1169 fn eq(&self, other: &Self) -> bool {
1170 *self.0 == *other.0
1171 }
1172}
1173
1174impl std::cmp::Eq for TracedDOMString {}
1175
1176impl std::cmp::Eq for DOMString {}
1177
1178impl From<std::string::String> for DOMString {
1179 fn from(string: String) -> Self {
1180 TracedDOMString(RefCell::new(DOMStringType::Rust(string))).root()
1181 }
1182}
1183
1184impl From<&str> for DOMString {
1186 fn from(string: &str) -> Self {
1187 String::from(string).into()
1188 }
1189}
1190
1191impl From<DOMString> for LocalName {
1192 fn from(dom_string: DOMString) -> LocalName {
1193 dom_string.with_str_reference(|string| LocalName::from(string))
1194 }
1195}
1196
1197impl From<&DOMString> for LocalName {
1198 fn from(dom_string: &DOMString) -> LocalName {
1199 dom_string.with_str_reference(|string| LocalName::from(string))
1200 }
1201}
1202
1203impl From<DOMString> for Namespace {
1204 fn from(dom_string: DOMString) -> Namespace {
1205 dom_string.with_str_reference(|string| Namespace::from(string))
1206 }
1207}
1208
1209impl From<DOMString> for Atom {
1210 fn from(dom_string: DOMString) -> Atom {
1211 dom_string.with_str_reference(|string| Atom::from(string))
1212 }
1213}
1214
1215impl From<LocalName> for TracedDOMString {
1216 fn from(value: LocalName) -> Self {
1217 TracedDOMString(RefCell::new(DOMStringType::Atom(value.into())))
1218 }
1219}
1220
1221impl From<stylo_atoms::Atom> for TracedDOMString {
1222 fn from(value: stylo_atoms::Atom) -> Self {
1223 TracedDOMString(RefCell::new(DOMStringType::Atom(value.into())))
1224 }
1225}
1226
1227impl From<web_atoms::Namespace> for TracedDOMString {
1228 fn from(value: web_atoms::Namespace) -> Self {
1229 TracedDOMString(RefCell::new(DOMStringType::Atom(value.into())))
1230 }
1231}
1232
1233impl From<web_atoms::Prefix> for TracedDOMString {
1234 fn from(value: web_atoms::Prefix) -> Self {
1235 TracedDOMString(RefCell::new(DOMStringType::Atom(value.into())))
1236 }
1237}
1238
1239#[cfg_attr(crown, expect(crown::unrooted_must_root))]
1240impl From<TracedDOMString> for String {
1241 fn from(val: TracedDOMString) -> Self {
1242 val.ensure_rust_string();
1243 let inner = val.0.take();
1244 match inner {
1245 DOMStringType::Rust(s) => s,
1246 DOMStringType::JSString(_) => unreachable!(),
1247 #[cfg(test)]
1248 DOMStringType::Latin1Vec(items) => String::from_utf8(items).expect("Not valid latin1"),
1249 DOMStringType::RustStatic(s) => s.to_owned(),
1250 DOMStringType::Atom(s) => s.as_ref().to_owned(),
1251 }
1252 }
1253}
1254
1255impl From<DOMString> for String {
1256 fn from(value: DOMString) -> Self {
1257 String::from(value.traced())
1258 }
1259}
1260
1261#[cfg_attr(crown, expect(crown::unrooted_must_root))]
1262impl From<TracedDOMString> for Vec<u8> {
1263 fn from(value: TracedDOMString) -> Self {
1264 value.ensure_rust_string();
1265 let inner = value.0.take();
1266 match inner {
1267 DOMStringType::Rust(s) => s.into_bytes(),
1268 DOMStringType::JSString(_) => unreachable!(),
1269 #[cfg(test)]
1270 DOMStringType::Latin1Vec(items) => items,
1271 DOMStringType::RustStatic(_) => unreachable!(),
1272 DOMStringType::Atom(_) => unreachable!(),
1273 }
1274 }
1275}
1276
1277impl From<DOMString> for Vec<u8> {
1278 fn from(value: DOMString) -> Self {
1279 Vec::<u8>::from(value.traced())
1280 }
1281}
1282
1283impl From<Cow<'_, str>> for DOMString {
1284 fn from(value: Cow<'_, str>) -> Self {
1285 TracedDOMString(RefCell::new(DOMStringType::Rust(value.into_owned()))).root()
1286 }
1287}
1288
1289impl Zeroize for TracedDOMString {
1290 fn zeroize(&mut self) {
1291 self.0.get_mut().zeroize();
1292 }
1293}
1294
1295impl Zeroize for DOMString {
1296 fn zeroize(&mut self) {
1297 self.0.zeroize()
1298 }
1299}
1300
1301#[macro_export]
1302macro_rules! match_domstring_ascii_inner {
1303 ($variant: expr, $input: expr, $ascii_literal: literal => $then: expr, $($rest:tt)*) => {
1304 if {
1305 debug_assert!(($ascii_literal).is_ascii());
1306 $ascii_literal.as_bytes()
1307 } == $input.bytes() {
1308 $then
1309 } else {
1310 $crate::match_domstring_ascii_inner!($variant, $input, $($rest)*)
1311 }
1312
1313 };
1314 ($variant: expr, $input: expr, $p: pat => $then: expr,) => {
1315 match $input {
1316 $p => $then
1317 }
1318 }
1319}
1320
1321pub fn is_valid_floating_point_number_string(s: &str) -> bool {
1324 static RE: LazyLock<Regex> =
1325 LazyLock::new(|| Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap());
1326
1327 RE.is_match(s)
1328}
1329
1330#[macro_export]
1347macro_rules! match_domstring_ascii {
1348 ($input:expr, $($tail:tt)*) => {
1349 {
1350 use $crate::domstring::EncodedBytes;
1351 use js::context::NoGC;
1352
1353 let no_gc = unsafe { NoGC::new() };
1355 let encoded_bytes = $input.encoded_bytes(&no_gc);
1356 match encoded_bytes {
1357 EncodedBytes::Latin1(_) => {
1358 $crate::match_domstring_ascii_inner!(EncodedBytes::Latin1, encoded_bytes, $($tail)*)
1359 }
1360 EncodedBytes::Utf8(_) => {
1361 $crate::match_domstring_ascii_inner!(EncodedBytes::Utf8, encoded_bytes, $($tail)*)
1362 }
1363
1364 }
1365 }
1366 };
1367}
1368
1369#[cfg(test)]
1370mod tests {
1371 use super::*;
1372
1373 const LATIN1_PILLCROW: u8 = 0xB6;
1374 const UTF8_PILLCROW: [u8; 2] = [194, 182];
1375 const LATIN1_POWER2: u8 = 0xB2;
1376
1377 fn from_latin1(l1vec: Vec<u8>) -> DOMString {
1378 TracedDOMString(RefCell::new(DOMStringType::Latin1Vec(l1vec))).root()
1379 }
1380
1381 #[test]
1382 fn string_functions() {
1383 let s = DOMString::from("AbBcC❤&%$#");
1384 let s_copy = s.clone();
1385 assert_eq!(s.to_ascii_lowercase(), "abbcc❤&%$#");
1386 assert_eq!(s, s_copy);
1387 assert_eq!(s.len_utf8().0, 12);
1388 assert_eq!(s_copy.len_utf8().0, 12);
1389 assert!(s.starts_with('A'));
1390 let s2 = DOMString::from("");
1391 assert!(s2.is_empty());
1392 }
1393
1394 #[test]
1395 fn string_functions_latin1() {
1396 {
1397 let s = from_latin1(vec![
1398 b'A', b'b', b'B', b'c', b'C', b'&', b'%', b'$', b'#', 0xB2,
1399 ]);
1400 assert_eq!(s.to_ascii_lowercase(), "abbcc&%$#²");
1401 }
1402 {
1403 let s = from_latin1(vec![b'A', b'b', b'B', b'c', b'C']);
1404 assert_eq!(s.to_ascii_lowercase(), "abbcc");
1405 }
1406 {
1407 let s = from_latin1(vec![
1408 b'A', b'b', b'B', b'c', b'C', b'&', b'%', b'$', b'#', 0xB2,
1409 ]);
1410 assert_eq!(s.len_utf8().0, 11);
1411 assert!(s.starts_with('A'));
1412 }
1413 {
1414 let s = from_latin1(vec![]);
1415 assert!(s.is_empty());
1416 }
1417 }
1418
1419 #[test]
1420 fn test_length() {
1421 let s1 = from_latin1(vec![
1422 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD,
1423 0xAE, 0xAF,
1424 ]);
1425 let s2 = from_latin1(vec![
1426 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD,
1427 0xBE, 0xBF,
1428 ]);
1429 let s3 = from_latin1(vec![
1430 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD,
1431 0xCE, 0xCF,
1432 ]);
1433 let s4 = from_latin1(vec![
1434 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD,
1435 0xDE, 0xDF,
1436 ]);
1437 let s5 = from_latin1(vec![
1438 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED,
1439 0xEE, 0xEF,
1440 ]);
1441 let s6 = from_latin1(vec![
1442 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD,
1443 0xFE, 0xFF,
1444 ]);
1445
1446 let s1_utf8 = String::from("\u{00A0}¡¢£¤¥¦§¨©ª«¬\u{00AD}®¯");
1447 let s2_utf8 = String::from("°±²³´µ¶·¸¹º»¼½¾¿");
1448 let s3_utf8 = String::from("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
1449 let s4_utf8 = String::from("ÐÑÒÓÔÕÖרÙÚÛÜÝÞß");
1450 let s5_utf8 = String::from("àáâãäåæçèéêëìíîï");
1451 let s6_utf8 = String::from("ðñòóôõö÷øùúûüýþÿ");
1452
1453 assert_eq!(usize::from(s1.len_utf8()), s1_utf8.len());
1454 assert_eq!(usize::from(s2.len_utf8()), s2_utf8.len());
1455 assert_eq!(usize::from(s3.len_utf8()), s3_utf8.len());
1456 assert_eq!(usize::from(s4.len_utf8()), s4_utf8.len());
1457 assert_eq!(usize::from(s5.len_utf8()), s5_utf8.len());
1458 assert_eq!(usize::from(s6.len_utf8()), s6_utf8.len());
1459
1460 s1.ensure_rust_string();
1461 s2.ensure_rust_string();
1462 s3.ensure_rust_string();
1463 s4.ensure_rust_string();
1464 s5.ensure_rust_string();
1465 s6.ensure_rust_string();
1466 assert_eq!(usize::from(s1.len_utf8()), s1_utf8.len());
1467 assert_eq!(usize::from(s2.len_utf8()), s2_utf8.len());
1468 assert_eq!(usize::from(s3.len_utf8()), s3_utf8.len());
1469 assert_eq!(usize::from(s4.len_utf8()), s4_utf8.len());
1470 assert_eq!(usize::from(s5.len_utf8()), s5_utf8.len());
1471 assert_eq!(usize::from(s6.len_utf8()), s6_utf8.len());
1472 }
1473
1474 #[test]
1475 fn test_convert() {
1476 let s = from_latin1(vec![b'a', b'b', b'c', b'%', b'$']);
1477 s.ensure_rust_string();
1478 assert_eq!(&*s.str(), "abc%$");
1479 }
1480
1481 #[test]
1482 fn partial_eq() {
1483 let s = from_latin1(vec![b'a', b'b', b'c', b'%', b'$']);
1484 let string = String::from("abc%$");
1485 let s2 = DOMString::from(string.clone());
1486 let s3 = DOMString::from_static("abc%$");
1487 assert_eq!(s, s2);
1488 assert_eq!(s, string);
1489 assert_eq!(s, s3);
1490 }
1491
1492 #[test]
1493 fn encoded_latin1_bytes() {
1494 let original_latin1_bytes = vec![b'a', b'b', b'c', b'%', b'$', 0xB2];
1495 let dom_string = from_latin1(original_latin1_bytes.clone());
1496 let no_gc = unsafe { NoGC::new() };
1497 let string_latin1_bytes = match dom_string.encoded_bytes(&no_gc) {
1498 EncodedBytes::Latin1(bytes) => bytes,
1499 _ => unreachable!("Expected Latin1 encoded bytes"),
1500 };
1501 assert_eq!(*original_latin1_bytes, *string_latin1_bytes.1);
1502 }
1503
1504 #[test]
1505 fn testing_stringview() {
1506 let s = from_latin1(vec![b'a', b'b', b'c', b'%', b'$', 0xB2]);
1507
1508 assert_eq!(
1509 s.str().chars().collect::<Vec<char>>(),
1510 vec!['a', 'b', 'c', '%', '$', '²']
1511 );
1512 assert_eq!(s.str().as_bytes(), String::from("abc%$²").as_bytes());
1513 }
1514
1515 #[test]
1520 fn test_hash() {
1521 use std::hash::{DefaultHasher, Hash, Hasher};
1522 fn hash_value(d: &DOMString) -> u64 {
1523 let mut hasher = DefaultHasher::new();
1524 d.hash(&mut hasher);
1525 hasher.finish()
1526 }
1527
1528 let s = from_latin1(vec![b'a', b'b', b'c', b'%', b'$', 0xB2]);
1529 let s_converted = from_latin1(vec![b'a', b'b', b'c', b'%', b'$', 0xB2]);
1530 s_converted.ensure_rust_string();
1531 let s2 = DOMString::from("abc%$²");
1532 let s3 = DOMString::from_static("abc%$²");
1533
1534 let hash_s = hash_value(&s);
1535 let hash_s_converted = hash_value(&s_converted);
1536 let hash_s2 = hash_value(&s2);
1537 let hash_s3 = hash_value(&s3);
1538
1539 assert_eq!(hash_s, hash_s2);
1540 assert_eq!(hash_s, hash_s_converted);
1541 assert_eq!(hash_s, hash_s3);
1542 }
1543
1544 #[test]
1546 fn test_match_executing() {
1547 {
1549 let s = from_latin1(vec![b'a', b'b', b'c']);
1550 match_domstring_ascii!( s,
1551 "abc" => assert!(true),
1552 "bcd" => assert!(false),
1553 _ => (),
1554 );
1555 }
1556
1557 {
1558 let s = from_latin1(vec![b'a', b'b', b'c', b'/']);
1559 match_domstring_ascii!( s,
1560 "abc/" => assert!(true),
1561 "bcd" => assert!(false),
1562 _ => (),
1563 );
1564 }
1565
1566 {
1567 let s = from_latin1(vec![b'a', b'b', b'c', b'%', b'$']);
1568 match_domstring_ascii!( s,
1569 "bcd" => assert!(false),
1570 "abc%$" => assert!(true),
1571 _ => (),
1572 );
1573 }
1574
1575 {
1576 let s = DOMString::from("abcde");
1577 match_domstring_ascii!( s,
1578 "abc" => assert!(false),
1579 "bcd" => assert!(false),
1580 _ => assert!(true),
1581 );
1582 }
1583 {
1584 let s = DOMString::from("abc%$");
1585 match_domstring_ascii!( s,
1586 "bcd" => assert!(false),
1587 "abc%$" => assert!(true),
1588 _ => (),
1589 );
1590 }
1591 {
1592 let s = from_latin1(vec![b'a', b'b', b'c']);
1593 match_domstring_ascii!( s,
1594 "abcdd" => assert!(false),
1595 "bcd" => assert!(false),
1596 _ => (),
1597 );
1598 }
1599 {
1600 let s = DOMString::from_static("abc");
1601 match_domstring_ascii!( s,
1602 "abc" => assert!(true),
1603 "bcd" => assert!(false),
1604 _ => (),
1605 );
1606 }
1607 }
1608
1609 #[test]
1611 fn test_match_returning_result() {
1612 {
1613 let s = from_latin1(vec![b'a', b'b', b'c']);
1614 let res = match_domstring_ascii!( s,
1615 "abc" => true,
1616 "bcd" => false,
1617 _ => false,
1618 );
1619 assert_eq!(res, true);
1620 }
1621 {
1622 let s = from_latin1(vec![b'a', b'b', b'c', b'/']);
1623 let res = match_domstring_ascii!( s,
1624 "abc/" => true,
1625 "bcd" => false,
1626 _ => false,
1627 );
1628 assert_eq!(res, true);
1629 }
1630 {
1631 let s = from_latin1(vec![b'a', b'b', b'c', b'%', b'$']);
1632 let res = match_domstring_ascii!( s,
1633 "bcd" => false,
1634 "abc%$" => true,
1635 _ => false,
1636 );
1637 assert_eq!(res, true);
1638 }
1639
1640 {
1641 let s = DOMString::from("abcde");
1642 let res = match_domstring_ascii!( s,
1643 "abc" => false,
1644 "bcd" => false,
1645 _ => true,
1646 );
1647 assert_eq!(res, true);
1648 }
1649 {
1650 let s = DOMString::from("abc%$");
1651 let res = match_domstring_ascii!( s,
1652 "bcd" => false,
1653 "abc%$" => true,
1654 _ => false,
1655 );
1656 assert_eq!(res, true);
1657 }
1658 {
1659 let s = from_latin1(vec![b'a', b'b', b'c']);
1660 let res = match_domstring_ascii!( s,
1661 "abcdd" => false,
1662 "bcd" => false,
1663 _ => true,
1664 );
1665 assert_eq!(res, true);
1666 }
1667 }
1668
1669 #[test]
1670 #[cfg(debug_assertions)]
1671 #[should_panic]
1672 fn test_match_panic() {
1673 let s = DOMString::from("abcd");
1674 let _res = match_domstring_ascii!(s,
1675 "❤" => true,
1676 _ => false,);
1677 }
1678
1679 #[test]
1680 #[cfg(debug_assertions)]
1681 #[should_panic]
1682 fn test_match_panic2() {
1683 let s = DOMString::from("abcd");
1684 let _res = match_domstring_ascii!(s,
1685 "abc" => false,
1686 "❤" => true,
1687 _ => false,
1688 );
1689 }
1690
1691 #[test]
1692 fn test_strip_whitespace() {
1693 {
1694 let mut s = from_latin1(vec![
1695 b' ', b' ', b' ', b'\n', b' ', b'a', b'b', b'c', b'%', b'$', 0xB2, b' ',
1696 ]);
1697
1698 s.strip_leading_and_trailing_ascii_whitespace();
1699 s.ensure_rust_string();
1700 assert_eq!(&*s.str(), "abc%$²");
1701 }
1702 {
1703 let mut s = DOMString::from(" \n abc%$ ");
1704
1705 s.strip_leading_and_trailing_ascii_whitespace();
1706 s.ensure_rust_string();
1707 assert_eq!(&*s.str(), "abc%$");
1708 }
1709 {
1710 let mut s = DOMString::from_static(" \n abc%$ ");
1711
1712 s.strip_leading_and_trailing_ascii_whitespace();
1713 s.ensure_rust_string();
1714 assert_eq!(&*s.str(), "abc%$");
1715 }
1716 }
1717
1718 #[test]
1720 fn contains_html_space_characters() {
1721 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_TAB, b'a', b'a']); assert!(s.contains_html_space_characters());
1723 s.ensure_rust_string();
1724 assert!(s.contains_html_space_characters());
1725
1726 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_NEWLINE, b'a', b'a']); assert!(s.contains_html_space_characters());
1728 s.ensure_rust_string();
1729 assert!(s.contains_html_space_characters());
1730
1731 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_FORMFEED, b'a', b'a']); assert!(s.contains_html_space_characters());
1733 s.ensure_rust_string();
1734 assert!(s.contains_html_space_characters());
1735
1736 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_CR, b'a', b'a']); assert!(s.contains_html_space_characters());
1738 s.ensure_rust_string();
1739 assert!(s.contains_html_space_characters());
1740
1741 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_SPACE, b'a', b'a']); assert!(s.contains_html_space_characters());
1743 s.ensure_rust_string();
1744 assert!(s.contains_html_space_characters());
1745
1746 let s = from_latin1(vec![b'a', b'a', b'a', b'a', b'a']);
1747 assert!(!s.contains_html_space_characters());
1748 s.ensure_rust_string();
1749 assert!(!s.contains_html_space_characters());
1750
1751 let s = DOMString::from_static("aba aaa");
1752 assert!(s.contains_html_space_characters());
1753 s.ensure_rust_string();
1754 assert!(s.contains_html_space_characters());
1755 }
1756
1757 #[test]
1758 fn atom() {
1759 let s = from_latin1(vec![b'a', b'a', b'a', 0x20, b'a', b'a']);
1760 let atom1 = Atom::from(s);
1761 let s2 = DOMString::from("aaa aa");
1762 let atom2 = Atom::from(s2);
1763 assert_eq!(atom1, atom2);
1764 let s3 = from_latin1(vec![b'a', b'a', b'a', 0xB2, b'a', b'a']);
1765 let atom3 = Atom::from(s3);
1766 assert_ne!(atom1, atom3);
1767 let s3 = DOMString::from_static("aaa\u{03B1}aa");
1768 let atom3 = Atom::from(s3);
1769 assert_ne!(atom1, atom3);
1770 let s4 = DOMString::from_static("aaa aa");
1771 let atom4 = Atom::from(s4);
1772 assert_eq!(atom2, atom4);
1773 }
1774
1775 #[test]
1776 fn namespace() {
1777 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_SPACE, b'a', b'a']);
1778 let atom1 = Namespace::from(s);
1779 let s2 = DOMString::from("aaa aa");
1780 let atom2 = Namespace::from(s2);
1781 assert_eq!(atom1, atom2);
1782 let s3 = from_latin1(vec![b'a', b'a', b'a', LATIN1_POWER2, b'a', b'a']);
1783 let atom3 = Namespace::from(s3);
1784 assert_ne!(atom1, atom3);
1785 let s4 = DOMString::from_static("aaa aa");
1786 let atom4 = Namespace::from(s4);
1787 assert_eq!(atom2, atom4);
1788 }
1789
1790 #[test]
1791 fn localname() {
1792 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_SPACE, b'a', b'a']);
1793 let atom1 = LocalName::from(s);
1794 let s2 = DOMString::from("aaa aa");
1795 let atom2 = LocalName::from(s2);
1796 assert_eq!(atom1, atom2);
1797 let s3 = from_latin1(vec![b'a', b'a', b'a', LATIN1_POWER2, b'a', b'a']);
1798 let atom3 = LocalName::from(s3);
1799 assert_ne!(atom1, atom3);
1800 let s4 = DOMString::from_static("aaa aa");
1801 let atom4 = LocalName::from(s4);
1802 assert_eq!(atom2, atom4);
1803 }
1804
1805 #[test]
1806 fn is_ascii_lowercase() {
1807 let s = from_latin1(vec![b'a', b'a', b'a', ASCII_SPACE, b'a', b'a']);
1808 assert!(!s.is_ascii_lowercase());
1809 let s = from_latin1(vec![b'a', b'a', b'a', LATIN1_PILLCROW, b'a', b'a']);
1810 assert!(!s.is_ascii_lowercase());
1811 let s = from_latin1(vec![b'a', b'a', b'a', b'a', b'z']);
1812 assert!(s.is_ascii_lowercase());
1813 let s = from_latin1(vec![b'`', b'a', b'a', b'a', b'z']);
1814 assert!(!s.is_ascii_lowercase());
1815 let s = DOMString::from("`aaaz");
1816 assert!(!s.is_ascii_lowercase());
1817 let s = DOMString::from("aaaz");
1818 assert!(s.is_ascii_lowercase());
1819 let s = DOMString::from_static("aaaz");
1820 assert!(s.is_ascii_lowercase());
1821 }
1822
1823 #[test]
1824 fn test_as_bytes() {
1825 const ASCII_SMALL_A: u8 = b'a';
1826 const ASCII_SMALL_Z: u8 = b'z';
1827
1828 let v1 = vec![b'a', b'a', b'a', LATIN1_PILLCROW, b'a', b'a'];
1829 let s = from_latin1(v1.clone());
1830 {
1831 let no_gc = unsafe { NoGC::new() };
1832 assert_eq!(
1833 *s.as_bytes(&no_gc),
1834 [
1835 ASCII_SMALL_A,
1836 ASCII_SMALL_A,
1837 ASCII_SMALL_A,
1838 UTF8_PILLCROW[0],
1839 UTF8_PILLCROW[1],
1840 ASCII_SMALL_A,
1841 ASCII_SMALL_A
1842 ]
1843 );
1844 }
1845 let v2 = vec![b'a', b'a', b'a', b'a', b'z'];
1846 let s = from_latin1(v2.clone());
1847 {
1848 let no_gc = unsafe { NoGC::new() };
1849 assert_eq!(
1850 *s.as_bytes(&no_gc),
1851 [
1852 ASCII_SMALL_A,
1853 ASCII_SMALL_A,
1854 ASCII_SMALL_A,
1855 ASCII_SMALL_A,
1856 ASCII_SMALL_Z
1857 ]
1858 );
1859 }
1860
1861 let str = "abc%$²".to_owned();
1862 let s = DOMString::from(str.clone());
1863 {
1864 let no_gc = unsafe { NoGC::new() };
1865 assert_eq!(&*s.as_bytes(&no_gc), str.as_bytes());
1866 }
1867 let str = "AbBcC❤&%$#".to_owned();
1868 let s = DOMString::from(str.clone());
1869 {
1870 let no_gc = unsafe { NoGC::new() };
1871 assert_eq!(&*s.as_bytes(&no_gc), str.as_bytes());
1872 }
1873 let s = DOMString::from_static("AbBcC❤&%$#");
1874
1875 {
1876 let no_gc = unsafe { NoGC::new() };
1877 assert_eq!(&*s.as_bytes(&no_gc), str.as_bytes());
1878 }
1879 }
1880
1881 #[test]
1882 fn test_atom_restore() {
1883 let local_name = LocalName::from("test_name");
1884 let local_name_domstring = TracedDOMString::from(local_name.clone());
1885 assert_eq!(local_name_domstring.str(), local_name.as_str());
1886
1887 let stylo = stylo_atoms::Atom::from("test-atom-stylo");
1888 let stylo_domstring = TracedDOMString::from(stylo.clone());
1889 assert_eq!(stylo_domstring.str(), stylo.as_str());
1890
1891 let namespace = web_atoms::Namespace::from("test-atom-namespace");
1892 let namespace_domstring = TracedDOMString::from(namespace.clone());
1893 assert_eq!(namespace_domstring.str(), namespace.as_str());
1894
1895 let prefix = web_atoms::Prefix::from("prefix");
1896 let prefix_domstring = TracedDOMString::from(prefix.clone());
1897 assert_eq!(prefix_domstring.str(), prefix.as_str());
1898 }
1899}