1use std::cell::{OnceCell, UnsafeCell};
28use std::default::Default;
29use std::hash::{Hash, Hasher};
30use std::ops::Deref;
31use std::{mem, ptr};
32
33use js::context::NoGC;
34use js::jsapi::{Heap, JSObject, JSTracer, Value};
35use js::rust::HandleValue;
36use layout_api::TrustedNodeAddress;
37use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
38pub(crate) use script_bindings::root::*;
39use style::thread_state;
40
41use crate::dom::bindings::conversions::DerivedFrom;
42use crate::dom::bindings::inheritance::Castable;
43use crate::dom::bindings::reflector::DomObject;
44use crate::dom::bindings::trace::JSTraceable;
45use crate::dom::node::Node;
46
47pub(crate) trait ToLayout<T> {
48 unsafe fn to_layout(&self) -> LayoutDom<'_, T>;
54}
55
56impl<T: DomObject> ToLayout<T> for Dom<T> {
57 unsafe fn to_layout(&self) -> LayoutDom<'_, T> {
58 assert_in_layout();
59 LayoutDom {
60 value: unsafe { self.as_ptr().as_ref().unwrap() },
61 }
62 }
63}
64
65#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
68#[repr(transparent)]
69pub(crate) struct LayoutDom<'dom, T> {
70 value: &'dom T,
71}
72
73impl<'dom, T> LayoutDom<'dom, T>
74where
75 T: Castable,
76{
77 pub(crate) fn upcast<U>(&self) -> LayoutDom<'dom, U>
79 where
80 U: Castable,
81 T: DerivedFrom<U>,
82 {
83 assert_in_layout();
84 LayoutDom {
85 value: self.value.upcast::<U>(),
86 }
87 }
88
89 pub(crate) fn downcast<U>(&self) -> Option<LayoutDom<'dom, U>>
91 where
92 U: DerivedFrom<T>,
93 {
94 assert_in_layout();
95 self.value.downcast::<U>().map(|value| LayoutDom { value })
96 }
97
98 pub(crate) fn is<U>(&self) -> bool
100 where
101 U: DerivedFrom<T>,
102 {
103 assert_in_layout();
104 self.value.is::<U>()
105 }
106
107 pub(crate) unsafe fn as_ref(self) -> &'dom T {
113 self.value
114 }
115}
116
117impl<T> LayoutDom<'_, T>
118where
119 T: DomObject,
120{
121 pub(crate) unsafe fn get_jsobject(&self) -> *mut JSObject {
123 assert_in_layout();
124 self.value.reflector().get_jsobject().get()
125 }
126}
127
128impl<T> Copy for LayoutDom<'_, T> {}
129
130impl<T> PartialEq for LayoutDom<'_, T> {
131 fn eq(&self, other: &Self) -> bool {
132 std::ptr::eq(self.value, other.value)
133 }
134}
135
136impl<T> Eq for LayoutDom<'_, T> {}
137
138impl<T> Hash for LayoutDom<'_, T> {
139 fn hash<H: Hasher>(&self, state: &mut H) {
140 (self.value as *const T).hash(state)
141 }
142}
143
144#[expect(clippy::non_canonical_clone_impl)]
145impl<T> Clone for LayoutDom<'_, T> {
146 #[inline]
147 fn clone(&self) -> Self {
148 assert_in_layout();
149 *self
150 }
151}
152
153impl LayoutDom<'_, Node> {
154 pub(crate) unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> Self {
157 assert_in_layout();
158 let TrustedNodeAddress(addr) = inner;
159 LayoutDom {
160 value: unsafe { &*(addr as *const Node) },
161 }
162 }
163}
164
165#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
171#[derive(JSTraceable)]
172pub(crate) struct MutDom<T: DomObject> {
173 val: UnsafeCell<Dom<T>>,
174}
175
176impl<T: DomObject> MutDom<T> {
177 pub(crate) fn new(initial: &T) -> MutDom<T> {
179 assert_in_script();
180 MutDom {
181 val: UnsafeCell::new(Dom::from_ref(initial)),
182 }
183 }
184
185 pub(crate) fn set(&self, val: &T) {
187 assert_in_script();
188 unsafe {
189 *self.val.get() = Dom::from_ref(val);
190 }
191 }
192
193 pub(crate) fn get(&self) -> DomRoot<T> {
195 assert_in_script();
196 unsafe { DomRoot::from_ref(&*ptr::read(self.val.get())) }
197 }
198}
199
200impl<T: DomObject> MallocSizeOf for MutDom<T> {
201 fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
202 0
204 }
205}
206
207impl<T: DomObject> PartialEq for MutDom<T> {
208 fn eq(&self, other: &Self) -> bool {
209 unsafe { *self.val.get() == *other.val.get() }
210 }
211}
212
213impl<T: DomObject + PartialEq> PartialEq<T> for MutDom<T> {
214 fn eq(&self, other: &T) -> bool {
215 unsafe { **self.val.get() == *other }
216 }
217}
218
219pub(crate) fn assert_in_layout() {
220 debug_assert!(thread_state::get().is_layout());
221}
222
223#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
226pub(crate) struct UnrootedDom<'a, T: DomObject> {
227 inner: Dom<T>,
228 no_gc: &'a NoGC,
229}
230
231impl<'a, T: DomObject> UnrootedDom<'a, T> {
232 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
234 pub(crate) fn from_dom(object: Dom<T>, no_gc: &'a NoGC) -> UnrootedDom<'a, T> {
235 UnrootedDom {
236 inner: object,
237 no_gc,
238 }
239 }
240}
241
242impl<'a, T: DomObject> Deref for UnrootedDom<'a, T> {
243 type Target = Dom<T>;
244
245 fn deref(&self) -> &Self::Target {
246 &self.inner
247 }
248}
249
250impl<'a, T: Castable> UnrootedDom<'a, T> {
254 #[expect(dead_code)]
256 pub fn upcast<U>(dom: UnrootedDom<'a, T>) -> UnrootedDom<'a, U>
257 where
258 U: Castable,
259 T: DerivedFrom<U>,
260 {
261 UnrootedDom {
262 inner: unsafe { mem::transmute::<Dom<T>, Dom<U>>(dom.inner) },
263 no_gc: dom.no_gc,
264 }
265 }
266
267 pub fn downcast<U>(dom: UnrootedDom<'a, T>) -> Option<UnrootedDom<'a, U>>
269 where
270 U: DerivedFrom<T>,
271 {
272 if dom.is::<U>() {
273 Some(UnrootedDom {
274 inner: unsafe { mem::transmute::<Dom<T>, Dom<U>>(dom.inner) },
275 no_gc: dom.no_gc,
276 })
277 } else {
278 None
279 }
280 }
281}
282
283#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
290#[derive(JSTraceable)]
291pub(crate) struct MutNullableDom<T: DomObject> {
292 ptr: UnsafeCell<Option<Dom<T>>>,
293}
294
295impl<T: DomObject> MutNullableDom<T> {
296 pub(crate) fn new(initial: Option<&T>) -> MutNullableDom<T> {
298 assert_in_script();
299 MutNullableDom {
300 ptr: UnsafeCell::new(initial.map(Dom::from_ref)),
301 }
302 }
303
304 pub(crate) fn or_init<F>(&self, cb: F) -> DomRoot<T>
307 where
308 F: FnOnce() -> DomRoot<T>,
309 {
310 assert_in_script();
311 match self.get() {
312 Some(inner) => inner,
313 None => {
314 let inner = cb();
315 self.set(Some(&inner));
316 inner
317 },
318 }
319 }
320
321 pub(crate) unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<'_, T>> {
324 assert_in_layout();
325 unsafe { (*self.ptr.get()).as_ref().map(|js| js.to_layout()) }
326 }
327
328 pub(crate) fn get(&self) -> Option<DomRoot<T>> {
330 assert_in_script();
331 unsafe { ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o)) }
332 }
333
334 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
338 pub(crate) fn get_unrooted<'a>(&self, no_gc: &'a NoGC) -> Option<UnrootedDom<'a, T>> {
339 assert_in_script();
340 let ptr = unsafe { ptr::read(self.ptr.get()) };
341 ptr.map(|o| Dom::from_ref(&*o))
342 .map(|dom| UnrootedDom { inner: dom, no_gc })
343 }
344
345 pub(crate) fn set(&self, val: Option<&T>) {
347 assert_in_script();
348 unsafe {
349 *self.ptr.get() = val.map(|p| Dom::from_ref(p));
350 }
351 }
352
353 pub(crate) fn take(&self) -> Option<DomRoot<T>> {
355 let value = self.get();
356 self.set(None);
357 value
358 }
359
360 pub(crate) fn clear(&self) {
362 self.set(None)
363 }
364
365 pub(crate) fn if_is_some<F, R>(&self, cb: F) -> Option<&R>
367 where
368 F: FnOnce(&T) -> &R,
369 {
370 unsafe {
371 if let Some(ref value) = *self.ptr.get() {
372 Some(cb(value))
373 } else {
374 None
375 }
376 }
377 }
378}
379
380impl<T: DomObject> PartialEq for MutNullableDom<T> {
381 fn eq(&self, other: &Self) -> bool {
382 unsafe { *self.ptr.get() == *other.ptr.get() }
383 }
384}
385
386impl<T: DomObject> PartialEq<Option<&T>> for MutNullableDom<T> {
387 fn eq(&self, other: &Option<&T>) -> bool {
388 unsafe { *self.ptr.get() == other.map(Dom::from_ref) }
389 }
390}
391
392impl<T: DomObject> Default for MutNullableDom<T> {
393 fn default() -> MutNullableDom<T> {
394 assert_in_script();
395 MutNullableDom {
396 ptr: UnsafeCell::new(None),
397 }
398 }
399}
400
401impl<T: DomObject> MallocSizeOf for MutNullableDom<T> {
402 fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
403 0
405 }
406}
407
408#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
415pub(crate) struct DomOnceCell<T: DomObject> {
416 ptr: OnceCell<Dom<T>>,
417}
418
419impl<T> DomOnceCell<T>
420where
421 T: DomObject,
422{
423 pub(crate) fn init_once<F>(&self, cb: F) -> &T
426 where
427 F: FnOnce() -> DomRoot<T>,
428 {
429 assert_in_script();
430 self.ptr.get_or_init(|| Dom::from_ref(&cb()))
431 }
432}
433
434impl<T: DomObject> Default for DomOnceCell<T> {
435 fn default() -> DomOnceCell<T> {
436 assert_in_script();
437 DomOnceCell {
438 ptr: OnceCell::new(),
439 }
440 }
441}
442
443impl<T: DomObject> MallocSizeOf for DomOnceCell<T> {
444 fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
445 0
447 }
448}
449
450unsafe impl<T: DomObject> JSTraceable for DomOnceCell<T> {
451 unsafe fn trace(&self, trc: *mut JSTracer) {
452 if let Some(ptr) = self.ptr.get() {
453 unsafe { ptr.trace(trc) };
454 }
455 }
456}
457
458impl<'dom, T> LayoutDom<'dom, T>
459where
460 T: 'dom + DomObject,
461{
462 pub(crate) fn unsafe_get(self) -> &'dom T {
465 assert_in_layout();
466 self.value
467 }
468
469 pub(crate) unsafe fn to_layout_slice(slice: &'dom [Dom<T>]) -> &'dom [LayoutDom<'dom, T>] {
472 let _ = mem::transmute::<Dom<T>, LayoutDom<T>>;
475 unsafe { &*(slice as *const [Dom<T>] as *const [LayoutDom<T>]) }
476 }
477}
478
479pub trait AsHandleValue<'a> {
485 fn as_handle_value(&'a self) -> HandleValue<'a>;
486}
487
488impl<'a> AsHandleValue<'a> for Heap<Value> {
489 #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
490 fn as_handle_value(&'a self) -> HandleValue<'a> {
491 unsafe { HandleValue::from_marked_location(self.ptr.get() as *const _) }
494 }
495}