Maraiah/src/durandal/crc.rs

35 lines
574 B
Rust
Raw Normal View History

2019-02-08 21:08:53 -08:00
//! Cyclic redundancy check function.
2019-02-10 02:31:57 -08:00
fn crc_accum(a: u32, _: u32) -> u32
2019-02-08 21:08:53 -08:00
{
2019-02-08 21:53:27 -08:00
if a & 1 == 1 {
2019-02-13 21:19:36 -08:00
0xEDB8_8320 ^ a >> 1
2019-02-08 21:53:27 -08:00
} else {
a >> 1
}
2019-02-08 21:08:53 -08:00
}
fn crc_init() -> [u32; 256]
{
let mut t = [0; 256];
2019-02-13 21:19:36 -08:00
for (n, v) in t.iter_mut().enumerate() {
*v = (0..8).fold(n as u32, crc_accum);
2019-02-08 21:53:27 -08:00
}
2019-02-08 21:08:53 -08:00
t
}
pub fn crc32(b: &[u8], s: u32) -> u32
{
let t = crc_init();
2019-02-08 21:53:27 -08:00
!b.iter()
2019-02-13 21:19:36 -08:00
.fold(s, |a, &o| a >> 8 ^ t[(a & 0xFF ^ u32::from(o)) as usize])
2019-02-08 21:08:53 -08:00
}
#[test]
fn crc32_lorem_ipsum()
{
assert_eq!(crc32(b"Lorem ipsum dolor sit amet", !0), 0x5F29D461);
}
// EOF