script_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};
8pub use std::cell::{Ref, RefCell, RefMut};
9
10use js::context::NoGC;
11use js::jsapi::JSTracer;
12use malloc_size_of::{MallocConditionalSizeOf, MallocSizeOfOps};
13
14use crate::CustomTraceable;
15use crate::assert::{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 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 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 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 unsafe fn borrow_mut_for_layout(&self) -> &mut T {
92 assert_in_layout();
93 unsafe { &mut *self.value.as_ptr() }
94 }
95
96 /// Mutably borrows the wrapped value.
97 ///
98 /// The borrow lasts until the returned `RefMut` exits scope. The value
99 /// cannot be borrowed while this borrow is active.
100 ///
101 /// By passing a `&NoGC` we statically prevent GC from being run while the borrow is active,
102 /// to prevent panic when tracing (which calls `borrow`).
103 ///
104 /// # Example
105 ///
106 /// In simple cases one can use `NoGC` to statically ensure no GC can happen in the whole DOM method:
107 ///
108 /// ```
109 /// use js::context::{JSContext, NoGC};
110 /// use script_bindings::cell::DomRefCell;
111 /// fn DomMethod(no_gc: &NoGC, cell: &DomRefCell<usize>) {
112 /// let mut mutably_borrowed = cell.safe_borrow_mut(no_gc);
113 /// }
114 /// ```
115 ///
116 /// But in more complex cases, method might trigger a GC, and thus require a `&mut JSContext`.
117 /// In that case `&JSContext` can be used in place of `NoGC`,
118 /// which will make `RefMut` bounded to the lifetime of the `&JSContext`
119 /// and thus prevent any GC from happening while it is alive.
120 ///
121 /// ```
122 /// use js::context::{JSContext, NoGC};
123 /// use script_bindings::cell::DomRefCell;
124 /// fn GC(cx: &mut JSContext) {}
125 ///
126 /// fn DomMethod(cell: &DomRefCell<usize>, cx: &mut JSContext) {
127 /// {
128 /// let mut mutably_borrowed = cell.safe_borrow_mut(cx);
129 /// // do something with mutably_borrowed
130 ///
131 /// // only &JSContext is available here
132 /// } // mutably_borrowed goes out of scope here
133 /// // so one can now use &mut JSContext
134 /// GC(cx);
135 /// }
136 /// ```
137 ///
138 /// ```compile_fail
139 /// use js::context::{JSContext, NoGC};
140 /// use script_bindings::cell::DomRefCell;
141 /// fn GC(cx: &mut JSContext) {}
142 ///
143 /// fn DomMethod(cell: &DomRefCell<usize>, cx: &mut JSContext) {
144 /// {
145 /// let mut mutably_borrowed = cell.safe_borrow_mut(cx);
146 /// // do something with mutably_borrowed
147 ///
148 /// // here one cannot use anything that might trigger a GC
149 /// // as that would require &mut JSContext
150 /// // but there is already existing &JSContext bounded at RefMut
151 /// GC(cx);
152 /// } // mutably_borrowed goes out of scope here
153 /// }
154 /// ```
155 ///
156 /// # Panics
157 ///
158 /// Panics if the value is currently borrowed.
159 #[track_caller]
160 pub fn safe_borrow_mut<'a: 'r, 'no_cx: 'r, 'r>(
161 &'a self,
162 _no_gc: &'no_cx NoGC,
163 ) -> RefMut<'r, T> {
164 self.value.borrow_mut()
165 }
166
167 /// Mutably borrows the wrapped value.
168 ///
169 /// The borrow lasts until the returned `RefMut` exits scope. The value
170 /// cannot be borrowed while this borrow is active.
171 ///
172 /// By passing a `&NoGC` we statically prevent GC from being run while the borrow is active,
173 /// to prevent panic when tracing (which calls `borrow`).
174 ///
175 /// Returns `None` if the value is currently borrowed.
176 pub fn safe_try_borrow_mut<'a: 'r, 'no_cx: 'r, 'r>(
177 &'a self,
178 _no_gc: &'no_cx NoGC,
179 ) -> Result<RefMut<'r, T>, BorrowMutError> {
180 self.value.try_borrow_mut()
181 }
182}
183
184// Functionality duplicated with `std::cell::RefCell`
185// ===================================================
186impl<T> DomRefCell<T> {
187 /// Create a new `DomRefCell` containing `value`.
188 pub fn new(value: T) -> DomRefCell<T> {
189 DomRefCell {
190 value: RefCell::new(value),
191 }
192 }
193
194 /// Immutably borrows the wrapped value.
195 ///
196 /// The borrow lasts until the returned `Ref` exits scope. Multiple
197 /// immutable borrows can be taken out at the same time.
198 ///
199 /// # Panics
200 ///
201 /// Panics if the value is currently mutably borrowed.
202 /// Panics if this is called from anywhere other than the script thread.
203 /// Use borrow_for_layout if the borrowed data might used during layout.
204 #[track_caller]
205 pub fn borrow(&self) -> Ref<'_, T> {
206 assert_in_script();
207 self.value.borrow()
208 }
209
210 /// Mutably borrows the wrapped value.
211 ///
212 /// The borrow lasts until the returned `RefMut` exits scope. The value
213 /// cannot be borrowed while this borrow is active.
214 ///
215 /// # Panics
216 ///
217 /// Panics if the value is currently borrowed.
218 /// Panics if this is called from anywhere other than the script thread.
219 #[track_caller]
220 pub fn borrow_mut(&self) -> RefMut<'_, T> {
221 assert_in_script();
222 self.value.borrow_mut()
223 }
224
225 /// Attempts to immutably borrow the wrapped value.
226 ///
227 /// The borrow lasts until the returned `Ref` exits scope. Multiple
228 /// immutable borrows can be taken out at the same time.
229 ///
230 /// Returns `None` if the value is currently mutably borrowed.
231 ///
232 /// # Panics
233 ///
234 /// Panics if this is called off the script thread.
235 pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
236 assert_in_script();
237 self.value.try_borrow()
238 }
239
240 /// Mutably borrows the wrapped value.
241 ///
242 /// The borrow lasts until the returned `RefMut` exits scope. The value
243 /// cannot be borrowed while this borrow is active.
244 ///
245 /// Returns `None` if the value is currently borrowed.
246 ///
247 /// # Panics
248 ///
249 /// Panics if this is called off the script thread.
250 pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
251 assert_in_script();
252 self.value.try_borrow_mut()
253 }
254}
255
256impl<T: Default> DomRefCell<T> {
257 /// Takes the wrapped value, leaving `Default::default()` in its place.
258 ///
259 /// # Panics
260 ///
261 /// Panics if the value is currently borrowed.
262 pub fn take(&self) -> T {
263 self.value.take()
264 }
265}
266
267unsafe impl<T: CustomTraceable> CustomTraceable for DomRefCell<T> {
268 unsafe fn trace(&self, trc: *mut JSTracer) {
269 unsafe { (*self).borrow().trace(trc) }
270 }
271}
272
273unsafe impl<T: js::gc::Traceable> js::gc::Traceable for DomRefCell<T> {
274 unsafe fn trace(&self, trc: *mut JSTracer) {
275 unsafe { (*self).borrow().trace(trc) };
276 }
277}