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
//! ZIP が各エントリに求める CRC-32
//!
//! 多項式はビットを逆に並べる流儀の 0xedb88320 である。
//! 1 バイトごとに 8 回まわす代わりに、256 通りをあらかじめ表にして 1 回引く。
/// 1 バイト分をまとめた表
static TABLE: [u32; 256] = table();
/// 表を作る。const なので実行時には作らない
const fn table() -> [u32; 256] {
let mut result = [0u32; 256];
let mut index = 0;
while index < 256 {
let mut value = index as u32;
let mut round = 0;
while round < 8 {
value = if value & 1 == 1 {0xedb88320 ^ (value >> 1)} else {value >> 1};
round += 1;
}
result[index] = value;
index += 1;
}
result
}
/// 少しずつ渡しても、一度に渡したときと同じ値になる CRC-32
#[derive(Debug, Clone, Copy)]
pub struct Crc {
value: u32,
}
impl Crc {
pub fn new() -> Crc {
Crc {value: 0xffffffff}
}
/// 続きのバイト列を流し込む
pub fn update(&mut self, data: &[u8]) {
let mut value = self.value;
for byte in data {
value = TABLE[((value ^ *byte as u32) & 0xff) as usize] ^ (value >> 8);
}
self.value = value;
}
/// ここまでの値
pub fn finish(&self) -> u32 {
!self.value
}
}
impl Default for Crc {
fn default() -> Crc {
Crc::new()
}
}
/// 一度に全部渡すとき
pub fn checksum(data: &[u8]) -> u32 {
let mut crc = Crc::new();
crc.update(data);
crc.finish()
}