crcany_core/
crc.rs

1pub trait Crc {
2    type Int;
3
4    fn init(&self) -> Self::Int;
5    fn add_bytes(&self, previous: Self::Int, data: &[u8]) -> Self::Int;
6}
7
8pub struct Computer<Algorithm: Crc> {
9    crc: Algorithm,
10    val: Algorithm::Int,
11}
12
13impl<'a, Algorithm: Crc> Computer<Algorithm> {
14    pub fn new(crc: Algorithm) -> Self {
15        let val = crc.init();
16        Computer { crc, val }
17    }
18
19    pub fn add_bytes(&mut self, data: &[u8]) {
20        let mut other = self.crc.init();
21        std::mem::swap(&mut other, &mut self.val);
22        self.val = self.crc.add_bytes(other, data);
23    }
24
25    pub fn into_inner(self) -> Algorithm::Int {
26        self.val
27    }
28
29    pub fn crc(crc: Algorithm, data: &[u8]) -> Algorithm::Int {
30        let mut state = Self::new(crc);
31        state.add_bytes(data);
32        state.into_inner()
33    }
34}
35
36impl<T: Crc> Crc for &T {
37    type Int = T::Int;
38    fn init(&self) -> Self::Int {
39        (*self).init()
40    }
41    fn add_bytes(&self, previous: Self::Int, data: &[u8]) -> Self::Int {
42        (*self).add_bytes(previous, data)
43    }
44}