use serde::{Serialize, de::DeserializeOwned};
use std::{
fs::File,
io::{self, Read, Write},
path::Path,
};
pub trait Persistable: Serialize + DeserializeOwned + Sized {
fn to_json(&self) -> serde_json::Result<String> {
serde_json::to_string_pretty(self)
}
fn from_json(s: &str) -> serde_json::Result<Self> {
serde_json::from_str(s)
}
fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), io::Error> {
let json = self.to_json().map_err(io::Error::other)?;
let mut file = File::create(path)?;
file.write_all(json.as_bytes())
}
fn load<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
let mut file = File::open(path)?;
let mut contents = String::new();
let _num_bytes_read = file.read_to_string(&mut contents)?;
Self::from_json(&contents).map_err(io::Error::other)
}
}
impl<T> Persistable for T where T: Serialize + DeserializeOwned + Sized {}