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