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
use ron::de::{self, from_str};
use serde::Deserialize;
use std::fmt;
use std::fs::read_to_string;
use std::io;
use std::path::PathBuf;
use crate::key::Key;
use crate::load::{Load, Loaded, Storage};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Ron;
#[derive(Debug)]
pub enum RonError {
RonError(de::Error),
CannotReadFile(PathBuf, io::Error),
NoKey,
}
impl fmt::Display for RonError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
RonError::RonError(ref e) => write!(f, "RON error: {}", e),
RonError::CannotReadFile(ref path, ref e) => {
write!(f, "cannot read file {}: {}", path.display(), e)
}
RonError::NoKey => f.write_str("no path key available"),
}
}
}
impl<C, K, T> Load<C, K, Ron> for T
where K: Key + Into<Option<PathBuf>>,
T: 'static + for<'de> Deserialize<'de>, {
type Error = RonError;
fn load(key: K, _: &mut Storage<C, K>, _: &mut C) -> Result<Loaded<Self, K>, Self::Error> {
if let Some(path) = key.into() {
let file_content =
read_to_string(&path).map_err(|ioerr| RonError::CannotReadFile(path, ioerr))?;
from_str(&file_content)
.map(Loaded::without_dep)
.map_err(RonError::RonError)
} else {
Err(RonError::NoKey)
}
}
}