/rust/registry/src/github.com-1ecc6299db9ec823/crc-1.8.1/src/crc32.rs
Line | Count | Source (jump to first uncovered line) |
1 | | #[cfg(feature = "std")] |
2 | | use std::hash::Hasher; |
3 | | #[cfg(not(feature = "std"))] |
4 | | use core::hash::Hasher; |
5 | | |
6 | | pub use util::make_table_crc32 as make_table; |
7 | | |
8 | | include!(concat!(env!("OUT_DIR"), "/crc32_constants.rs")); |
9 | | |
10 | | pub struct Digest { |
11 | | table: [u32; 256], |
12 | | initial: u32, |
13 | | value: u32 |
14 | | } |
15 | | |
16 | | pub trait Hasher32 { |
17 | | fn reset(&mut self); |
18 | | fn write(&mut self, bytes: &[u8]); |
19 | | fn sum32(&self) -> u32; |
20 | | } |
21 | | |
22 | 26.4k | pub fn update(mut value: u32, table: &[u32; 256], bytes: &[u8]) -> u32 { |
23 | 26.4k | value = !value; |
24 | 856k | for &i in bytes.iter() { |
25 | 856k | value = table[((value as u8) ^ i) as usize] ^ (value >> 8) |
26 | | } |
27 | 26.4k | !value |
28 | 26.4k | } |
29 | | |
30 | 26.4k | pub fn checksum_ieee(bytes: &[u8]) -> u32 { |
31 | 26.4k | return update(0, &IEEE_TABLE, bytes); |
32 | 26.4k | } |
33 | | |
34 | 0 | pub fn checksum_castagnoli(bytes: &[u8]) -> u32 { |
35 | 0 | return update(0, &CASTAGNOLI_TABLE, bytes); |
36 | 0 | } |
37 | | |
38 | 0 | pub fn checksum_koopman(bytes: &[u8]) -> u32 { |
39 | 0 | return update(0, &KOOPMAN_TABLE, bytes); |
40 | 0 | } |
41 | | |
42 | | impl Digest { |
43 | 0 | pub fn new(poly: u32) -> Digest { |
44 | 0 | Digest { |
45 | 0 | table: make_table(poly), |
46 | 0 | initial: 0, |
47 | 0 | value: 0 |
48 | 0 | } |
49 | 0 | } |
50 | | |
51 | 0 | pub fn new_with_initial(poly: u32, initial: u32) -> Digest { |
52 | 0 | Digest { |
53 | 0 | table: make_table(poly), |
54 | 0 | initial: initial, |
55 | 0 | value: initial |
56 | 0 | } |
57 | 0 | } |
58 | | } |
59 | | |
60 | | impl Hasher32 for Digest { |
61 | 0 | fn reset(&mut self) { |
62 | 0 | self.value = self.initial; |
63 | 0 | } |
64 | 0 | fn write(&mut self, bytes: &[u8]) { |
65 | 0 | self.value = update(self.value, &self.table, bytes); |
66 | 0 | } |
67 | 0 | fn sum32(&self) -> u32 { |
68 | 0 | self.value |
69 | 0 | } |
70 | | } |
71 | | |
72 | | /// Implementation of std::hash::Hasher so that types which #[derive(Hash)] can hash with Digest. |
73 | | impl Hasher for Digest { |
74 | 0 | fn write(&mut self, bytes: &[u8]) { |
75 | 0 | Hasher32::write(self, bytes); |
76 | 0 | } |
77 | | |
78 | 0 | fn finish(&self) -> u64 { |
79 | 0 | self.sum32() as u64 |
80 | 0 | } |
81 | | } |