Skip to main content

wry_bindgen/
parent.rs

1//! Shared parent storage for generated extended Rust types.
2
3use crate::{Ref, RefMut};
4
5/// Storage wrapper for the auto-injected parent field on extended Rust types.
6pub struct Parent<T> {
7    inner: alloc::rc::Rc<core::cell::RefCell<T>>,
8}
9
10impl<T> Clone for Parent<T> {
11    fn clone(&self) -> Self {
12        Self {
13            inner: alloc::rc::Rc::clone(&self.inner),
14        }
15    }
16}
17
18// Match upstream wasm-bindgen, whose `Rc<WasmRefCell<T>>`-backed `Parent` opts into the
19// unwind-safe markers (`WasmRefCell` implements both). These are safe marker traits.
20impl<T> core::panic::UnwindSafe for Parent<T> {}
21impl<T> core::panic::RefUnwindSafe for Parent<T> {}
22
23impl<T: core::fmt::Debug> core::fmt::Debug for Parent<T> {
24    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
25        f.debug_tuple("Parent")
26            .field(&*self.inner.borrow())
27            .finish()
28    }
29}
30
31impl<T> Parent<T> {
32    pub fn new(value: T) -> Self {
33        Self {
34            inner: alloc::rc::Rc::new(core::cell::RefCell::new(value)),
35        }
36    }
37
38    pub fn borrow(&self) -> Ref<'_, T> {
39        Ref {
40            inner: self.inner.borrow(),
41        }
42    }
43
44    pub fn borrow_mut(&self) -> RefMut<'_, T> {
45        RefMut {
46            inner: self.inner.borrow_mut(),
47        }
48    }
49}
50
51impl<T> From<T> for Parent<T> {
52    fn from(value: T) -> Self {
53        Parent::new(value)
54    }
55}