pub const SOH: u8 = 0x01;
pub const STX: u8 = 0x02;
pub const EOT: u8 = 0x04;
pub const ACK: u8 = 0x06;
pub const NAK: u8 = 0x15;
pub const CAN: u8 = 0x18;
pub const CRC_START: u8 = b'C';
pub const HP_CRC_START: u8 = b'D';
pub(crate) const CR_KERMIT: u8 = b'\r';
pub const SUB: u8 = 0x1A;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Check {
Checksum,
Crc16,
HpCrc,
}
impl Check {
pub fn len(self) -> usize {
match self {
Check::Checksum => 1,
Check::Crc16 | Check::HpCrc => 2,
}
}
pub fn is_empty(self) -> bool {
false
}
pub fn compute(self, data: &[u8]) -> Vec<u8> {
match self {
Check::Checksum => vec![checksum(data)],
Check::Crc16 => crc16(data).to_be_bytes().to_vec(),
Check::HpCrc => hp_crc(data).to_be_bytes().to_vec(),
}
}
pub fn start_char(self) -> u8 {
match self {
Check::Checksum => NAK,
Check::Crc16 => CRC_START,
Check::HpCrc => HP_CRC_START,
}
}
pub fn from_start_char(byte: u8) -> Option<Check> {
match byte {
NAK => Some(Check::Checksum),
CRC_START => Some(Check::Crc16),
HP_CRC_START => Some(Check::HpCrc),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BlockSize {
B128,
B1k,
}
impl BlockSize {
pub fn len(self) -> usize {
match self {
BlockSize::B128 => 128,
BlockSize::B1k => 1024,
}
}
pub fn is_empty(self) -> bool {
false
}
pub fn header(self) -> u8 {
match self {
BlockSize::B128 => SOH,
BlockSize::B1k => STX,
}
}
pub fn from_header(byte: u8) -> Option<BlockSize> {
match byte {
SOH => Some(BlockSize::B128),
STX => Some(BlockSize::B1k),
_ => None,
}
}
}
pub fn checksum(data: &[u8]) -> u8 {
data.iter().fold(0u8, |acc, &b| acc.wrapping_add(b))
}
pub fn crc16(data: &[u8]) -> u16 {
let mut crc: u16 = 0;
for &byte in data {
crc ^= u16::from(byte) << 8;
for _ in 0..8 {
crc = if crc & 0x8000 != 0 {
(crc << 1) ^ 0x1021
} else {
crc << 1
};
}
}
crc
}
pub fn hp_crc(data: &[u8]) -> u16 {
let mut crc: u16 = 0;
for &byte in data {
for nibble in [byte & 0x0F, byte >> 4] {
let q = (crc ^ u16::from(nibble)) & 0x0F;
crc = (crc >> 4) ^ (q * 0x1081);
}
}
crc
}
pub fn frame_len(size: BlockSize, check: Check) -> usize {
3 + size.len() + check.len()
}
pub fn encode_block(
num: u8,
size: BlockSize,
data: &[u8],
pad: u8,
check: Check,
) -> Result<Vec<u8>, EncodeError> {
if data.len() > size.len() {
return Err(EncodeError {
len: data.len(),
max: size.len(),
});
}
Ok(frame_block(num, size, data, pad, check))
}
pub(crate) fn frame_block(num: u8, size: BlockSize, data: &[u8], pad: u8, check: Check) -> Vec<u8> {
let n = size.len();
let mut out = Vec::with_capacity(frame_len(size, check));
out.push(size.header());
out.push(num);
out.push(!num);
let take = data.len().min(n);
out.extend_from_slice(data.get(..take).unwrap_or_default());
out.resize(3 + n, pad);
let check_bytes = check.compute(out.get(3..).unwrap_or_default());
out.extend_from_slice(&check_bytes);
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncodeError {
pub len: usize,
pub max: usize,
}
impl std::fmt::Display for EncodeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"block data too long: {} bytes, the block holds {}",
self.len, self.max
)
}
}
impl std::error::Error for EncodeError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Block {
pub num: u8,
pub data: Vec<u8>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlockError {
BadHeader,
BadNumber,
BadLength,
BadCheck,
}
pub fn decode_block(frame: &[u8], check: Check) -> Result<Block, BlockError> {
let size = frame
.first()
.and_then(|&b| BlockSize::from_header(b))
.ok_or(BlockError::BadHeader)?;
if frame.len() != frame_len(size, check) {
return Err(BlockError::BadLength);
}
let (num, inv) = match (frame.get(1), frame.get(2)) {
(Some(&a), Some(&b)) => (a, b),
_ => return Err(BlockError::BadLength),
};
if num != !inv {
return Err(BlockError::BadNumber);
}
let data = frame.get(3..3 + size.len()).ok_or(BlockError::BadLength)?;
let got = frame.get(3 + size.len()..).ok_or(BlockError::BadLength)?;
if got != check.compute(data).as_slice() {
return Err(BlockError::BadCheck);
}
Ok(Block {
num,
data: data.to_vec(),
})
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn crc16_known_vectors() {
assert_eq!(crc16(b"123456789"), 0x31C3);
assert_eq!(crc16(b""), 0);
assert_eq!(crc16(b"A"), 0x58E5);
assert_eq!(crc16(&[SUB; 128]), crc16(&[SUB; 128]));
assert_eq!(crc16(&[0u8; 128]), 0);
}
#[test]
fn crc16_is_not_the_kermit_check() {
assert_ne!(crc16(b"123456789"), 0x2189);
}
#[test]
fn hp_crc_known_vectors() {
assert_eq!(hp_crc(b"123456789"), 0x2189);
assert_eq!(hp_crc(b""), 0);
assert_eq!(Check::HpCrc.compute(b"123456789"), vec![0x21, 0x89]);
assert_eq!(Check::from_start_char(b'D'), Some(Check::HpCrc));
assert_eq!(Check::from_start_char(0x15), Some(Check::Checksum));
assert_eq!(Check::from_start_char(b'C'), Some(Check::Crc16));
assert_eq!(Check::from_start_char(b'X'), None);
}
#[test]
fn checksum_wraps() {
assert_eq!(checksum(b""), 0);
assert_eq!(checksum(&[0xFF, 0x02]), 0x01);
let all: Vec<u8> = (0..=127).collect();
assert_eq!(checksum(&all), (127 * 128 / 2 % 256) as u8);
}
#[test]
fn encode_checksum_block_bytes() {
let b = encode_block(1, BlockSize::B128, b"AB", SUB, Check::Checksum).unwrap();
assert_eq!(b.len(), 132);
assert_eq!(&b[..5], &[SOH, 0x01, 0xFE, b'A', b'B']);
assert!(b[5..131].iter().all(|&x| x == SUB));
assert_eq!(b[131], 0x4F);
}
#[test]
fn encode_crc_block_bytes() {
let data: Vec<u8> = (0..128).collect();
let b = encode_block(0xFF, BlockSize::B128, &data, 0, Check::Crc16).unwrap();
assert_eq!(b.len(), 133);
assert_eq!(&b[..3], &[SOH, 0xFF, 0x00]);
let crc = crc16(&data);
assert_eq!(&b[131..], &[(crc >> 8) as u8, crc as u8]);
}
#[test]
fn encode_1k_block() {
let b = encode_block(2, BlockSize::B1k, &[7; 1000], 0, Check::Crc16).unwrap();
assert_eq!(b.len(), 1029);
assert_eq!(&b[..3], &[STX, 2, 0xFD]);
assert_eq!(b[1002], 7);
assert_eq!(b[1003], 0);
}
#[test]
fn oversized_block_is_an_error() {
assert_eq!(
encode_block(1, BlockSize::B128, &[0; 129], SUB, Check::Crc16),
Err(EncodeError { len: 129, max: 128 })
);
assert!(encode_block(1, BlockSize::B1k, &[0; 1024], SUB, Check::Crc16).is_ok());
}
#[test]
fn decode_round_trip_and_errors() {
let b = encode_block(3, BlockSize::B128, b"hello", SUB, Check::Crc16).unwrap();
let got = decode_block(&b, Check::Crc16).unwrap();
assert_eq!(got.num, 3);
assert!(got.data.starts_with(b"hello"));
assert_eq!(
decode_block(&b, Check::Checksum),
Err(BlockError::BadLength)
);
let mut bad = b.clone();
bad[10] ^= 1;
assert_eq!(decode_block(&bad, Check::Crc16), Err(BlockError::BadCheck));
let mut bad = b.clone();
bad[2] = 0;
assert_eq!(decode_block(&bad, Check::Crc16), Err(BlockError::BadNumber));
assert_eq!(
decode_block(&[EOT], Check::Crc16),
Err(BlockError::BadHeader)
);
}
}