coip-format 0.1.0

Core binary format definitions, schema, varint, CRC32C, and wire codecs for COI (.coi) columnar IP databases
Documentation
//! Pure-Rust CRC32C (Castagnoli) using slicing-by-4 lookup tables (`no_std`).

const POLY: u32 = 0x82F6_3B78;

const fn make_tables() -> [[u32; 256]; 4] {
    let mut tables = [[0u32; 256]; 4];
    let mut i = 0;
    while i < 256 {
        let mut crc = i as u32;
        let mut j = 0;
        while j < 8 {
            if (crc & 1) != 0 {
                crc = (crc >> 1) ^ POLY;
            } else {
                crc >>= 1;
            }
            j += 1;
        }
        tables[0][i] = crc;
        i += 1;
    }

    let mut t = 1;
    while t < 4 {
        let mut k = 0;
        while k < 256 {
            let prev = tables[t - 1][k];
            tables[t][k] = tables[0][(prev & 0xFF) as usize] ^ (prev >> 8);
            k += 1;
        }
        t += 1;
    }
    tables
}

static TABLES: [[u32; 256]; 4] = make_tables();

/// Compute CRC32C (Castagnoli) over `data`.
#[inline]
pub fn crc32c(data: &[u8]) -> u32 {
    crc32c_append(0, data)
}

/// Continue CRC32C computation with an existing checksum.
pub fn crc32c_append(crc: u32, data: &[u8]) -> u32 {
    let mut c = !crc;
    let mut chunks = data.chunks_exact(4);
    for chunk in &mut chunks {
        let word = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) ^ c;
        c = TABLES[3][(word & 0xFF) as usize]
            ^ TABLES[2][((word >> 8) & 0xFF) as usize]
            ^ TABLES[1][((word >> 16) & 0xFF) as usize]
            ^ TABLES[0][((word >> 24) & 0xFF) as usize];
    }
    for &b in chunks.remainder() {
        c = TABLES[0][((c ^ (b as u32)) & 0xFF) as usize] ^ (c >> 8);
    }
    !c
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_crc32c_standard_check_value() {
        assert_eq!(crc32c(b"123456789"), 0xE306_9283);
        assert_eq!(crc32c(b""), 0x0000_0000);
        assert_eq!(crc32c_append(crc32c(b"1234"), b"56789"), 0xE306_9283);
    }
}