-
Notifications
You must be signed in to change notification settings - Fork 48
/
crc16.rs
79 lines (68 loc) · 2.16 KB
/
crc16.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use super::{Algorithm, Crc, Digest};
use crate::table::crc16_table;
impl Crc<u16> {
pub const fn new(algorithm: &'static Algorithm<u16>) -> Self {
let table = crc16_table(algorithm.width, algorithm.poly, algorithm.refin);
Self { algorithm, table }
}
pub const fn checksum(&self, bytes: &[u8]) -> u16 {
let mut crc = self.init();
crc = self.update(crc, bytes);
self.finalize(crc)
}
const fn init(&self) -> u16 {
if self.algorithm.refin {
self.algorithm.init.reverse_bits() >> (16u8 - self.algorithm.width)
} else {
self.algorithm.init << (16u8 - self.algorithm.width)
}
}
const fn table_entry(&self, index: u16) -> u16 {
self.table[(index & 0xFF) as usize]
}
const fn update(&self, mut crc: u16, bytes: &[u8]) -> u16 {
let mut i = 0;
if self.algorithm.refin {
while i < bytes.len() {
let table_index = crc ^ bytes[i] as u16;
crc = self.table_entry(table_index) ^ (crc >> 8);
i += 1;
}
} else {
while i < bytes.len() {
let table_index = (crc >> 8) ^ bytes[i] as u16;
crc = self.table_entry(table_index) ^ (crc << 8);
i += 1;
}
}
crc
}
const fn finalize(&self, mut crc: u16) -> u16 {
if self.algorithm.refin ^ self.algorithm.refout {
crc = crc.reverse_bits();
}
if !self.algorithm.refout {
crc >>= 16u8 - self.algorithm.width;
}
crc ^ self.algorithm.xorout
}
pub const fn digest(&self) -> Digest<u16> {
Digest::new(self)
}
}
impl<'a> Digest<'a, u16> {
const fn new(crc: &'a Crc<u16>) -> Self {
let value = crc.init();
Digest { crc, value }
}
pub fn update(&mut self, bytes: &[u8]) {
self.value = self.crc.update(self.value, bytes);
}
pub const fn updated(mut self, bytes: &[u8]) -> Self {
self.value = self.crc.update(self.value, bytes);
self
}
pub const fn finalize(self) -> u16 {
self.crc.finalize(self.value)
}
}