forked from trifectatechfoundation/zlib-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
First part of issue trifectatechfoundation#14
Add a naive implementation of CRC-32 based on the C code from the PNG specification.
- Loading branch information
Showing
3 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
use std::sync::Once; | ||
|
||
const LSB_POLY: u32 = 0xedb8_8320u32; | ||
const START_CHECKSUM: u32 = 0xffff_ffffu32; | ||
const FINAL_XOR: u32 = 0xffff_ffffu32; | ||
|
||
// This could be auto-generated | ||
static mut CRC_TABLE: [u32; 256] = [0; 256]; | ||
static CRC_TABLE_ONCE: Once = Once::new(); | ||
|
||
fn get_crc_table() -> &'static [u32] { | ||
CRC_TABLE_ONCE.call_once(|| { | ||
for i in 0..256u16 { | ||
let mut c = u32::from(i); | ||
for k in 0..8 { | ||
if c & 1 != 0 { | ||
c = LSB_POLY ^ (c >> 1); | ||
} else { | ||
c >>= 1; | ||
} | ||
} | ||
unsafe { CRC_TABLE[usize::from(i)] = c; } | ||
} | ||
}); | ||
unsafe { &CRC_TABLE[..] } | ||
} | ||
|
||
fn naive_crc32(data: &[u8]) -> u32 { | ||
let crc_table = get_crc_table(); | ||
let crc = data.iter().fold(START_CHECKSUM, |crc, val| { | ||
let i = (crc as u8) ^ *val; | ||
crc_table[usize::from(i)] ^ (crc >> 8) | ||
}); | ||
crc ^ FINAL_XOR | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use super::*; | ||
|
||
quickcheck::quickcheck! { | ||
fn naive_is_crc32fast(v: Vec<u8>) -> bool { | ||
naive_crc32(&v[..]) == crc32fast::hash(&v[..]) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
mod adler32; | ||
mod crc32; | ||
pub mod allocate; | ||
pub mod c_api; | ||
pub mod deflate; | ||
|