distributed_physics_test/src/net/packet.rs

53 lines
1.2 KiB
Rust

use bevy::prelude::*;
use uuid::Uuid;
#[derive(Debug)]
pub enum TryFromBytesError {
InsufficientLength,
NotUUID,
}
pub const UUID_SIZE: usize = 16;
#[derive(Clone, Debug)]
pub struct Packet {
pub peer: Uuid,
pub message: Vec<u8>,
}
impl Packet {
pub fn create<T: From<Packet>>(peer: Uuid, message: Vec<u8>) -> T {
Self { peer, message }.into()
}
}
impl TryFrom<Vec<u8>> for Packet {
type Error = TryFromBytesError;
fn try_from(mut value: Vec<u8>) -> std::result::Result<Self, Self::Error> {
if value.len() < UUID_SIZE {
return Err(TryFromBytesError::InsufficientLength);
}
let message = value.split_off(UUID_SIZE);
let uuid = Uuid::from_slice(value.as_slice()).map_err(|_| TryFromBytesError::NotUUID)?;
Ok(Packet::create(uuid, message))
}
}
#[derive(Debug, Message)]
pub struct OutboundPacket(pub Packet);
impl From<Packet> for OutboundPacket {
fn from(value: Packet) -> Self {
Self(value)
}
}
#[derive(Debug, Message)]
pub struct InboundPacket(pub Packet);
impl From<Packet> for InboundPacket {
fn from(value: Packet) -> Self {
Self(value)
}
}