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
use crate::prelude::*;
#[cfg(any(feature = "yaml", feature = "json"))]
use serde::de::DeserializeOwned;
pub fn yaml_from_path<T>(path: &Path) -> Result<T>
where
T: DeserializeOwned,
{
let file = File::open(path)?;
let reader = BufReader::new(file);
let config: T = serde_yaml::from_reader(reader)?; Ok(config)
}
#[cfg(feature = "json")]
pub fn json_from_path<T>(path: &Path) -> Result<T>
where
T: DeserializeOwned,
{
let file = File::open(path)?;
let reader = BufReader::new(file);
let config: T = serde_json::from_reader(reader)?; Ok(config)
}
#[cfg(feature = "yaml")]
pub fn yaml_from_str<T>(text: &str) -> Result<T>
where
T: DeserializeOwned,
{
serde_yaml::from_str(text)
.with_context(|| format!("Failed to deserialize into yaml:\n{}", text))
}
#[cfg(feature = "json")]
pub fn json_from_str<T>(text: &str) -> Result<T>
where
T: DeserializeOwned,
{
serde_json::from_str(text)
.with_context(|| format!("Failed to deserialize into json:\n{}", text))
}
#[cfg(feature = "yaml")]
pub fn to_yaml_str<T>(t: &T) -> Result<String>
where
T: Serialize,
{
serde_yaml::to_string(t).with_context(|| "Failed to serialize into yaml") }