use crate::error::Error;
use crate::payload_util::require_exact_len;
use alloc::vec::Vec;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Com {
pub address: u8,
pub baud: u32,
}
impl Com {
pub fn encode(&self) -> Result<Vec<u8>, Error> {
let mut out = Vec::with_capacity(5);
out.push(self.address);
out.extend_from_slice(&self.baud.to_le_bytes());
Ok(out)
}
pub fn decode(data: &[u8]) -> Result<Self, Error> {
require_exact_len(data, 5, 0x54)?;
Ok(Self {
address: data[0],
baud: u32::from_le_bytes([data[1], data[2], data[3], data[4]]),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip() {
let body = Com {
address: 0x05,
baud: 9600,
};
let bytes = body.encode().unwrap();
assert_eq!(bytes, [0x05, 0x80, 0x25, 0x00, 0x00]);
assert_eq!(Com::decode(&bytes).unwrap(), body);
}
#[test]
fn decode_rejects_wrong_length() {
assert!(matches!(
Com::decode(&[0; 4]),
Err(Error::PayloadLength { code: 0x54, .. })
));
}
}