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
use std::{collections::HashMap, fmt, sync::Arc};
use crate::{config::Value, INet, IServer, Net, Result, Server};
pub type NetFromConfig<T> = Box<dyn Fn(Vec<Net>, Value) -> Result<T>>;
pub type ServerFromConfig<T> = Box<dyn Fn(Net, Net, Value) -> Result<T>>;
pub struct Registry {
pub net: HashMap<String, NetFromConfig<Net>>,
pub server: HashMap<String, ServerFromConfig<Server>>,
}
impl fmt::Debug for Registry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Registry")
.field("net", &self.net.keys())
.field("server", &self.server.keys())
.finish()
}
}
impl Registry {
pub fn new() -> Registry {
Registry {
net: HashMap::new(),
server: HashMap::new(),
}
}
pub fn add_net<N: INet + 'static>(
&mut self,
name: impl Into<String>,
from_cfg: impl Fn(Vec<Net>, Value) -> Result<N> + 'static,
) {
self.net.insert(
name.into(),
Box::new(move |net, cfg| from_cfg(net, cfg).map(|n| Arc::new(n) as Net)),
);
}
pub fn add_server<S: IServer + 'static>(
&mut self,
name: impl Into<String>,
from_cfg: impl Fn(Net, Net, Value) -> Result<S> + 'static,
) {
self.server.insert(
name.into(),
Box::new(move |listen_net, net, cfg| {
from_cfg(listen_net, net, cfg).map(|n| Box::new(n) as Server)
}),
);
}
}