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
use std::any::Any;
use std::collections::HashMap;

pub struct Depot {
    data: HashMap<String, Box<dyn Any + Send>>,
}

impl Depot {
    pub(crate) fn new() -> Depot {
        Depot { data: HashMap::new() }
    }

    pub fn insert<K, V>(&mut self, key: K, value: V)
    where
        K: Into<String>,
        V: Any + Send,
    {
        self.data.insert(key.into(), Box::new(value));
    }

    pub fn has<K>(&self, key: K) -> bool
    where
        K: Into<String>,
    {
        self.data.get(&key.into()).is_some()
    }

    pub fn try_borrow<K, V>(&self, key: K) -> Option<&V>
    where
        K: Into<String>,
        V: Any + Send,
    {
        self.data.get(&key.into()).and_then(|b| b.downcast_ref::<V>())
    }

    pub fn borrow<K, V>(&self, key: K) -> &V
    where
        K: Into<String>,
        V: Any + Send,
    {
        self.try_borrow(key).expect("required type is not present in depot container")
    }
    pub fn try_borrow_mut<K, V>(&mut self, key: K) -> Option<&mut V>
    where
        K: Into<String>,
        V: Any + Send,
    {
        self.data.get_mut(&key.into()).and_then(|b| b.downcast_mut::<V>())
    }

    pub fn borrow_mut<K, V>(&mut self, key: K) -> &mut V
    where
        K: Into<String>,
        V: Any + Send,
    {
        self.try_borrow_mut(key)
            .expect("required type is not present in depot container")
    }

    pub fn try_take<K, V>(&mut self, key: K) -> Option<V>
    where
        K: Into<String>,
        V: Any + Send,
    {
        self.data.remove(&key.into()).and_then(|b| b.downcast::<V>().ok()).map(|b| *b)
    }

    pub fn take<K, V>(&mut self, key: K) -> V
    where
        K: Into<String>,
        V: Any + Send,
    {
        self.try_take(key).expect("required type is not present in depot container")
    }
}