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
111
112
113
114
115
116
117
118
use std::any::Any;
use std::collections::HashMap;
use std::fmt::{self, Formatter};
#[derive(Default)]
pub struct Depot {
data: HashMap<String, Box<dyn Any + Send>>,
}
impl Depot {
#[inline]
pub fn new() -> Depot {
Depot { data: HashMap::new() }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Depot {
Depot {
data: HashMap::with_capacity(capacity),
}
}
#[inline]
pub fn capacity(&self) -> usize {
self.data.capacity()
}
#[inline]
pub fn insert<K, V>(&mut self, key: K, value: V)
where
K: Into<String>,
V: Any + Send + Sync,
{
self.data.insert(key.into(), Box::new(value));
}
#[inline]
pub fn contains_key(&self, key: &str) -> bool {
self.data.contains_key(key)
}
#[inline]
pub fn get<V>(&self, key: &str) -> Option<&V>
where
V: Any + Send,
{
self.data.get(key).and_then(|b| b.downcast_ref::<V>())
}
#[inline]
pub fn get_mut<V>(&mut self, key: &str) -> Option<&mut V>
where
V: Any + Send,
{
self.data.get_mut(key).and_then(|b| b.downcast_mut::<V>())
}
#[inline]
pub fn remove<V>(&mut self, key: &str) -> Option<V>
where
V: Any + Send,
{
self.data.remove(key).and_then(|b| b.downcast::<V>().ok()).map(|b| *b)
}
#[inline]
pub fn transfer(&mut self) -> Depot {
let mut data = HashMap::with_capacity(self.data.len());
for (k, v) in self.data.drain() {
data.insert(k, v);
}
Depot { data }
}
}
impl fmt::Debug for Depot {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Depot").field("keys", &self.data.keys()).finish()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_depot() {
let mut depot = Depot::with_capacity(6);
assert!(depot.capacity() >= 6);
depot.insert("one", "ONE".to_owned());
assert!(depot.contains_key("one"));
assert_eq!(depot.get::<String>("one").unwrap(), &"ONE".to_owned());
assert_eq!(depot.get_mut::<String>("one").unwrap(), &mut "ONE".to_owned());
}
#[test]
fn test_transfer() {
let mut depot = Depot::with_capacity(6);
depot.insert("one", "ONE".to_owned());
let depot = depot.transfer();
assert_eq!(depot.get::<String>("one").unwrap(), &"ONE".to_owned());
}
}