Read improv packet bytes into struct

This commit is contained in:
2024-10-27 12:46:42 +01:00
parent 5134589f6e
commit 5582ec6cb2
2 changed files with 41 additions and 15 deletions

View File

@@ -103,3 +103,37 @@ pub fn calculate_checksum(data: &Vec<u8>) -> u8 {
return checksum;
}
pub struct ImprovPacket {
pub version: u8,
pub r#type: PacketType,
pub data: Vec<u8>,
}
impl ImprovPacket {
pub fn try_from_bytes(bytes: &Vec<u8>) -> Result<Self, &str> {
if bytes.len() < 11 {
return Err("Packet too small");
}
for i in 0..5 {
if bytes[i] != IMPROV_HEADER[i] {
return Err("Improv header not found");
}
}
let data: Vec<u8> = Vec::new();
let length: usize = bytes[8].into();
if bytes.len() != length + 10 {
return Err("Packet with invalid length");
}
return Ok(Self {
version: bytes[6],
r#type: PacketType::try_from(&bytes[7])?,
data: bytes[9..(bytes.len()-1)].to_vec(),
});
}
}