wasm_bridge_js/
store.rs

1use std::{
2    cell::RefCell,
3    ops::{Deref, DerefMut},
4    rc::Rc,
5};
6
7use crate::*;
8
9#[derive(Debug, Default)]
10pub struct Store<T> {
11    engine: Engine,
12    data: DataHandle<T>,
13}
14
15impl<T> Store<T> {
16    pub fn new(engine: &Engine, data: T) -> Self {
17        Self {
18            engine: engine.clone(),
19            data: Rc::new(RefCell::new(data)),
20        }
21    }
22
23    pub(crate) fn from_handle(handle: DataHandle<T>) -> Self {
24        Self {
25            engine: Engine::default(), // Engine is unused, so this is file for now
26            data: handle,
27        }
28    }
29
30    pub fn engine(&self) -> &Engine {
31        &self.engine
32    }
33
34    pub fn data(&self) -> impl Deref<Target = T> + '_ {
35        self.data.borrow()
36    }
37
38    pub fn data_mut(&mut self) -> impl DerefMut<Target = T> + '_ {
39        self.data.borrow_mut()
40    }
41
42    pub(crate) fn data_handle(&self) -> &DataHandle<T> {
43        &self.data
44    }
45}
46
47pub(crate) type DataHandle<T> = Rc<RefCell<T>>;
48
49pub struct StoreContext<'a, T>(&'a T);
50
51impl<'a, T> StoreContext<'a, T> {
52    pub fn new(reference: &'a T) -> Self {
53        Self(reference)
54    }
55
56    pub fn data(&self) -> &T {
57        self.0
58    }
59}
60
61pub struct StoreContextMut<'a, T>(&'a mut T);
62
63impl<'a, T> StoreContextMut<'a, T> {
64    pub fn new(reference: &'a mut T) -> Self {
65        Self(reference)
66    }
67
68    pub fn data(&self) -> &T {
69        self.0
70    }
71
72    pub fn data_mut(&mut self) -> &mut T {
73        self.0
74    }
75}
76
77impl<T> Clone for Store<T> {
78    fn clone(&self) -> Self {
79        Self {
80            data: self.data.clone(),
81            engine: self.engine.clone(),
82        }
83    }
84}