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
use std::any::{Any, TypeId};
use std::sync::Arc;
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use std::fmt;
type AnyMap = HashMap<TypeId, Box<Any + Send + Sync>, BuildHasherDefault<IdHasher>>;
#[derive(Debug, Default)]
struct IdHasher(u64);
impl Hasher for IdHasher {
fn write(&mut self, _: &[u8]) {
unreachable!("TypeId calls write_u64");
}
#[inline]
fn write_u64(&mut self, id: u64) {
self.0 = id;
}
#[inline]
fn finish(&self) -> u64 {
self.0
}
}
pub(crate) struct ConfigBuilder {
inner: AnyMap,
}
impl ConfigBuilder {
pub(crate) fn new() -> Self {
Self { inner: AnyMap::default() }
}
pub(crate) fn insert<T: Send + Sync + 'static>(mut self, val: T) -> Self {
self.inner.insert(TypeId::of::<T>(), Box::new(val));
self
}
pub(crate) fn into_config(self) -> Config {
Config { inner: Arc::new(self.inner) }
}
}
impl fmt::Debug for ConfigBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ConfigBuilder")
.finish()
}
}
#[derive(Clone)]
pub struct Config {
inner: Arc<AnyMap>,
}
impl Config {
pub fn get<T: 'static>(&self) -> Option<&T> {
self.inner
.get(&TypeId::of::<T>())
.and_then(|boxed| {
(&**boxed as &Any).downcast_ref()
})
}
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Config")
.finish()
}
}