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
use std::path::Path;

pub use failure::Error;
use serde::de::DeserializeOwned;
pub use serde::{Serialize, Deserialize};

/// Convert any file into a struct
pub fn structify<T: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<T, Error> {
    Ok(serde_json::from_reader(std::fs::File::open(path)?)?)
}

/// Convert any struct to a file
pub fn jsonify<T: Serialize, P: AsRef<Path>>(x: &T, path: P) -> Result<(), Error> {
    std::fs::write(path, serde_json::to_string(x)?)?;
    Ok(())
}

#[macro_export]
macro_rules! auto_json_impl {
    ($type: ty) => {

        impl $type {

            fn from_json<P: AsRef<std::path::Path>>(path: P) -> Result<Self, failure::Error> {
                crate::structify(path)
            }

            fn to_json<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), failure::Error> {
                crate::jsonify(self, path)
            }

        }
        
    };
}


#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Serialize, Deserialize)]
    struct Data{
        x: u8
    }

    auto_json_impl!(Data);

}