Remove unused packet variant, move peer UUID to start of packet
This commit is contained in:
parent
fee5fb3c95
commit
fe967d70b9
5 changed files with 18 additions and 66 deletions
|
|
@ -5,58 +5,19 @@ use uuid::Uuid;
|
|||
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,
|
||||
pub message: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Packet {
|
||||
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()
|
||||
pub fn create<T: From<Packet>>(peer: Uuid, message: Vec<u8>) -> T {
|
||||
Self { peer, message }.into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -67,13 +28,9 @@ impl TryFrom<Vec<u8>> for Packet {
|
|||
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))
|
||||
let message = value.split_off(UUID_SIZE);
|
||||
let uuid = Uuid::from_slice(value.as_slice()).map_err(|_| TryFromBytesError::NotUUID)?;
|
||||
Ok(Packet::create(uuid, message))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue