Skip to main content

script/dom/element/attributes/
storage.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use 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
27/// The empty namespace, so that [`AttrName::namespace`] can hand out a reference
28/// for unqualified attributes without storing one per attribute.
29static EMPTY_NAMESPACE: Namespace = ns!();
30
31/// The name of a content attribute.
32#[derive(Clone, MallocSizeOf)]
33pub(crate) enum AttrName {
34    /// Common case: `name == local_name`, empty namespace, no prefix.
35    Unqualified(LocalName),
36    /// Namespaced and/or prefixed.
37    Qualified(Box<AttrIdentifier>),
38}
39
40impl AttrName {
41    /// Build a name from the four parts of an [`AttrIdentifier`], picking the
42    /// compact representation when they allow it.
43    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    /// Decompose into the parts `Attr::new` takes.
94    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    /// Materialize a stylo [`AttrIdentifier`].
110    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/// Lightweight attribute storage that avoids allocating a full DOM `Attr` node.
124#[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
157/// A reference to an attribute value, abstracting over direct and RefCell-borrowed access.
158pub(crate) enum AttrValueRef<'a> {
159    /// Direct reference to a value (from [`ContentAttributeData`]).
160    Direct(&'a AttrValue),
161    /// Borrowed from a [`DomRefCell`] (from [`Attr`]).
162    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/// A reference to attribute data, either from a lightweight [`ContentAttributeData`]
183/// or from a full [`Attr`] DOM node. Provides the same accessor interface regardless
184/// of storage form.
185#[derive(Clone, Copy)]
186pub(crate) enum AttrRef<'a> {
187    /// Lightweight data (no DOM node allocated).
188    Raw(&'a ContentAttributeData),
189    /// Full Attr DOM node.
190    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    /// Returns the underlying `&Attr` if this is a `Dom` reference.
235    /// Returns `None` for `Raw` data (no DOM node exists).
236    #[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    /// Returns the attribute value as a `DOMString`, equivalent to `Attr::Value()`.
245    pub(crate) fn to_dom_string(self) -> DOMString {
246        DOMString::from(&**self.value())
247    }
248
249    /// Returns a summary for devtools.
250    #[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    /// Materializes the stylo `AttrIdentifier` for this attribute.
260    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/// A single attribute entry, either lightweight raw data or a full DOM Attr node.
269#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
270#[derive(MallocSizeOf)]
271pub(crate) enum AttributeEntry {
272    /// Lightweight data — no Attr DOM node allocated.
273    Raw(ContentAttributeData),
274    /// Full Attr DOM node.
275    Dom(Dom<Attr>),
276}
277
278impl AttributeEntry {
279    /// Get an `AttrRef` for this entry.
280    #[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    /// Get the value of this attribute for layout.
289    #[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    /// Get the local name of this attribute for layout.
303    #[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    /// Get the namespace of this attribute for layout.
317    #[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    /// The number of stored attributes in the [`AttributeStorage`]. This is different
334    /// than the [`HeaderSlice::len`], which represents the capacity.
335    length: usize,
336    /// Presentational hints, that is, CSS declarations that are automatically implied
337    /// by the attributes of the element.
338    /// <https://drafts.csswg.org/css-cascade-5/#preshint>
339    /// <https://html.spec.whatwg.org/multipage/#presentational-hints>
340    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/// Storage for an element's attributes. Contains an internal `DomRefCell` so that
357/// `ensure_dom` can split its borrow around `Attr::new()` allocation, preventing
358/// GC-during-allocation panics from double-borrowing.
359/// The attributes are stored in a `HeaderSlice` so that we can also store the
360/// presentational hints derived from the attributes in the header.
361/// This is a compromise in order to avoid increasing the size of `Element`,
362/// while having a minimal impact on performance.
363#[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
386/// A borrowed view of attribute storage that provides convenient access
387/// to attributes as `AttrRef` items. To be used in script.
388pub(crate) struct AttributesBorrow<'a>(Ref<'a, AttributeStorageInner>);
389
390impl<'a> AttributesBorrow<'a> {
391    /// Iterate over attributes as `AttrRef`.
392    #[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
438/// A borrowed view of attribute storage that provides convenient access
439/// to attributes as `&AttributeEntry` items. To be used in layout.
440pub(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        // TODO: Once MSRV is raised to 1.93, use `slice.assume_init_ref()`.
451        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    /// Borrow the attributes for read access with convenient `AttrRef` iteration.
476    #[inline]
477    pub(crate) fn borrow(&self) -> AttributesBorrow<'_> {
478        AttributesBorrow(self.0.borrow())
479    }
480
481    /// Borrow the underlying entries for layout access (unsafe).
482    #[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    /// Reserve room for at least `additional` more attributes. Unlike `reserve()`, this
489    /// will not deliberately over-allocate to speculatively avoid frequent allocations.
490    #[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        // Fast path if we already have enough capacity.
510        if needed_capacity <= current_capacity {
511            return;
512        }
513
514        // Replace the UniqueArc with a new one with more capacity, filled with
515        // the data taken from the old one.
516        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    /// Reserve room for at least `additional` more attributes. The collection may reserve
534    /// more space to speculatively avoid frequent reallocations.
535    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        // Fast path if we already have enough capacity.
551        if needed_capacity <= current_capacity {
552            return;
553        }
554
555        // Doubling the capacity provides exponential growth, so that `push()` can have
556        // an amortized cost of O(1). The doubling cannot overflow `usize` because the
557        // capacity doesn't exceed `isize::MAX`.
558        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    /// Push raw attribute data.
573    pub(crate) fn push_raw(&self, data: ContentAttributeData) {
574        self.push(AttributeEntry::Raw(data));
575    }
576
577    /// Push a Dom Attr node.
578    pub(crate) fn push_dom(&self, attr: &Attr) {
579        self.push(AttributeEntry::Dom(Dom::from_ref(attr)));
580    }
581
582    /// Remove an attribute by index, returning the entry.
583    #[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    /// Set an attribute entry by index.
609    #[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    /// Ensure entry at index is a Dom Attr node, materializing if needed.
626    /// Returns a `DomRoot<Attr>`.
627    ///
628    /// This method carefully splits the mutable borrow around the `Attr::new()`
629    /// allocation so that GC tracing can safely borrow the storage.
630    #[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        // Fast path: already materialized.
646        if let AttributeEntry::Dom(attr) = unsafe { attributes.slice()[index].assume_init_ref() } {
647            return DomRoot::from_ref(&**attr);
648        }
649
650        // Extract the raw data, dropping the mutable borrow before allocating.
651        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// Safety: Only Dom entries contain GC-traced Dom<Attr> pointers.
720// Raw entries have no pointers to trace.
721#[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}