script/dom/element/attributes/
storage.rs1use std::cell::Ref;
6use std::mem::MaybeUninit;
7use std::ops::Deref;
8
9use html5ever::{LocalName, Namespace, Prefix, ns};
10use itertools::Either;
11use js::context::JSContext;
12use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
13use script_bindings::cell::DomRefCell;
14use script_bindings::root::{Dom, DomRoot};
15use script_bindings::str::DOMString;
16use servo_arc::{Arc, HeaderSlice, UniqueArc};
17use style::attr::{AttrIdentifier, AttrValue};
18use style::properties::PropertyDeclarationBlock;
19use style::shared_lock::Locked;
20use style::values::GenericAtomIdent;
21
22use crate::dom::attr::Attr;
23use crate::dom::bindings::root::{LayoutDom, ToLayout};
24use crate::dom::element::Element;
25use crate::dom::node::node::NodeTraits;
26
27static EMPTY_NAMESPACE: Namespace = ns!();
30
31#[derive(Clone, MallocSizeOf)]
33pub(crate) enum AttrName {
34 Unqualified(LocalName),
36 Qualified(Box<AttrIdentifier>),
38}
39
40impl AttrName {
41 pub(crate) fn new(
44 local_name: LocalName,
45 name: LocalName,
46 namespace: Namespace,
47 prefix: Option<Prefix>,
48 ) -> Self {
49 if prefix.is_none() && name == local_name && namespace == ns!() {
50 AttrName::Unqualified(local_name)
51 } else {
52 AttrName::Qualified(Box::new(AttrIdentifier {
53 local_name: GenericAtomIdent(local_name),
54 name: GenericAtomIdent(name),
55 namespace: GenericAtomIdent(namespace),
56 prefix: prefix.map(GenericAtomIdent),
57 }))
58 }
59 }
60
61 #[inline]
62 pub(crate) fn local_name(&self) -> &LocalName {
63 match self {
64 AttrName::Unqualified(local_name) => local_name,
65 AttrName::Qualified(identifier) => &identifier.local_name.0,
66 }
67 }
68
69 #[inline]
70 pub(crate) fn name(&self) -> &LocalName {
71 match self {
72 AttrName::Unqualified(local_name) => local_name,
73 AttrName::Qualified(identifier) => &identifier.name.0,
74 }
75 }
76
77 #[inline]
78 pub(crate) fn namespace(&self) -> &Namespace {
79 match self {
80 AttrName::Unqualified(_) => &EMPTY_NAMESPACE,
81 AttrName::Qualified(identifier) => &identifier.namespace.0,
82 }
83 }
84
85 #[inline]
86 pub(crate) fn prefix(&self) -> Option<&Prefix> {
87 match self {
88 AttrName::Unqualified(_) => None,
89 AttrName::Qualified(identifier) => Some(&identifier.prefix.as_ref()?.0),
90 }
91 }
92
93 pub(crate) fn into_parts(self) -> (LocalName, LocalName, Namespace, Option<Prefix>) {
95 match self {
96 AttrName::Unqualified(local_name) => (local_name.clone(), local_name, ns!(), None),
97 AttrName::Qualified(identifier) => {
98 let AttrIdentifier {
99 local_name,
100 name,
101 namespace,
102 prefix,
103 } = *identifier;
104 (local_name.0, name.0, namespace.0, prefix.map(|p| p.0))
105 },
106 }
107 }
108
109 pub(crate) fn as_identifier(&self) -> AttrIdentifier {
111 match self {
112 AttrName::Unqualified(local_name) => AttrIdentifier {
113 local_name: GenericAtomIdent(local_name.clone()),
114 name: GenericAtomIdent(local_name.clone()),
115 namespace: GenericAtomIdent(ns!()),
116 prefix: None,
117 },
118 AttrName::Qualified(identifier) => (**identifier).clone(),
119 }
120 }
121}
122
123#[derive(MallocSizeOf)]
125pub(crate) struct ContentAttributeData {
126 pub identifier: AttrName,
127 pub value: AttrValue,
128}
129
130impl ContentAttributeData {
131 #[inline]
132 pub(crate) fn local_name(&self) -> &LocalName {
133 self.identifier.local_name()
134 }
135
136 #[inline]
137 pub(crate) fn name(&self) -> &LocalName {
138 self.identifier.name()
139 }
140
141 #[inline]
142 pub(crate) fn namespace(&self) -> &Namespace {
143 self.identifier.namespace()
144 }
145
146 #[inline]
147 pub(crate) fn prefix(&self) -> Option<&Prefix> {
148 self.identifier.prefix()
149 }
150
151 #[inline]
152 pub(crate) fn value(&self) -> &AttrValue {
153 &self.value
154 }
155}
156
157pub(crate) enum AttrValueRef<'a> {
159 Direct(&'a AttrValue),
161 Borrowed(Ref<'a, AttrValue>),
163}
164
165impl Deref for AttrValueRef<'_> {
166 type Target = AttrValue;
167
168 fn deref(&self) -> &AttrValue {
169 match self {
170 AttrValueRef::Direct(value) => value,
171 AttrValueRef::Borrowed(value) => value,
172 }
173 }
174}
175
176impl AsRef<str> for AttrValueRef<'_> {
177 fn as_ref(&self) -> &str {
178 self.deref()
179 }
180}
181
182#[derive(Clone, Copy)]
186pub(crate) enum AttrRef<'a> {
187 Raw(&'a ContentAttributeData),
189 Dom(&'a Attr),
191}
192
193impl<'a> AttrRef<'a> {
194 #[inline]
195 pub(crate) fn local_name(&self) -> &'a LocalName {
196 match self {
197 AttrRef::Raw(data) => data.local_name(),
198 AttrRef::Dom(attr) => attr.local_name(),
199 }
200 }
201
202 #[inline]
203 pub(crate) fn name(&self) -> &'a LocalName {
204 match self {
205 AttrRef::Raw(data) => data.name(),
206 AttrRef::Dom(attr) => attr.name(),
207 }
208 }
209
210 #[inline]
211 pub(crate) fn namespace(&self) -> &'a Namespace {
212 match self {
213 AttrRef::Raw(data) => data.namespace(),
214 AttrRef::Dom(attr) => attr.namespace(),
215 }
216 }
217
218 #[inline]
219 pub(crate) fn prefix(&self) -> Option<&'a Prefix> {
220 match self {
221 AttrRef::Raw(data) => data.prefix(),
222 AttrRef::Dom(attr) => attr.prefix(),
223 }
224 }
225
226 #[inline]
227 pub(crate) fn value(&self) -> AttrValueRef<'a> {
228 match self {
229 AttrRef::Raw(data) => AttrValueRef::Direct(data.value()),
230 AttrRef::Dom(attr) => AttrValueRef::Borrowed(attr.value()),
231 }
232 }
233
234 #[inline]
237 pub(crate) fn as_attr(&self) -> Option<&'a Attr> {
238 match self {
239 AttrRef::Dom(attr) => Some(attr),
240 AttrRef::Raw(_) => None,
241 }
242 }
243
244 pub(crate) fn to_dom_string(self) -> DOMString {
246 DOMString::from(&**self.value())
247 }
248
249 #[cfg(feature = "devtools")]
251 pub(crate) fn summarize(&self) -> devtools_traits::AttrInfo {
252 devtools_traits::AttrInfo {
253 namespace: (**self.namespace()).to_owned(),
254 name: (**self.name()).to_owned(),
255 value: (**self.value()).to_owned(),
256 }
257 }
258
259 pub(crate) fn as_identifier(&self) -> AttrIdentifier {
261 match self {
262 AttrRef::Raw(data) => data.identifier.as_identifier(),
263 AttrRef::Dom(attr) => attr.identifier().clone(),
264 }
265 }
266}
267
268#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
270#[derive(MallocSizeOf)]
271pub(crate) enum AttributeEntry {
272 Raw(ContentAttributeData),
274 Dom(Dom<Attr>),
276}
277
278impl AttributeEntry {
279 #[inline]
281 pub(crate) fn as_ref(&self) -> AttrRef<'_> {
282 match self {
283 AttributeEntry::Raw(data) => AttrRef::Raw(data),
284 AttributeEntry::Dom(attr) => AttrRef::Dom(attr),
285 }
286 }
287
288 #[expect(unsafe_code)]
290 #[inline]
291 pub(crate) fn value_for_layout(&self) -> &AttrValue {
292 match self {
293 AttributeEntry::Raw(data) => &data.value,
294 AttributeEntry::Dom(attr) => unsafe {
295 let value: LayoutDom<'_, _> = attr.to_layout();
296 value
297 }
298 .value(),
299 }
300 }
301
302 #[expect(unsafe_code)]
304 #[inline]
305 pub(crate) fn local_name_for_layout(&self) -> &LocalName {
306 match self {
307 AttributeEntry::Raw(data) => data.local_name(),
308 AttributeEntry::Dom(attr) => unsafe {
309 let value: LayoutDom<'_, _> = attr.to_layout();
310 value
311 }
312 .local_name(),
313 }
314 }
315
316 #[expect(unsafe_code)]
318 #[inline]
319 pub(crate) fn namespace_for_layout(&self) -> &Namespace {
320 match self {
321 AttributeEntry::Raw(data) => data.namespace(),
322 AttributeEntry::Dom(attr) => unsafe {
323 let value: LayoutDom<'_, _> = attr.to_layout();
324 value
325 }
326 .namespace(),
327 }
328 }
329}
330
331#[derive(Default)]
332struct AttributeStorageHeader {
333 length: usize,
336 presentational_hints: Option<Arc<Locked<PropertyDeclarationBlock>>>,
341}
342
343impl MallocSizeOf for AttributeStorageHeader {
344 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
345 if let Some(ref presentational_hints) = self.presentational_hints {
346 presentational_hints.size_of(ops)
347 } else {
348 0
349 }
350 }
351}
352
353type AttributeStorageInner =
354 Option<UniqueArc<HeaderSlice<AttributeStorageHeader, MaybeUninit<AttributeEntry>>>>;
355
356#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
364#[derive(Default)]
365pub(crate) struct AttributeStorage(DomRefCell<AttributeStorageInner>);
366
367impl MallocSizeOf for AttributeStorage {
368 #[expect(unsafe_code)]
369 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
370 let attributes = self.0.borrow();
371 let Some(attributes) = &*attributes else {
372 return 0;
373 };
374 let capacity = attributes.len();
375 let mut n = std::mem::size_of::<AttributeStorageHeader>() + attributes.header.size_of(ops);
376 n += capacity * std::mem::size_of::<MaybeUninit<AttributeEntry>>();
377 for entry in &attributes.slice()[..attributes.header.length] {
378 unsafe {
379 n += entry.assume_init_ref().size_of(ops);
380 }
381 }
382 n
383 }
384}
385
386pub(crate) struct AttributesBorrow<'a>(Ref<'a, AttributeStorageInner>);
389
390impl<'a> AttributesBorrow<'a> {
391 #[inline]
393 #[expect(unsafe_code)]
394 pub(crate) fn iter(&self) -> impl Iterator<Item = AttrRef<'_>> + '_ {
395 if let Some(attributes) = &*self.0 {
396 let iterator = attributes.slice()[..self.len()]
397 .iter()
398 .map(|entry| unsafe { entry.assume_init_ref() }.as_ref());
399 Either::Left(iterator)
400 } else {
401 Either::Right(std::iter::empty())
402 }
403 }
404
405 #[inline]
406 pub(crate) fn len(&self) -> usize {
407 let Some(attributes) = &*self.0 else {
408 return 0;
409 };
410 attributes.header.length
411 }
412
413 #[inline]
414 pub(crate) fn is_empty(&self) -> bool {
415 self.len() == 0
416 }
417
418 #[inline]
419 pub(crate) fn first(&self) -> Option<AttrRef<'_>> {
420 self.get(0)
421 }
422
423 #[inline]
424 #[expect(unsafe_code)]
425 pub(crate) fn get(&self, index: usize) -> Option<AttrRef<'_>> {
426 if index >= self.len() {
427 return None;
428 }
429 self.0
430 .as_ref()
431 .unwrap()
432 .slice()
433 .get(index)
434 .map(|entry| unsafe { entry.assume_init_ref() }.as_ref())
435 }
436}
437
438pub(crate) struct AttributesRef<'a>(&'a AttributeStorageInner);
441
442impl<'a> AttributesRef<'a> {
443 #[inline]
444 #[expect(unsafe_code)]
445 pub(crate) fn iter(&self) -> std::slice::Iter<'a, AttributeEntry> {
446 let Some(attributes) = self.0 else {
447 return std::slice::Iter::default();
448 };
449 let slice = &attributes.slice()[..self.len()];
450 unsafe { &*(slice as *const [MaybeUninit<AttributeEntry>] as *const [AttributeEntry]) }
452 .iter()
453 }
454
455 #[inline]
456 pub(crate) fn len(&self) -> usize {
457 let Some(attributes) = self.0 else {
458 return 0;
459 };
460 attributes.header.length
461 }
462
463 #[inline]
464 pub(crate) fn presentational_hints(&self) -> Option<&'a Arc<Locked<PropertyDeclarationBlock>>> {
465 self.0.as_ref()?.header.presentational_hints.as_ref()
466 }
467}
468
469#[inline]
470fn assert_valid_index(index: usize, len: usize) {
471 assert!(index < len, "Index {index} isn't smaller than length {len}");
472}
473
474impl AttributeStorage {
475 #[inline]
477 pub(crate) fn borrow(&self) -> AttributesBorrow<'_> {
478 AttributesBorrow(self.0.borrow())
479 }
480
481 #[expect(unsafe_code)]
483 #[inline]
484 pub(crate) unsafe fn borrow_for_layout<'a>(&'a self) -> AttributesRef<'a> {
485 AttributesRef(unsafe { self.0.borrow_for_layout() })
486 }
487
488 #[inline]
491 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
492 pub(crate) fn reserve_exact(&self, additional: usize) {
493 let mut attributes = self.0.borrow_mut();
494 let Some(attributes) = &mut *attributes else {
495 *attributes = Some(UniqueArc::from_header_and_iter_with_size(
496 AttributeStorageHeader::default(),
497 std::iter::repeat_with(MaybeUninit::uninit).take(additional),
498 additional,
499 ));
500 return;
501 };
502 let current_length = attributes.header.length;
503 let current_capacity = attributes.len();
504 let needed_capacity = current_length.saturating_add(additional);
505 if needed_capacity > isize::MAX as usize {
506 panic!("Capacity overflow");
507 }
508
509 if needed_capacity <= current_capacity {
511 return;
512 }
513
514 let mut new_attributes = UniqueArc::from_header_and_iter_with_size(
517 AttributeStorageHeader {
518 presentational_hints: attributes.header.presentational_hints.take(),
519 length: 0,
520 },
521 std::iter::repeat_with(MaybeUninit::uninit).take(needed_capacity),
522 needed_capacity,
523 );
524 new_attributes.slice_mut()[0..current_length]
525 .swap_with_slice(&mut attributes.slice_mut()[0..current_length]);
526 std::mem::swap(
527 &mut new_attributes.header.length,
528 &mut attributes.header.length,
529 );
530 *attributes = new_attributes;
531 }
532
533 pub(crate) fn reserve(&self, additional: usize) {
536 let mut borrow = self.0.borrow_mut();
537 let Some(attributes) = &mut *borrow else {
538 *borrow = Some(UniqueArc::from_header_and_iter_with_size(
539 AttributeStorageHeader::default(),
540 std::iter::repeat_with(MaybeUninit::uninit).take(additional),
541 additional,
542 ));
543 return;
544 };
545 let current_length = attributes.header.length;
546 let current_capacity = attributes.len();
547 std::mem::drop(borrow);
548 let needed_capacity = current_length.saturating_add(additional);
549
550 if needed_capacity <= current_capacity {
552 return;
553 }
554
555 let new_capacity = needed_capacity.max(current_capacity * 2);
559 self.reserve_exact(new_capacity - current_length);
560 }
561
562 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
563 fn push(&self, entry: AttributeEntry) {
564 self.reserve(1);
565 let mut attributes = self.0.borrow_mut();
566 let attributes = attributes.as_mut().unwrap();
567 let current_length = attributes.header.length;
568 attributes.slice_mut()[current_length].write(entry);
569 attributes.header.length = current_length + 1;
570 }
571
572 pub(crate) fn push_raw(&self, data: ContentAttributeData) {
574 self.push(AttributeEntry::Raw(data));
575 }
576
577 pub(crate) fn push_dom(&self, attr: &Attr) {
579 self.push(AttributeEntry::Dom(Dom::from_ref(attr)));
580 }
581
582 #[expect(unsafe_code)]
584 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
585 pub(crate) fn remove(&self, index: usize) -> AttributeEntry {
586 let mut attributes = self.0.borrow_mut();
587 let Some(attributes) = &mut *attributes else {
588 assert_valid_index(index, 0);
589 unreachable!("The above should panic with the right message");
590 };
591 let current_length = attributes.header.length;
592 assert_valid_index(index, current_length);
593 let slice = attributes.slice_mut();
594 let slice_ptr = slice.as_mut_ptr();
595 let removed;
596 unsafe {
597 removed = slice[index].assume_init_read();
598 std::ptr::copy(
599 slice_ptr.add(index + 1),
600 slice_ptr.add(index),
601 current_length - index - 1,
602 );
603 }
604 attributes.header.length -= 1;
605 removed
606 }
607
608 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
610 #[expect(unsafe_code)]
611 pub(crate) fn set(&self, index: usize, entry: AttributeEntry) {
612 let mut attributes = self.0.borrow_mut();
613 let Some(attributes) = &mut *attributes else {
614 assert_valid_index(index, 0);
615 unreachable!("The above should panic with the right message");
616 };
617 assert_valid_index(index, attributes.header.length);
618 let slot = &mut attributes.slice_mut()[index];
619 unsafe {
620 slot.assume_init_drop();
621 }
622 slot.write(entry);
623 }
624
625 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
631 #[expect(unsafe_code)]
632 pub(crate) fn ensure_dom(
633 &self,
634 cx: &mut JSContext,
635 index: usize,
636 element: &Element,
637 ) -> DomRoot<Attr> {
638 let mut attributes = self.0.borrow_mut();
639 let Some(attributes) = &mut *attributes else {
640 assert_valid_index(index, 0);
641 unreachable!("The above should panic with the right message");
642 };
643 assert_valid_index(index, attributes.header.length);
644
645 if let AttributeEntry::Dom(attr) = unsafe { attributes.slice()[index].assume_init_ref() } {
647 return DomRoot::from_ref(&**attr);
648 }
649
650 let data = {
652 let entries = attributes.slice_mut();
653 let entry = unsafe { entries[index].assume_init_mut() };
654 let placeholder = AttributeEntry::Raw(ContentAttributeData {
655 identifier: AttrName::Unqualified(html5ever::local_name!("")),
656 value: AttrValue::String(String::new()),
657 });
658 let old = std::mem::replace(entry, placeholder);
659 match old {
660 AttributeEntry::Raw(data) => data,
661 _ => unreachable!(),
662 }
663 };
664
665 let doc = element.owner_document();
666 let (local_name, name, namespace, prefix) = data.identifier.into_parts();
667 let attr = Attr::new(
668 cx,
669 &doc,
670 local_name,
671 data.value,
672 name,
673 namespace,
674 prefix,
675 Some(element),
676 );
677
678 let slot = &mut attributes.slice_mut()[index];
679 unsafe {
680 slot.assume_init_drop();
681 }
682 slot.write(AttributeEntry::Dom(Dom::from_ref(&*attr)));
683 attr
684 }
685
686 #[expect(unsafe_code)]
687 pub(crate) fn set_presentational_hints(
688 &self,
689 presentational_hints: Option<Arc<Locked<PropertyDeclarationBlock>>>,
690 ) {
691 unsafe { self.0.borrow_mut_for_layout() }
692 .get_or_insert_with(|| {
693 UniqueArc::from_header_and_iter(
694 AttributeStorageHeader::default(),
695 std::iter::empty::<MaybeUninit<AttributeEntry>>(),
696 )
697 })
698 .header
699 .presentational_hints = presentational_hints;
700 }
701}
702
703impl Drop for AttributeStorage {
704 #[expect(unsafe_code)]
705 fn drop(&mut self) {
706 let mut attributes = self.0.borrow_mut();
707 let Some(attributes) = &mut *attributes else {
708 return;
709 };
710 let length = attributes.header.length;
711 for entry in &mut attributes.slice_mut()[..length] {
712 unsafe {
713 entry.assume_init_drop();
714 }
715 }
716 }
717}
718
719#[expect(unsafe_code)]
722unsafe impl crate::dom::bindings::trace::JSTraceable for AttributeStorage {
723 unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
724 let attributes = self.0.borrow();
725 let Some(attributes) = &*attributes else {
726 return;
727 };
728 for entry in attributes.slice()[..attributes.header.length].iter() {
729 if let AttributeEntry::Dom(attr) = unsafe { entry.assume_init_ref() } {
730 unsafe { js::rust::Trace::trace(attr, trc) };
731 }
732 }
733 }
734}