#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CrcCheck {
#[default]
Strict,
Lenient,
Off,
}
impl CrcCheck {
pub(crate) fn accepts(self, x25: u16, kermit: u16, wire_be: u16) -> bool {
match self {
Self::Strict => wire_be == x25.swap_bytes(),
Self::Lenient => [x25, x25.swap_bytes(), kermit, kermit.swap_bytes()].contains(&wire_be),
Self::Off => true,
}
}
}
#[allow(clippy::indexing_slicing, clippy::cast_possible_truncation)]
const fn table() -> [u16; 256] {
let mut t = [0u16; 256];
let mut i = 0;
while i < 256 {
let mut crc = i as u16;
let mut bit = 0;
while bit < 8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0x8408 } else { crc >> 1 };
bit += 1;
}
t[i] = crc;
i += 1;
}
t
}
static TABLE: [u16; 256] = table();
fn step(crc: u16, byte: u8) -> u16 {
let [low, _] = (crc ^ u16::from(byte)).to_le_bytes();
(crc >> 8) ^ TABLE.get(usize::from(low)).copied().unwrap_or(0)
}
#[derive(Clone, Copy, Debug)]
pub struct X25(u16);
impl Default for X25 {
fn default() -> Self {
Self::new()
}
}
impl X25 {
pub const fn new() -> Self {
Self(0xFFFF)
}
pub fn update(&mut self, bytes: &[u8]) {
self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
}
pub const fn finish(self) -> u16 {
self.0 ^ 0xFFFF
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Kermit(u16);
impl Kermit {
pub const fn new() -> Self {
Self(0)
}
pub fn update(&mut self, bytes: &[u8]) {
self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
}
pub const fn finish(self) -> u16 {
self.0
}
}
pub fn x25(bytes: &[u8]) -> u16 {
let mut c = X25::new();
c.update(bytes);
c.finish()
}
pub fn kermit(bytes: &[u8]) -> u16 {
let mut c = Kermit::new();
c.update(bytes);
c.finish()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn standard_check_values() {
assert_eq!(x25(b"123456789"), 0x906E);
assert_eq!(kermit(b"123456789"), 0x2189);
}
#[test]
fn incremental_equals_one_shot() {
let mut c = X25::new();
c.update(b"1234");
c.update(b"56789");
assert_eq!(c.finish(), x25(b"123456789"));
}
#[test]
fn strict_wants_x25_low_byte_first() {
let (x25, k) = (0x906E, 0x2189);
assert!(CrcCheck::Strict.accepts(x25, k, 0x6E90));
assert!(!CrcCheck::Strict.accepts(x25, k, 0x906E));
assert!(!CrcCheck::Strict.accepts(x25, k, 0x2189));
assert!(!CrcCheck::Strict.accepts(x25, k, 0x8921));
for wire in [0x6E90, 0x906E, 0x2189, 0x8921] {
assert!(CrcCheck::Lenient.accepts(x25, k, wire));
}
assert!(!CrcCheck::Lenient.accepts(x25, k, 0x1234));
assert!(CrcCheck::Off.accepts(x25, k, 0));
assert_eq!(CrcCheck::default(), CrcCheck::Strict);
}
}