script/dom/bindings/
cell.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
5//! A shareable mutable container for the DOM.
6
7use std::cell::{BorrowError, BorrowMutError};
8#[cfg(not(feature = "refcell_backtrace"))]
9pub(crate) use std::cell::{Ref, RefCell, RefMut};
10
11#[cfg(feature = "refcell_backtrace")]
12pub(crate) use accountable_refcell::{Ref, RefCell, RefMut};
13use malloc_size_of::{MallocConditionalSizeOf, MallocSizeOfOps};
14
15use crate::dom::bindings::root::{assert_in_layout, assert_in_script};
16
17/// A mutable field in the DOM.
18///
19/// This extends the API of `std::cell::RefCell` to allow unsafe access in
20/// certain situations, with dynamic checking in debug builds.
21#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq)]
22pub(crate) struct DomRefCell<T> {
23    value: RefCell<T>,
24}
25
26impl<T: MallocConditionalSizeOf> MallocConditionalSizeOf for DomRefCell<T> {
27    fn conditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
28        self.value.borrow().conditional_size_of(ops)
29    }
30}
31
32// Functionality specific to Servo's `DomRefCell` type
33// ===================================================
34
35impl<T> DomRefCell<T> {
36    /// Return a reference to the contents.  For use in layout only.
37    ///
38    /// # Safety
39    ///
40    /// Unlike RefCell::borrow, this method is unsafe because it does not return a Ref, thus leaving
41    /// the borrow flag untouched. Mutably borrowing the RefCell while the reference returned by
42    /// this method is alive is undefined behaviour.
43    ///
44    /// # Panics
45    ///
46    /// Panics if this is called from anywhere other than the layout thread
47    ///
48    /// Panics if the value is currently mutably borrowed.
49    #[expect(unsafe_code)]
50    pub(crate) unsafe fn borrow_for_layout(&self) -> &T {
51        assert_in_layout();
52        unsafe {
53            self.value
54                .try_borrow_unguarded()
55                .expect("cell is mutably borrowed")
56        }
57    }
58
59    /// Borrow the contents for the purpose of script deallocation.
60    ///
61    /// # Safety
62    ///
63    /// Unlike RefCell::borrow, this method is unsafe because it does not return a Ref, thus leaving
64    /// the borrow flag untouched. Mutably borrowing the RefCell while the reference returned by
65    /// this method is alive is undefined behaviour.
66    ///
67    /// # Panics
68    ///
69    /// Panics if this is called from anywhere other than the script thread.
70    #[expect(unsafe_code)]
71    #[allow(clippy::mut_from_ref)]
72    pub(crate) unsafe fn borrow_for_script_deallocation(&self) -> &mut T {
73        assert_in_script();
74        unsafe { &mut *self.value.as_ptr() }
75    }
76
77    /// Mutably borrow a cell for layout. Ideally this would use
78    /// `RefCell::try_borrow_mut_unguarded` but that doesn't exist yet.
79    ///
80    /// # Safety
81    ///
82    /// Unlike RefCell::borrow, this method is unsafe because it does not return a Ref, thus leaving
83    /// the borrow flag untouched. Mutably borrowing the RefCell while the reference returned by
84    /// this method is alive is undefined behaviour.
85    ///
86    /// # Panics
87    ///
88    /// Panics if this is called from anywhere other than the layout thread.
89    #[expect(unsafe_code)]
90    #[allow(clippy::mut_from_ref)]
91    pub(crate) unsafe fn borrow_mut_for_layout(&self) -> &mut T {
92        assert_in_layout();
93        unsafe { &mut *self.value.as_ptr() }
94    }
95}
96
97// Functionality duplicated with `std::cell::RefCell`
98// ===================================================
99impl<T> DomRefCell<T> {
100    /// Create a new `DomRefCell` containing `value`.
101    pub(crate) fn new(value: T) -> DomRefCell<T> {
102        DomRefCell {
103            value: RefCell::new(value),
104        }
105    }
106
107    /// Immutably borrows the wrapped value.
108    ///
109    /// The borrow lasts until the returned `Ref` exits scope. Multiple
110    /// immutable borrows can be taken out at the same time.
111    ///
112    /// # Panics
113    ///
114    /// Panics if the value is currently mutably borrowed.
115    /// Panics if this is called from anywhere other than the script thread.
116    /// Use borrow_for_layout if the borrowed data might used during layout.
117    #[track_caller]
118    pub(crate) fn borrow(&self) -> Ref<'_, T> {
119        assert_in_script();
120        self.value.borrow()
121    }
122
123    /// Mutably borrows the wrapped value.
124    ///
125    /// The borrow lasts until the returned `RefMut` exits scope. The value
126    /// cannot be borrowed while this borrow is active.
127    ///
128    /// # Panics
129    ///
130    /// Panics if the value is currently borrowed.
131    /// Panics if this is called from anywhere other than the script thread.
132    #[track_caller]
133    pub(crate) fn borrow_mut(&self) -> RefMut<'_, T> {
134        assert_in_script();
135        self.value.borrow_mut()
136    }
137
138    /// Attempts to immutably borrow the wrapped value.
139    ///
140    /// The borrow lasts until the returned `Ref` exits scope. Multiple
141    /// immutable borrows can be taken out at the same time.
142    ///
143    /// Returns `None` if the value is currently mutably borrowed.
144    ///
145    /// # Panics
146    ///
147    /// Panics if this is called off the script thread.
148    pub(crate) fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
149        assert_in_script();
150        self.value.try_borrow()
151    }
152
153    /// Mutably borrows the wrapped value.
154    ///
155    /// The borrow lasts until the returned `RefMut` exits scope. The value
156    /// cannot be borrowed while this borrow is active.
157    ///
158    /// Returns `None` if the value is currently borrowed.
159    ///
160    /// # Panics
161    ///
162    /// Panics if this is called off the script thread.
163    pub(crate) fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
164        assert_in_script();
165        self.value.try_borrow_mut()
166    }
167}
168
169impl<T: Default> DomRefCell<T> {
170    /// Takes the wrapped value, leaving `Default::default()` in its place.
171    ///
172    /// # Panics
173    ///
174    /// Panics if the value is currently borrowed.
175    pub(crate) fn take(&self) -> T {
176        self.value.take()
177    }
178}