Slightly better implementation of peers, still need to create a more generic system for deciding which components to distribute where and then use that for Peers.
This commit is contained in:
parent
e013fb427a
commit
53fe3333f0
14 changed files with 438 additions and 265 deletions
|
|
@ -2,19 +2,95 @@ use bevy::prelude::*;
|
|||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TryFromBytesError {
|
||||
InsufficientLength,
|
||||
NotUUID,
|
||||
NotVariant,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum PacketType {
|
||||
Standard = 0x00,
|
||||
Peer = 0x01,
|
||||
}
|
||||
|
||||
impl From<PacketType> for u8 {
|
||||
fn from(value: PacketType) -> Self {
|
||||
value as u8
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for PacketType {
|
||||
type Error = TryFromBytesError;
|
||||
|
||||
fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
|
||||
match value {
|
||||
value if value == PacketType::Standard as u8 => Ok(PacketType::Standard),
|
||||
value if value == PacketType::Peer as u8 => Ok(PacketType::Peer),
|
||||
_ => Err(TryFromBytesError::NotVariant),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const UUID_SIZE: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Packet {
|
||||
pub message: Vec<u8>,
|
||||
pub variant: PacketType,
|
||||
pub peer: Uuid,
|
||||
}
|
||||
|
||||
impl Packet {
|
||||
pub fn new(message: Vec<u8>, peer: Uuid) -> Self {
|
||||
Self { peer, message }
|
||||
pub fn new(message: Vec<u8>, variant: PacketType, peer: Uuid) -> Self {
|
||||
Self {
|
||||
message,
|
||||
variant,
|
||||
peer,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create<T: From<Packet>>(message: Vec<u8>, peer: Uuid) -> T {
|
||||
Self {
|
||||
message,
|
||||
variant: PacketType::Standard,
|
||||
peer,
|
||||
}
|
||||
.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 uuid = Uuid::from_slice(value.split_off(value.len() - UUID_SIZE).as_slice())
|
||||
.map_err(|_| TryFromBytesError::NotUUID)?;
|
||||
let variant = value
|
||||
.pop()
|
||||
.ok_or(TryFromBytesError::InsufficientLength)?
|
||||
.try_into()?;
|
||||
Ok(Packet::new(value, variant, uuid))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Event)]
|
||||
pub struct OutboundPacket(pub Packet);
|
||||
|
||||
impl From<Packet> for OutboundPacket {
|
||||
fn from(value: Packet) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Event)]
|
||||
pub struct InboundPacket(pub Packet);
|
||||
|
||||
impl From<Packet> for InboundPacket {
|
||||
fn from(value: Packet) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue