use std::path::Path;
pub use failure::Error;
use serde::de::DeserializeOwned;
pub use serde::{Serialize, Deserialize};
pub fn structify<T: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<T, Error> {
Ok(serde_json::from_reader(std::fs::File::open(path)?)?)
}
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);
}