From 44088f76e5a5aa92e771ec2bc5e43ce46c1e3cd1 Mon Sep 17 00:00:00 2001 From: griffi-gh Date: Mon, 6 Feb 2023 19:30:26 +0100 Subject: [PATCH] serializable trait --- kubi-udp/src/lib.rs | 1 + kubi-udp/src/serializable.rs | 22 ++++++++++++++++++++++ kubi-udp/src/server.rs | 2 +- 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 kubi-udp/src/serializable.rs diff --git a/kubi-udp/src/lib.rs b/kubi-udp/src/lib.rs index ec14b35..319ed4f 100644 --- a/kubi-udp/src/lib.rs +++ b/kubi-udp/src/lib.rs @@ -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 {} diff --git a/kubi-udp/src/serializable.rs b/kubi-udp/src/serializable.rs new file mode 100644 index 0000000..61da4d8 --- /dev/null +++ b/kubi-udp/src/serializable.rs @@ -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; + + fn serialize_to_vec(&self) -> Result> { + let mut buf = Vec::new(); + self.serialize(&mut buf)?; + Ok(buf) + } +} +impl Serializable for T { + fn serialize(&self, buf: &mut [u8]) -> Result<()> { + bincode::encode_into_slice(self, buf, BINCODE_CONFIG)?; + Ok(()) + } + fn deserialize(buf: &[u8]) -> Result { + bincode::decode_from_slice(buf, BINCODE_CONFIG)?.0 + } +} diff --git a/kubi-udp/src/server.rs b/kubi-udp/src/server.rs index 3edb8c2..fce125d 100644 --- a/kubi-udp/src/server.rs +++ b/kubi-udp/src/server.rs @@ -39,7 +39,7 @@ impl Server { clients: HashMap::with_capacity_and_hasher(MAX_CLIENTS, BuildNoHashHasher::default()) }) } - fn connect_client(&mut self, addr: SocketAddr) -> Result { + fn add_client(&mut self, addr: SocketAddr) -> Result { let Some(id) = (1..=self.config.max_clients) .map(|x| ClientId::new(x as _).unwrap()) .find(|i| self.clients.contains_key(i)) else {