1use std::path::Path;
2
3pub use failure::Error;
4use serde::de::DeserializeOwned;
5pub use serde::{Serialize, Deserialize};
6
7pub fn structify<T: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<T, Error> {
9 Ok(serde_json::from_reader(std::fs::File::open(path)?)?)
10}
11
12pub fn jsonify<T: Serialize, P: AsRef<Path>>(x: &T, path: P) -> Result<(), Error> {
14 std::fs::write(path, serde_json::to_string(x)?)?;
15 Ok(())
16}
17
18#[macro_export]
19macro_rules! auto_json_impl {
20 ($type: ty) => {
21
22 impl $type {
23
24 fn from_json<P: AsRef<std::path::Path>>(path: P) -> Result<Self, failure::Error> {
25 crate::structify(path)
26 }
27
28 fn to_json<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), failure::Error> {
29 crate::jsonify(self, path)
30 }
31
32 }
33
34 };
35}
36
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[derive(Serialize, Deserialize)]
43 struct Data{
44 x: u8
45 }
46
47 auto_json_impl!(Data);
48
49}