use crate::crc;
use crate::error::FrameError;
const MIN_FRAME_LEN: usize = 4; const CRC_LEN: usize = 2;
pub const MAX_DATA_LEN: usize = 252;
pub const MAX_FRAME_LEN: usize = 1 + 1 + MAX_DATA_LEN + CRC_LEN;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Frame<'a> {
address: u8,
function_code: u8,
data: &'a [u8],
}
impl<'a> Frame<'a> {
pub fn parse(buf: &'a [u8]) -> Result<Self, FrameError> {
if buf.len() < MIN_FRAME_LEN {
return Err(FrameError::TooShort {
needed: MIN_FRAME_LEN,
got: buf.len(),
});
}
let body_len = buf.len() - CRC_LEN;
let body = &buf[..body_len];
let expected = u16::from(buf[body_len]) | (u16::from(buf[body_len + 1]) << 8);
if crc::checksum(body) != expected {
return Err(FrameError::ChecksumMismatch);
}
Ok(Self {
address: body[0],
function_code: body[1],
data: &body[2..],
})
}
pub fn parse_response(buf: &'a [u8]) -> Result<Self, FrameError> {
let frame = Self::parse(buf)?;
if frame.address == 0 {
return Err(FrameError::BroadcastResponse);
}
Ok(frame)
}
#[must_use]
pub const fn address(&self) -> u8 {
self.address
}
#[must_use]
pub const fn function_code(&self) -> u8 {
self.function_code
}
#[must_use]
pub const fn data(&self) -> &'a [u8] {
self.data
}
}
pub fn encode(
buf: &mut [u8],
address: u8,
function_code: u8,
data: &[u8],
) -> Result<usize, FrameError> {
let total = 1 + 1 + data.len() + CRC_LEN;
if buf.len() < total {
return Err(FrameError::TooShort {
needed: total,
got: buf.len(),
});
}
buf[0] = address;
buf[1] = function_code;
let data_end = 2 + data.len();
buf[2..data_end].copy_from_slice(data);
let crc = crc::checksum(&buf[..data_end]);
buf[data_end] = (crc & 0xFF) as u8;
buf[data_end + 1] = (crc >> 8) as u8;
Ok(total)
}
#[cfg(kani)]
mod kani_proofs {
use super::{Frame, encode};
#[kani::proof]
#[kani::unwind(17)]
fn parse_never_panics() {
let buf: [u8; 16] = kani::any();
let _ = Frame::parse(&buf);
}
#[kani::proof]
#[kani::unwind(17)]
fn encode_never_panics() {
let mut buf = [0u8; 32];
let address: u8 = kani::any();
let function_code: u8 = kani::any();
let data: [u8; 8] = kani::any();
let _ = encode(&mut buf, address, function_code, &data);
}
#[kani::proof]
#[kani::unwind(17)]
fn encode_then_parse_round_trips() {
let mut buf = [0u8; 32];
let address: u8 = kani::any();
let function_code: u8 = kani::any();
let data: [u8; 8] = kani::any();
let n = encode(&mut buf, address, function_code, &data).unwrap();
let frame = Frame::parse(&buf[..n]).unwrap();
assert_eq!(frame.address(), address);
assert_eq!(frame.function_code(), function_code);
assert_eq!(frame.data(), &data);
}
#[kani::proof]
#[kani::unwind(17)]
fn parse_response_never_panics() {
let buf: [u8; 16] = kani::any();
let _ = Frame::parse_response(&buf);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_a_reference_read_holding_registers_request() {
let buf = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
let frame = Frame::parse(&buf).unwrap();
assert_eq!(frame.address(), 0x11);
assert_eq!(frame.function_code(), 0x03);
assert_eq!(frame.data(), &[0x00, 0x6B, 0x00, 0x03]);
}
#[test]
fn rejects_a_buffer_shorter_than_the_minimum_frame() {
assert_eq!(
Frame::parse(&[0x11, 0x03, 0x00]),
Err(FrameError::TooShort { needed: 4, got: 3 })
);
}
#[test]
fn rejects_a_bad_checksum() {
let mut buf = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
buf[7] ^= 0xFF;
assert_eq!(Frame::parse(&buf), Err(FrameError::ChecksumMismatch));
}
#[test]
fn encode_matches_a_reference_frame() {
let expected = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
let mut buf = [0u8; MAX_FRAME_LEN];
let n = encode(&mut buf, 0x11, 0x03, &[0x00, 0x6B, 0x00, 0x03]).unwrap();
assert_eq!(&buf[..n], &expected[..]);
}
#[test]
fn encode_round_trips_through_parse() {
let data = [1u8, 2, 3, 4, 5];
let mut buf = [0u8; MAX_FRAME_LEN];
let n = encode(&mut buf, 0x01, 0x03, &data).unwrap();
let frame = Frame::parse(&buf[..n]).unwrap();
assert_eq!(frame.address(), 0x01);
assert_eq!(frame.function_code(), 0x03);
assert_eq!(frame.data(), &data);
}
#[test]
fn parse_response_rejects_the_broadcast_address() {
let data = [1u8, 2, 3, 4, 5];
let mut buf = [0u8; MAX_FRAME_LEN];
let n = encode(&mut buf, 0x00, 0x03, &data).unwrap();
assert!(Frame::parse(&buf[..n]).is_ok());
assert_eq!(
Frame::parse_response(&buf[..n]),
Err(FrameError::BroadcastResponse)
);
}
#[test]
fn parse_response_accepts_a_non_broadcast_address() {
let buf = [0x11, 0x03, 0x00, 0x6B, 0x00, 0x03, 0x76, 0x87];
let frame = Frame::parse_response(&buf).unwrap();
assert_eq!(frame.address(), 0x11);
}
}