1pub const SOH: u8 = 0x01;
9pub const STX: u8 = 0x02;
11pub const EOT: u8 = 0x04;
13pub const ACK: u8 = 0x06;
15pub const NAK: u8 = 0x15;
18pub const CAN: u8 = 0x18;
20pub const CRC_START: u8 = b'C';
22pub const HP_CRC_START: u8 = b'D';
24pub(crate) const CR_KERMIT: u8 = b'\r';
26pub const SUB: u8 = 0x1A;
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Check {
33 Checksum,
36 Crc16,
40 HpCrc,
46}
47
48impl Check {
49 pub fn len(self) -> usize {
51 match self {
52 Check::Checksum => 1,
53 Check::Crc16 | Check::HpCrc => 2,
54 }
55 }
56
57 pub fn is_empty(self) -> bool {
59 false
60 }
61
62 pub fn compute(self, data: &[u8]) -> Vec<u8> {
64 match self {
65 Check::Checksum => vec![checksum(data)],
66 Check::Crc16 => crc16(data).to_be_bytes().to_vec(),
67 Check::HpCrc => hp_crc(data).to_be_bytes().to_vec(),
68 }
69 }
70
71 pub fn start_char(self) -> u8 {
73 match self {
74 Check::Checksum => NAK,
75 Check::Crc16 => CRC_START,
76 Check::HpCrc => HP_CRC_START,
77 }
78 }
79
80 pub fn from_start_char(byte: u8) -> Option<Check> {
82 match byte {
83 NAK => Some(Check::Checksum),
84 CRC_START => Some(Check::Crc16),
85 HP_CRC_START => Some(Check::HpCrc),
86 _ => None,
87 }
88 }
89}
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum BlockSize {
95 B128,
97 B1k,
99}
100
101impl BlockSize {
102 pub fn len(self) -> usize {
104 match self {
105 BlockSize::B128 => 128,
106 BlockSize::B1k => 1024,
107 }
108 }
109
110 pub fn is_empty(self) -> bool {
112 false
113 }
114
115 pub fn header(self) -> u8 {
117 match self {
118 BlockSize::B128 => SOH,
119 BlockSize::B1k => STX,
120 }
121 }
122
123 pub fn from_header(byte: u8) -> Option<BlockSize> {
125 match byte {
126 SOH => Some(BlockSize::B128),
127 STX => Some(BlockSize::B1k),
128 _ => None,
129 }
130 }
131}
132
133pub fn checksum(data: &[u8]) -> u8 {
135 data.iter().fold(0u8, |acc, &b| acc.wrapping_add(b))
136}
137
138pub fn crc16(data: &[u8]) -> u16 {
140 let mut crc: u16 = 0;
141 for &byte in data {
142 crc ^= u16::from(byte) << 8;
143 for _ in 0..8 {
144 crc = if crc & 0x8000 != 0 {
145 (crc << 1) ^ 0x1021
146 } else {
147 crc << 1
148 };
149 }
150 }
151 crc
152}
153
154pub fn hp_crc(data: &[u8]) -> u16 {
157 let mut crc: u16 = 0;
158 for &byte in data {
159 for nibble in [byte & 0x0F, byte >> 4] {
160 let q = (crc ^ u16::from(nibble)) & 0x0F;
161 crc = (crc >> 4) ^ (q * 0x1081);
162 }
163 }
164 crc
165}
166
167pub fn frame_len(size: BlockSize, check: Check) -> usize {
169 3 + size.len() + check.len()
170}
171
172pub fn encode_block(
175 num: u8,
176 size: BlockSize,
177 data: &[u8],
178 pad: u8,
179 check: Check,
180) -> Result<Vec<u8>, EncodeError> {
181 if data.len() > size.len() {
182 return Err(EncodeError {
183 len: data.len(),
184 max: size.len(),
185 });
186 }
187 Ok(frame_block(num, size, data, pad, check))
188}
189
190pub(crate) fn frame_block(num: u8, size: BlockSize, data: &[u8], pad: u8, check: Check) -> Vec<u8> {
193 let n = size.len();
194 let mut out = Vec::with_capacity(frame_len(size, check));
195 out.push(size.header());
196 out.push(num);
197 out.push(!num);
198 let take = data.len().min(n);
199 out.extend_from_slice(data.get(..take).unwrap_or_default());
200 out.resize(3 + n, pad);
201 let check_bytes = check.compute(out.get(3..).unwrap_or_default());
202 out.extend_from_slice(&check_bytes);
203 out
204}
205
206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub struct EncodeError {
209 pub len: usize,
211 pub max: usize,
213}
214
215impl std::fmt::Display for EncodeError {
216 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217 write!(
218 f,
219 "block data too long: {} bytes, the block holds {}",
220 self.len, self.max
221 )
222 }
223}
224
225impl std::error::Error for EncodeError {}
226
227#[derive(Clone, Debug, PartialEq, Eq)]
229pub struct Block {
230 pub num: u8,
232 pub data: Vec<u8>,
234}
235
236#[derive(Clone, Copy, Debug, PartialEq, Eq)]
238pub enum BlockError {
239 BadHeader,
241 BadNumber,
243 BadLength,
245 BadCheck,
247}
248
249pub fn decode_block(frame: &[u8], check: Check) -> Result<Block, BlockError> {
251 let size = frame
252 .first()
253 .and_then(|&b| BlockSize::from_header(b))
254 .ok_or(BlockError::BadHeader)?;
255 if frame.len() != frame_len(size, check) {
256 return Err(BlockError::BadLength);
257 }
258 let (num, inv) = match (frame.get(1), frame.get(2)) {
259 (Some(&a), Some(&b)) => (a, b),
260 _ => return Err(BlockError::BadLength),
261 };
262 if num != !inv {
263 return Err(BlockError::BadNumber);
264 }
265 let data = frame.get(3..3 + size.len()).ok_or(BlockError::BadLength)?;
266 let got = frame.get(3 + size.len()..).ok_or(BlockError::BadLength)?;
267 if got != check.compute(data).as_slice() {
268 return Err(BlockError::BadCheck);
269 }
270 Ok(Block {
271 num,
272 data: data.to_vec(),
273 })
274}
275
276#[cfg(test)]
277#[allow(clippy::unwrap_used, clippy::expect_used)]
278mod tests {
279 use super::*;
280
281 #[test]
282 fn crc16_known_vectors() {
283 assert_eq!(crc16(b"123456789"), 0x31C3);
285 assert_eq!(crc16(b""), 0);
286 assert_eq!(crc16(b"A"), 0x58E5);
287 assert_eq!(crc16(&[SUB; 128]), crc16(&[SUB; 128]));
289 assert_eq!(crc16(&[0u8; 128]), 0);
290 }
291
292 #[test]
293 fn crc16_is_not_the_kermit_check() {
294 assert_ne!(crc16(b"123456789"), 0x2189);
296 }
297
298 #[test]
299 fn hp_crc_known_vectors() {
300 assert_eq!(hp_crc(b"123456789"), 0x2189);
302 assert_eq!(hp_crc(b""), 0);
303 assert_eq!(Check::HpCrc.compute(b"123456789"), vec![0x21, 0x89]);
304 assert_eq!(Check::from_start_char(b'D'), Some(Check::HpCrc));
305 assert_eq!(Check::from_start_char(0x15), Some(Check::Checksum));
306 assert_eq!(Check::from_start_char(b'C'), Some(Check::Crc16));
307 assert_eq!(Check::from_start_char(b'X'), None);
308 }
309
310 #[test]
311 fn checksum_wraps() {
312 assert_eq!(checksum(b""), 0);
313 assert_eq!(checksum(&[0xFF, 0x02]), 0x01);
314 let all: Vec<u8> = (0..=127).collect();
315 assert_eq!(checksum(&all), (127 * 128 / 2 % 256) as u8);
316 }
317
318 #[test]
319 fn encode_checksum_block_bytes() {
320 let b = encode_block(1, BlockSize::B128, b"AB", SUB, Check::Checksum).unwrap();
321 assert_eq!(b.len(), 132);
322 assert_eq!(&b[..5], &[SOH, 0x01, 0xFE, b'A', b'B']);
323 assert!(b[5..131].iter().all(|&x| x == SUB));
324 assert_eq!(b[131], 0x4F);
326 }
327
328 #[test]
329 fn encode_crc_block_bytes() {
330 let data: Vec<u8> = (0..128).collect();
331 let b = encode_block(0xFF, BlockSize::B128, &data, 0, Check::Crc16).unwrap();
332 assert_eq!(b.len(), 133);
333 assert_eq!(&b[..3], &[SOH, 0xFF, 0x00]);
334 let crc = crc16(&data);
335 assert_eq!(&b[131..], &[(crc >> 8) as u8, crc as u8]);
336 }
337
338 #[test]
339 fn encode_1k_block() {
340 let b = encode_block(2, BlockSize::B1k, &[7; 1000], 0, Check::Crc16).unwrap();
341 assert_eq!(b.len(), 1029);
342 assert_eq!(&b[..3], &[STX, 2, 0xFD]);
343 assert_eq!(b[1002], 7);
344 assert_eq!(b[1003], 0);
345 }
346
347 #[test]
348 fn oversized_block_is_an_error() {
349 assert_eq!(
350 encode_block(1, BlockSize::B128, &[0; 129], SUB, Check::Crc16),
351 Err(EncodeError { len: 129, max: 128 })
352 );
353 assert!(encode_block(1, BlockSize::B1k, &[0; 1024], SUB, Check::Crc16).is_ok());
354 }
355
356 #[test]
357 fn decode_round_trip_and_errors() {
358 let b = encode_block(3, BlockSize::B128, b"hello", SUB, Check::Crc16).unwrap();
359 let got = decode_block(&b, Check::Crc16).unwrap();
360 assert_eq!(got.num, 3);
361 assert!(got.data.starts_with(b"hello"));
362 assert_eq!(
363 decode_block(&b, Check::Checksum),
364 Err(BlockError::BadLength)
365 );
366 let mut bad = b.clone();
367 bad[10] ^= 1;
368 assert_eq!(decode_block(&bad, Check::Crc16), Err(BlockError::BadCheck));
369 let mut bad = b.clone();
370 bad[2] = 0;
371 assert_eq!(decode_block(&bad, Check::Crc16), Err(BlockError::BadNumber));
372 assert_eq!(
373 decode_block(&[EOT], Check::Crc16),
374 Err(BlockError::BadHeader)
375 );
376 }
377}