1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use once_cell::sync::OnceCell;
use std::{
any::{Any, TypeId},
cell::RefCell,
collections::BTreeMap,
rc::Rc,
};
use crate::prelude::{Model, Proxy, Singleton};
#[derive(Default)]
pub struct BaseModel {
storages: RefCell<BTreeMap<TypeId, Rc<dyn Any>>>,
}
unsafe impl std::marker::Send for BaseModel {}
unsafe impl std::marker::Sync for BaseModel {}
impl BaseModel {
pub fn new() -> Self {
Self {
storages: RefCell::new(BTreeMap::new()),
}
}
}
impl Singleton for BaseModel {
fn global() -> &'static Self {
static BASE_MODEL_INSTANCE: OnceCell<BaseModel> = OnceCell::new();
BASE_MODEL_INSTANCE.get_or_init(Self::new)
}
}
impl Model for BaseModel {
fn has_proxy<P: Proxy>(&self) -> bool {
let type_id = TypeId::of::<P>();
self.storages.borrow().contains_key(&type_id)
}
fn register_proxy<P: Proxy>(&self, proxy: Rc<P>) {
let type_id = TypeId::of::<P>();
log::info!("Register Proxy [BaseModel] {:?}", proxy);
self.storages.borrow_mut().insert(type_id, proxy.clone());
proxy.on_register();
}
fn remove_proxy<P: Proxy>(&self) -> Option<Rc<P>> {
let type_id = TypeId::of::<P>();
self.storages
.borrow_mut()
.remove(&type_id)
.map(|proxy| match proxy.downcast::<P>() {
Ok(proxy) => {
proxy.on_remove();
proxy
}
Err(_) => {
panic!("Something wrong with proxy storage");
}
})
}
fn retrieve_proxy<P: Proxy>(&self) -> Option<Rc<P>> {
let type_id = TypeId::of::<P>();
match self.storages.borrow().get(&type_id) {
Some(item) => match item.clone().downcast::<P>() {
Ok(proxy) => Some(proxy),
Err(_) => {
log::error!("Something wrong with proxy storage");
None
}
},
None => None,
}
}
}