62 lines
1.4 KiB
Rust
62 lines
1.4 KiB
Rust
use std::{
|
|
fs::{self, File},
|
|
path::Path,
|
|
};
|
|
|
|
use directories_next::ProjectDirs;
|
|
|
|
use crate::net::BINCODE_CONFIG;
|
|
|
|
pub const CLIENT_DATA: &str = "client_data";
|
|
|
|
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();
|
|
}
|
|
}
|
|
|
|
#[derive(bincode::Encode, bincode::Decode)]
|
|
pub struct ClientData {
|
|
pub ip: String,
|
|
pub username: String,
|
|
}
|
|
|
|
impl Default for ClientData {
|
|
fn default() -> Self {
|
|
Self {
|
|
ip: "localhost:39420".to_string(),
|
|
username: "your [NOVEMBER]".to_string(),
|
|
}
|
|
}
|
|
}
|