add client data cache for ip and username
This commit is contained in:
59
src/rsc.rs
Normal file
59
src/rsc.rs
Normal 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user