coip-format 0.2.0

Core binary format definitions, schema, varint, CRC32C, and wire codecs for COI (.coi) columnar IP databases
Documentation
use alloc::vec::Vec;

use crate::{Cursor, FormatError, crc32c};

pub const MAGIC_HEADER: [u8; 4] = *b"COI\0";
pub const MAGIC_FOOTER: [u8; 4] = *b"COI\xFF";
pub const FORMAT_MAJOR: u16 = 1;
pub const FORMAT_MINOR: u16 = 0;
pub const HEADER_SIZE: usize = 64;
pub const SECTION_ENTRY_SIZE: usize = 32;
pub const FOOTER_SIZE: usize = 16;
pub const SECTION_ALIGN: u64 = 8;

/// Bitmask flags stored in `FileHeader.flags`.
pub mod header_flags {
    pub const HAS_IPV4: u32 = 0x01;
    pub const HAS_IPV6: u32 = 0x02;
    pub const HAS_IPV6_HOST_EXT: u32 = 0x04;
    pub const HAS_ZSTD_DICTS: u32 = 0x08;
}

/// Compression codec identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Codec {
    None = 0,
    Zstd = 1,
    Lz4 = 2,
    BitPack = 3,
}

impl Codec {
    #[inline]
    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
        match v {
            0 => Ok(Self::None),
            1 => Ok(Self::Zstd),
            2 => Ok(Self::Lz4),
            3 => Ok(Self::BitPack),
            _ => Err(FormatError::InvalidCodec(v)),
        }
    }
}

/// Section kind identifier in the Section Directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
pub enum SectionKind {
    Metadata = 1,
    Schema = 2,
    ZstdDicts = 3,
    Ipv6Aliases = 4,
    Ipv4Index = 5,
    Ipv6Index = 6,
    Ipv6HostExt = 7,
    RecordColumns = 8,
    DictTables = 9,
}

impl SectionKind {
    #[inline]
    pub fn from_u16(v: u16) -> Result<Self, FormatError> {
        match v {
            1 => Ok(Self::Metadata),
            2 => Ok(Self::Schema),
            3 => Ok(Self::ZstdDicts),
            4 => Ok(Self::Ipv6Aliases),
            5 => Ok(Self::Ipv4Index),
            6 => Ok(Self::Ipv6Index),
            7 => Ok(Self::Ipv6HostExt),
            8 => Ok(Self::RecordColumns),
            9 => Ok(Self::DictTables),
            _ => Err(FormatError::InvalidSectionKind(v)),
        }
    }

    pub const fn name(self) -> &'static str {
        match self {
            Self::Metadata => "Metadata",
            Self::Schema => "Schema",
            Self::ZstdDicts => "ZstdDicts",
            Self::Ipv6Aliases => "Ipv6Aliases",
            Self::Ipv4Index => "Ipv4Index",
            Self::Ipv6Index => "Ipv6Index",
            Self::Ipv6HostExt => "Ipv6HostExt",
            Self::RecordColumns => "RecordColumns",
            Self::DictTables => "DictTables",
        }
    }
}

/// Fixed 64-byte COI file header at offset 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileHeader {
    pub format_major: u16,
    pub format_minor: u16,
    pub flags: u32,
    pub profile_codec: Codec,
    pub section_count: u8,
    pub header_ext_len: u16,
    pub build_epoch: u64,
    pub record_count: u64,
    pub section_dir_offset: u64,
    pub file_size: u64,
    pub header_crc32c: u32,
}

impl FileHeader {
    pub fn encode(&self) -> [u8; HEADER_SIZE] {
        let mut out = [0u8; HEADER_SIZE];
        out[0..4].copy_from_slice(&MAGIC_HEADER);
        out[4..6].copy_from_slice(&self.format_major.to_le_bytes());
        out[6..8].copy_from_slice(&self.format_minor.to_le_bytes());
        out[8..12].copy_from_slice(&self.flags.to_le_bytes());
        out[12] = self.profile_codec as u8;
        out[13] = self.section_count;
        out[14..16].copy_from_slice(&self.header_ext_len.to_le_bytes());
        out[16..24].copy_from_slice(&self.build_epoch.to_le_bytes());
        out[24..32].copy_from_slice(&self.record_count.to_le_bytes());
        out[32..40].copy_from_slice(&self.section_dir_offset.to_le_bytes());
        out[40..48].copy_from_slice(&self.file_size.to_le_bytes());
        let crc = crc32c(&out[0..48]);
        out[48..52].copy_from_slice(&crc.to_le_bytes());
        out
    }

    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
        if buf.len() < HEADER_SIZE {
            return Err(FormatError::UnexpectedEof);
        }
        let mut c = Cursor::new(&buf[..HEADER_SIZE]);
        let magic = c.read_array::<4>()?;
        if magic != MAGIC_HEADER {
            return Err(FormatError::InvalidMagic);
        }
        let format_major = c.read_u16()?;
        let format_minor = c.read_u16()?;
        if format_major != FORMAT_MAJOR {
            return Err(FormatError::UnsupportedVersion {
                major: format_major,
                minor: format_minor,
            });
        }
        let flags = c.read_u32()?;
        let profile_codec = Codec::from_u8(c.read_u8()?)?;
        let section_count = c.read_u8()?;
        let header_ext_len = c.read_u16()?;
        let build_epoch = c.read_u64()?;
        let record_count = c.read_u64()?;
        let section_dir_offset = c.read_u64()?;
        let file_size = c.read_u64()?;
        let header_crc32c = c.read_u32()?;
        let actual_crc = crc32c(&buf[0..48]);
        if header_crc32c != actual_crc {
            return Err(FormatError::InvalidCrc {
                expected: header_crc32c,
                actual: actual_crc,
            });
        }
        Ok(Self {
            format_major,
            format_minor,
            flags,
            profile_codec,
            section_count,
            header_ext_len,
            build_epoch,
            record_count,
            section_dir_offset,
            file_size,
            header_crc32c,
        })
    }

    #[inline]
    pub const fn has_ipv4(&self) -> bool {
        (self.flags & header_flags::HAS_IPV4) != 0
    }

    #[inline]
    pub const fn has_ipv6(&self) -> bool {
        (self.flags & header_flags::HAS_IPV6) != 0
    }

    #[inline]
    pub const fn has_ipv6_host_ext(&self) -> bool {
        (self.flags & header_flags::HAS_IPV6_HOST_EXT) != 0
    }

    #[inline]
    pub const fn has_zstd_dicts(&self) -> bool {
        (self.flags & header_flags::HAS_ZSTD_DICTS) != 0
    }
}

/// 32-byte entry in the Section Directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SectionEntry {
    pub kind: SectionKind,
    pub flags: u16,
    pub crc32c: u32,
    pub offset: u64,
    pub length: u64,
    pub uncompressed_length: u64,
}

impl SectionEntry {
    #[inline]
    pub fn codec(&self) -> Result<Codec, FormatError> {
        Codec::from_u8((self.flags & 0x0F) as u8)
    }

    pub fn encode(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&(self.kind as u16).to_le_bytes());
        out.extend_from_slice(&self.flags.to_le_bytes());
        out.extend_from_slice(&self.crc32c.to_le_bytes());
        out.extend_from_slice(&self.offset.to_le_bytes());
        out.extend_from_slice(&self.length.to_le_bytes());
        out.extend_from_slice(&self.uncompressed_length.to_le_bytes());
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let kind = SectionKind::from_u16(c.read_u16()?)?;
        let flags = c.read_u16()?;
        let _ = Codec::from_u8((flags & 0x0F) as u8)?;
        let crc32c = c.read_u32()?;
        let offset = c.read_u64()?;
        if offset % SECTION_ALIGN != 0 {
            return Err(FormatError::InvalidAlignment { offset });
        }
        let length = c.read_u64()?;
        let uncompressed_length = c.read_u64()?;
        Ok(Self {
            kind,
            flags,
            crc32c,
            offset,
            length,
            uncompressed_length,
        })
    }
}

/// Fixed 16-byte COI file footer at `file_size - 16`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileFooter {
    pub dir_crc32c: u32,
    pub section_dir_offset: u64,
}

impl FileFooter {
    pub fn encode(&self) -> [u8; FOOTER_SIZE] {
        let mut out = [0u8; FOOTER_SIZE];
        out[0..4].copy_from_slice(&self.dir_crc32c.to_le_bytes());
        out[4..12].copy_from_slice(&self.section_dir_offset.to_le_bytes());
        out[12..16].copy_from_slice(&MAGIC_FOOTER);
        out
    }

    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
        if buf.len() < FOOTER_SIZE {
            return Err(FormatError::UnexpectedEof);
        }
        let mut c = Cursor::new(&buf[..FOOTER_SIZE]);
        let dir_crc32c = c.read_u32()?;
        let section_dir_offset = c.read_u64()?;
        let magic_end = c.read_array::<4>()?;
        if magic_end != MAGIC_FOOTER {
            return Err(FormatError::InvalidMagic);
        }
        Ok(Self {
            dir_crc32c,
            section_dir_offset,
        })
    }
}

/// Align an offset up to the next multiple of 8 bytes.
#[inline]
pub const fn align8(offset: u64) -> u64 {
    (offset + (SECTION_ALIGN - 1)) & !(SECTION_ALIGN - 1)
}