serializable trait

This commit is contained in:
griffi-gh 2023-02-06 19:30:26 +01:00
parent b44e08e954
commit c8ff99e98c
3 changed files with 24 additions and 1 deletions

View file

@ -2,6 +2,7 @@ pub mod client;
pub mod server;
pub(crate) mod packet;
pub(crate) mod common;
pub(crate) mod serializable;
pub use common::ClientId;
//pub(crate) trait Serializable: bincode::Encode + bincode::Decode {}

View file

@ -0,0 +1,22 @@
use anyhow::Result;
use crate::BINCODE_CONFIG;
pub trait Serializable: bincode::Encode + bincode::Decode {
fn serialize(&self, buf: &mut [u8]) -> Result<()>;
fn deserialize(buf: &[u8]) -> Result<Self>;
fn serialize_to_vec(&self) -> Result<Vec<u8>> {
let mut buf = Vec::new();
self.serialize(&mut buf)?;
Ok(buf)
}
}
impl<T: bincode::Encode + bincode::Decode> Serializable for T {
fn serialize(&self, buf: &mut [u8]) -> Result<()> {
bincode::encode_into_slice(self, buf, BINCODE_CONFIG)?;
Ok(())
}
fn deserialize(buf: &[u8]) -> Result<Self> {
bincode::decode_from_slice(buf, BINCODE_CONFIG)?.0
}
}

View file

@ -39,7 +39,7 @@ impl Server {
clients: HashMap::with_capacity_and_hasher(MAX_CLIENTS, BuildNoHashHasher::default())
})
}
fn connect_client(&mut self, addr: SocketAddr) -> Result<ClientId> {
fn add_client(&mut self, addr: SocketAddr) -> Result<ClientId> {
let Some(id) = (1..=self.config.max_clients)
.map(|x| ClientId::new(x as _).unwrap())
.find(|i| self.clients.contains_key(i)) else {