Serialising and deserialising structured data into wire-format bytes without std, without serde_json, and without a heap.
The no_std constraint: No Vec for dynamic output. No String. Every buffer is either passed in by the caller or stack-allocated with a fixed compile-time size.
Manual bit manipulation approach (SpaceCAN CAN frames):
pub struct CanFrame {
id: u32, // 11-bit or 29-bit arbitration ID
dlc: u8, // Data length code (0-8)
data: [u8; 8],
}
impl CanFrame {
pub fn encode_into(&self, buf: &mut [u8; 13]) {
// Bytes 0-3: ID (big-endian, upper 11 bits of u32)
buf[0..4].copy_from_slice(&self.id.to_be_bytes());
// Byte 4: DLC
buf[4] = self.dlc;
// Bytes 5-12: data
buf[5..5 + self.dlc as usize]
.copy_from_slice(&self.data[..self.dlc as usize]);
}
pub fn decode(buf: &[u8; 13]) -> Result<Self, DecodeError> {
let id = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]);
if id > 0x7FF { return Err(DecodeError::InvalidId); }
let dlc = buf[4];
if dlc > 8 { return Err(DecodeError::InvalidDlc); }
let mut data = [0u8; 8];
data[..dlc as usize].copy_from_slice(&buf[5..5 + dlc as usize]);
Ok(CanFrame { id, dlc, data })
}
}The key discipline: every decode operation validates before accepting. The Result return type forces the caller to handle the error — invalid frames are caught at the boundary, not propagated silently.