#[derive(Debug, Clone, Copy)]
pub struct Fragment {
pub id: u16,
pub part: u16,
pub total: u16,
}
impl Fragment {
pub(crate) const SIZE: usize = 6;
pub(crate) fn parse(slice: &[u8]) -> std::io::Result<Self> {
if slice.len() >= 9 {
let id = u16::from_le_bytes([slice[3], slice[4]]);
let part = u16::from_le_bytes([slice[5], slice[6]]);
let total = u16::from_le_bytes([slice[7], slice[8]]);
Ok(Self {
id,
part,
total,
})
} else {
Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Data to parse is not long enough for fragment"))
}
}
pub(crate) fn dump<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<usize> {
writer.write_all(&self.id.to_le_bytes())?;
writer.write_all(&self.part.to_le_bytes())?;
writer.write_all(&self.total.to_le_bytes())?;
Ok(Self::SIZE)
}
pub(crate) fn is_valid(&self) -> bool {
self.part < self.total
}
}