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
use crate::router::Router;
use std::any::TypeId;
use std::cell::Ref;
use std::cell::RefCell;
use std::mem::discriminant;
use std::mem::Discriminant;
use std::ops::Deref;
use std::ops::DerefMut;
use std::rc::Rc;
pub struct Provided<T> {
pub data: Rc<T>,
}
impl<T> Deref for Provided<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T> Clone for Provided<T> {
fn clone(&self) -> Self {
Provided {
data: Rc::clone(&self.data),
}
}
}
impl Router {
pub fn provide<T: 'static>(&mut self, provided: T) {
let provided = Provided {
data: Rc::new(provided),
};
let type_id = TypeId::of::<Provided<T>>();
let provided = Box::new(provided);
self.provided.borrow_mut().insert(type_id, provided);
}
}
#[cfg(test)]
mod tests {
use super::*;
struct State {
count: u8,
}
#[test]
fn provide() {
let mut router = Router::default();
router.provide(State { count: 50 });
let state = router.provided.borrow();
let state = state
.get(&TypeId::of::<Provided<State>>())
.unwrap()
.downcast_ref::<Provided<State>>()
.expect("Downcast state");
assert_eq!(state.count, 50);
}
}