add client data cache for ip and username

This commit is contained in:
2025-11-17 17:57:41 -05:00
parent 510fafac9f
commit b3c833c667
8 changed files with 153 additions and 24 deletions

59
src/rsc.rs Normal file
View File

@@ -0,0 +1,59 @@
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 mut file = File::create(self.get().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(),
}
}
}