const TBLS : uint = 8;
pub type CrcTable = [[u32; 0x100]; TBLS];
pub fn make_crc_table() -> CrcTable
{
let p : [u8; 14] = [0,1,2,4,5,7,8,10,11,12,16,22,23,26];
let mut poly : u32 = 0;
for term in p.iter() {
poly |= 1u32 << (31 - *term as uint);
}
let mut crc_table : [[u32; 0x100]; TBLS] = [[0; 0x100]; TBLS];
for n in range(0, 0x100) {
let mut c = n as u32;
for _ in range(0u, 8u) {
c = if (c & 1) != 0 { poly ^ (c >> 1) } else { c >> 1 }
}
crc_table[0][n] = c;
}
for n in range(0, 0x100) {
let mut c : u32 = crc_table[0][n];
crc_table[4][n] = zswap32(c);
for k in range(1, 3) {
c = crc_table[0][c as uint & 0xff] ^ (c >> 8);
crc_table[k][n] = c;
crc_table[k + 4][n] = zswap32(c);
}
}
crc_table
}
pub fn zswap32(n: u32) -> u32
{
(n << 24) | ((n << 8) & 0x00ff0000u32) | ((n >> 8) & 0x0000ff00u32) | ((n >> 24) & 0x000000ffu32) }
pub fn write_tables(crc_table: &CrcTable) -> String
{
let mut s : String = String::new();
let tt = crc_table;
s.push_str("/* crc32tables.rs -- tables for rapid CRC calculation\n");
s.push_str(" * Generated automatically by crc32gen.rs\n */\n\n");
s.push_str("pub static CRC_TABLE:[[u32; 0x100]; 8] = [\n [\n");
write_table(&mut s, &tt[0]);
s.push_str("// #ifdef BYFOUR\n");
for k in range(1, 8) {
s.push_str(" ],\n [\n");
write_table(&mut s, &tt[k]);
}
s.push_str("// #endif\n");
s.push_str(" ]\n];\n");
s
}
fn write_table(s: &mut String, table: &[u32; 0x100]) {
for n in range(0, 0x100) {
let line = format!("{}0x{:08x}{}", if n % 5 != 0 { "" } else { " " },
table[n],
if n == 255 { "\n" } else if n % 5 == 4 { ",\n" } else { ", " });
s.push_str(line.as_slice());
}
}