1use crate::error::Error;
9use crate::payload_util::require_exact_len;
10use alloc::vec::Vec;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct Com {
15 pub address: u8,
17 pub baud: u32,
19}
20
21impl Com {
22 pub fn encode(&self) -> Result<Vec<u8>, Error> {
24 let mut out = Vec::with_capacity(5);
25 out.push(self.address);
26 out.extend_from_slice(&self.baud.to_le_bytes());
27 Ok(out)
28 }
29
30 pub fn decode(data: &[u8]) -> Result<Self, Error> {
32 require_exact_len(data, 5, 0x54)?;
33 Ok(Self {
34 address: data[0],
35 baud: u32::from_le_bytes([data[1], data[2], data[3], data[4]]),
36 })
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 #[test]
45 fn roundtrip() {
46 let body = Com {
47 address: 0x05,
48 baud: 9600,
49 };
50 let bytes = body.encode().unwrap();
51 assert_eq!(bytes, [0x05, 0x80, 0x25, 0x00, 0x00]);
52 assert_eq!(Com::decode(&bytes).unwrap(), body);
53 }
54
55 #[test]
56 fn decode_rejects_wrong_length() {
57 assert!(matches!(
58 Com::decode(&[0; 4]),
59 Err(Error::PayloadLength { code: 0x54, .. })
60 ));
61 }
62}