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
use std::collections::HashMap;
use std::str::FromStr;
pub trait ExtendedMap<K, V> {
fn get_owned(&self, key: K) -> Option<V>;
fn get_optional(&self, key: K, default: V) -> V;
fn get_compulsory(&self, key: K, error: &'static str) -> Result<V, &'static str>;
fn get_optional_parsed<T>(
&self,
key: K,
default: T,
error: &'static str,
) -> Result<T, &'static str>
where
T: FromStr;
fn get_compulsory_parsed<T>(&self, key: K, error: &'static str) -> Result<T, &'static str>
where
T: FromStr;
}
impl ExtendedMap<&'static str, String> for HashMap<String, String> {
fn get_owned(&self, key: &str) -> Option<String> {
self.get(key).map(|s| s.to_string())
}
fn get_optional(&self, key: &str, default: String) -> String {
self.get(key).unwrap_or(&default).to_string()
}
fn get_compulsory(&self, key: &str, error: &'static str) -> Result<String, &'static str> {
self.get(key).map_or(Err(error), |s| Ok(s.clone()))
}
fn get_optional_parsed<T>(
&self,
key: &str,
default: T,
error: &'static str,
) -> Result<T, &'static str>
where
T: FromStr,
{
self.get(key)
.map_or(Ok(default), |s| s.parse::<T>().map_err(|_| error))
}
fn get_compulsory_parsed<T>(&self, key: &str, error: &'static str) -> Result<T, &'static str>
where
T: FromStr,
{
self.get(key)
.map_or(Err(error), |s| s.parse::<T>().map_err(|_| error))
}
}