1#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
17pub enum CrcCheck {
18 #[default]
21 Strict,
22 Lenient,
29 Off,
31}
32
33impl CrcCheck {
34 pub(crate) fn accepts(self, x25: u16, kermit: u16, wire_be: u16) -> bool {
38 match self {
39 Self::Strict => wire_be == x25.swap_bytes(),
40 Self::Lenient => [x25, x25.swap_bytes(), kermit, kermit.swap_bytes()].contains(&wire_be),
41 Self::Off => true,
42 }
43 }
44}
45
46#[allow(clippy::indexing_slicing, clippy::cast_possible_truncation)]
48const fn table() -> [u16; 256] {
49 let mut t = [0u16; 256];
50 let mut i = 0;
51 while i < 256 {
52 let mut crc = i as u16;
53 let mut bit = 0;
54 while bit < 8 {
55 crc = if crc & 1 != 0 { (crc >> 1) ^ 0x8408 } else { crc >> 1 };
56 bit += 1;
57 }
58 t[i] = crc;
59 i += 1;
60 }
61 t
62}
63
64static TABLE: [u16; 256] = table();
65
66fn step(crc: u16, byte: u8) -> u16 {
68 let [low, _] = (crc ^ u16::from(byte)).to_le_bytes();
69 (crc >> 8) ^ TABLE.get(usize::from(low)).copied().unwrap_or(0)
71}
72
73#[derive(Clone, Copy, Debug)]
75pub struct X25(u16);
76
77impl Default for X25 {
78 fn default() -> Self {
79 Self::new()
80 }
81}
82
83impl X25 {
84 pub const fn new() -> Self {
86 Self(0xFFFF)
87 }
88
89 pub fn update(&mut self, bytes: &[u8]) {
91 self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
92 }
93
94 pub const fn finish(self) -> u16 {
96 self.0 ^ 0xFFFF
97 }
98}
99
100#[derive(Clone, Copy, Debug, Default)]
102pub struct Kermit(u16);
103
104impl Kermit {
105 pub const fn new() -> Self {
107 Self(0)
108 }
109
110 pub fn update(&mut self, bytes: &[u8]) {
112 self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
113 }
114
115 pub const fn finish(self) -> u16 {
117 self.0
118 }
119}
120
121pub fn x25(bytes: &[u8]) -> u16 {
123 let mut c = X25::new();
124 c.update(bytes);
125 c.finish()
126}
127
128pub fn kermit(bytes: &[u8]) -> u16 {
130 let mut c = Kermit::new();
131 c.update(bytes);
132 c.finish()
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn standard_check_values() {
141 assert_eq!(x25(b"123456789"), 0x906E);
142 assert_eq!(kermit(b"123456789"), 0x2189);
143 }
144
145 #[test]
146 fn incremental_equals_one_shot() {
147 let mut c = X25::new();
148 c.update(b"1234");
149 c.update(b"56789");
150 assert_eq!(c.finish(), x25(b"123456789"));
151 }
152
153 #[test]
155 fn strict_wants_x25_low_byte_first() {
156 let (x25, k) = (0x906E, 0x2189);
157 assert!(CrcCheck::Strict.accepts(x25, k, 0x6E90));
158 assert!(!CrcCheck::Strict.accepts(x25, k, 0x906E));
159 assert!(!CrcCheck::Strict.accepts(x25, k, 0x2189));
160 assert!(!CrcCheck::Strict.accepts(x25, k, 0x8921));
161 for wire in [0x6E90, 0x906E, 0x2189, 0x8921] {
162 assert!(CrcCheck::Lenient.accepts(x25, k, wire));
163 }
164 assert!(!CrcCheck::Lenient.accepts(x25, k, 0x1234));
165 assert!(CrcCheck::Off.accepts(x25, k, 0));
166 assert_eq!(CrcCheck::default(), CrcCheck::Strict);
167 }
168}