45 lines
1.1 KiB
Rust
45 lines
1.1 KiB
Rust
use std::{
|
|
fs::{self, File},
|
|
path::Path,
|
|
};
|
|
|
|
use directories_next::ProjectDirs;
|
|
|
|
use crate::net::BINCODE_CONFIG;
|
|
|
|
pub struct DataDir {
|
|
dirs: ProjectDirs,
|
|
}
|
|
|
|
impl Default for DataDir {
|
|
fn default() -> Self {
|
|
Self {
|
|
dirs: ProjectDirs::from("", "", "openworm").unwrap(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl DataDir {
|
|
pub fn get(&self) -> &Path {
|
|
self.dirs.data_local_dir()
|
|
}
|
|
|
|
pub fn load<T: bincode::Decode<()> + Default>(&self, path: &str) -> T {
|
|
let path = self.get().join(path);
|
|
match fs::read(path) {
|
|
Ok(bytes) => match bincode::decode_from_slice(&bytes, BINCODE_CONFIG) {
|
|
Ok((data, _)) => data,
|
|
Err(_) => todo!(),
|
|
},
|
|
Err(_) => T::default(),
|
|
}
|
|
}
|
|
|
|
pub fn save<T: bincode::Encode>(&self, path: &str, data: &T) {
|
|
let dir = self.get();
|
|
fs::create_dir_all(dir).unwrap();
|
|
let mut file = File::create(dir.join(path)).unwrap();
|
|
bincode::encode_into_std_write(data, &mut file, BINCODE_CONFIG).unwrap();
|
|
}
|
|
}
|