forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

crc.rs60 lines, 2.0 KiBHistoryRawDownload
1//! The Ogg page checksum.
2//!
3//! CRC-32 with the Ethernet polynomial `0x04c11db7`, but — unlike almost every
4//! other CRC-32 in use — with no bit reflection, no initial value and no final
5//! inversion. Feeding a byte stream through the reflected variant every other
6//! format uses is the classic way to produce pages a real player rejects, so
7//! this is its own small module with its own table.
8
9/// Bit-per-bit table for the unreflected polynomial.
10const fn build_table() -> [u32; 256] {
11 let mut table = [0u32; 256];
12 let mut i = 0;
13 while i < 256 {
14 let mut r = (i as u32) << 24;
15 let mut bit = 0;
16 while bit < 8 {
17 r = match r & 0x8000_0000 {
18 0 => r << 1,
19 _ => (r << 1) ^ 0x04c1_1db7,
20 };
21 bit += 1;
22 }
23 table[i] = r;
24 i += 1;
25 }
26 table
27}
28
29static TABLE: [u32; 256] = build_table();
30
31/// Checksum of `chunks` concatenated — the page header (with its checksum field
32/// zeroed) followed by the page body.
33pub fn crc32(chunks: &[&[u8]]) -> u32 {
34 let mut crc = 0u32;
35 for chunk in chunks {
36 for &byte in *chunk {
37 crc = (crc << 8) ^ TABLE[(((crc >> 24) as u8) ^ byte) as usize];
38 }
39 }
40 crc
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn matches_known_vectors() {
49 // Nothing checksums to zero, and the catalogue check value for this
50 // variant (poly 04C11DB7, init 0, no reflection, no final xor) is
51 // 0x89a1897f over the ASCII digits — the value that separates it from
52 // the reflected CRC-32 every zip file uses.
53 assert_eq!(crc32(&[]), 0);
54 assert_eq!(crc32(&[b"123456789"]), 0x89a1_897f);
55 // Chunking must not change the answer — the muxer feeds header and body
56 // as two slices, the demuxer as three.
57 let all = b"OggS\x00\x02longer body bytes";
58 assert_eq!(crc32(&[all]), crc32(&[&all[..4], &all[4..7], &all[7..]]));
59 }
60}