diff options
Diffstat (limited to 'shared/src/packets.rs')
-rw-r--r-- | shared/src/packets.rs | 38 |
1 files changed, 33 insertions, 5 deletions
diff --git a/shared/src/packets.rs b/shared/src/packets.rs index c273028..325cf14 100644 --- a/shared/src/packets.rs +++ b/shared/src/packets.rs @@ -1,6 +1,9 @@ use anyhow::{Result, bail}; use glam::Vec3; -use std::io::{Read, Write}; +use std::{ + fmt::Display, + io::{Read, Write}, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Resource(pub [u8; 32]); @@ -27,6 +30,13 @@ impl Object { impl Packet { pub fn serialize(&self, w: &mut impl Write) -> Result<()> { + let mut buf = Vec::new(); + self.serialize_inner(&mut buf)?; + w.write_all(&(buf.len() as u16).to_be_bytes())?; + w.write_all(&buf)?; + Ok(()) + } + pub fn serialize_inner(&self, w: &mut impl Write) -> Result<()> { match self { Packet::RequestResource(resource) => { w.write_all(&[0x01])?; @@ -75,9 +85,9 @@ impl Packet { Ok(()) } pub fn deserialize(r: &mut impl Read) -> Result<Self> { - let mut tag = [0u8; 1]; - r.read_exact(&mut tag)?; - Ok(match tag[0] { + let mut size_tag = [0u8; 3]; + r.read_exact(&mut size_tag)?; + Ok(match size_tag[2] { 0x01 => Packet::RequestResource(read_res(r)?), 0x02 => Packet::RespondResource(read_data(r)?), 0x03 => Packet::Add(Object(read_u128(r)?), read_res(r)?), @@ -90,7 +100,12 @@ impl Packet { 0x06 => Packet::Pose(Object(read_u128(r)?), read_params(r)?), 0x07 => Packet::Parent(Object(read_u128(r)?), Object(read_u128(r)?)), 0x08 => Packet::Sound(Object(read_u128(r)?), read_data(r)?), - _ => bail!("unknown packet tag"), + _ => { + for _ in 0..u16::from_be_bytes([size_tag[0], size_tag[1]]) { + r.read_exact(&mut [0])?; + } + bail!("unknown packet tag"); + } }) } } @@ -128,3 +143,16 @@ fn read_params(r: &mut impl Read) -> Result<Vec<f32>> { } Ok(v) } + +impl Display for Resource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Res{{{:08x}{:08x}{:08x}{:08x}}}", + u64::from_be_bytes(self.0[0..8].try_into().unwrap()), + u64::from_be_bytes(self.0[8..16].try_into().unwrap()), + u64::from_be_bytes(self.0[16..24].try_into().unwrap()), + u64::from_be_bytes(self.0[24..32].try_into().unwrap()), + ) + } +} |