coip-format 0.2.0

Core binary format definitions, schema, varint, CRC32C, and wire codecs for COI (.coi) columnar IP databases
Documentation
//! Core binary format primitives for COI (`.coi`) v1.0 columnar IP databases.
//!
//! `coip-format` is `no_std` + `alloc` compatible and defines:
//! - Fixed [`FileHeader`], [`SectionEntry`], and [`FileFooter`] layouts with Castagnoli [`crc32c()`]
//! - Self-describing 6-primitive [`Schema`] (`Primitive`, `DictRef`, `Struct`, `ShreddedMap`, `List`, `Dynamic`)
//! - IPv4 / IPv6 index metadata ([`IndexHeader`], [`RidMode`], [`Ipv6Aliases`], [`Ipv6HostExt`], [`ZstdDicts`])
//! - Columnar table and dictionary headers ([`ColumnTableHeader`], [`ChunkHeader`], [`FlatDictHeader`], [`ListDictHeader`])
//! - Lossless dynamic [`Value`] wire encoding, LEB128/ZigZag varints, and CIDR range decomposition
//!
//! # Example
//!
//! ```
//! use coip_format::{Codec, FileHeader, FORMAT_MAJOR, FORMAT_MINOR, HEADER_SIZE, header_flags};
//!
//! let hdr = FileHeader {
//!     format_major: FORMAT_MAJOR,
//!     format_minor: FORMAT_MINOR,
//!     flags: header_flags::HAS_IPV4,
//!     profile_codec: Codec::Zstd,
//!     section_count: 5,
//!     header_ext_len: 0,
//!     build_epoch: 1_750_000_000,
//!     record_count: 1024,
//!     section_dir_offset: HEADER_SIZE as u64,
//!     file_size: 4096,
//!     header_crc32c: 0,
//! };
//! let bytes = hdr.encode();
//! let decoded = FileHeader::decode(&bytes).unwrap();
//! assert_eq!(decoded.record_count, 1024);
//! assert!(decoded.has_ipv4());
//! ```

#![no_std]

extern crate alloc;
#[cfg(feature = "std")]
extern crate std;

pub mod column;
pub mod crc32c;
pub mod error;
pub mod header;
pub mod index;
pub mod schema;
pub mod value;
pub mod varint;

pub use column::{
    COLUMN_TABLE_HEADER_SIZE, ChunkHeader, ColumnTableHeader, EncMode, FLAT_DICT_HEADER_SIZE,
    FlatDictHeader, LIST_DICT_HEADER_SIZE, ListDictHeader, NullMode,
};
pub use crc32c::{crc32c, crc32c_append};
pub use error::FormatError;
pub use header::{
    Codec, FOOTER_SIZE, FORMAT_MAJOR, FORMAT_MINOR, FileFooter, FileHeader, HEADER_SIZE,
    MAGIC_FOOTER, MAGIC_HEADER, SECTION_ALIGN, SECTION_ENTRY_SIZE, SectionEntry, SectionKind,
    align8, header_flags,
};
pub use index::{
    ALIAS_RULE_SIZE, AliasRule, HOST_EXT_ENTRY_SIZE, HostExtEntry, INDEX_HEADER_SIZE, IndexHeader,
    Ipv6Aliases, Ipv6HostExt, NO_ZSTD_DICT, RidMode, ZstdDicts, range_to_cidrs_v4,
    range_to_cidrs_v6,
};
pub use schema::{
    ColumnType, DictGroup, DictKind, DictSchema, IdWidth, PType, PhysicalColKind, SCHEMA_VERSION,
    Schema, ShreddedMapEntry, StructField, StructSchema, TableSchema,
};
pub use value::Value;
pub use varint::{
    Cursor, read_svarint, read_uvarint, write_string, write_svarint, write_uvarint, zigzag_decode,
    zigzag_encode,
};

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::String;
    use alloc::vec;

    #[test]
    fn test_header_footer_schema_roundtrip() {
        let hdr = FileHeader {
            format_major: FORMAT_MAJOR,
            format_minor: FORMAT_MINOR,
            flags: header_flags::HAS_IPV4 | header_flags::HAS_IPV6,
            profile_codec: Codec::Zstd,
            section_count: 5,
            header_ext_len: 0,
            build_epoch: 1_700_000_000,
            record_count: 672_963,
            section_dir_offset: HEADER_SIZE as u64,
            file_size: 20_000_000,
            header_crc32c: 0,
        };
        let raw = hdr.encode();
        let decoded = FileHeader::decode(&raw).unwrap();
        assert_eq!(decoded.record_count, 672_963);
        assert!(decoded.has_ipv4());
        assert!(decoded.has_ipv6());
        assert!(!decoded.has_ipv6_host_ext());

        let footer = FileFooter {
            dir_crc32c: 0x1234_5678,
            section_dir_offset: 64,
        };
        let fraw = footer.encode();
        assert_eq!(FileFooter::decode(&fraw).unwrap(), footer);

        let schema = Schema {
            dicts: vec![
                DictSchema {
                    name: String::from("coords"),
                    kind: DictKind::Struct {
                        table: TableSchema {
                            column_count: 2,
                            root: StructSchema {
                                nullable: false,
                                presence_col: None,
                                fields: vec![
                                    StructField {
                                        name: String::from("latitude"),
                                        col_type: ColumnType::Primitive {
                                            ptype: PType::F64,
                                            nullable: true,
                                            col_id: 0,
                                        },
                                    },
                                    StructField {
                                        name: String::from("longitude"),
                                        col_type: ColumnType::Primitive {
                                            ptype: PType::F64,
                                            nullable: true,
                                            col_id: 1,
                                        },
                                    },
                                ],
                                dict_groups: vec![],
                            },
                        },
                    },
                },
                DictSchema {
                    name: String::from("tz"),
                    kind: DictKind::Flat {
                        ptype: PType::Utf8,
                        sorted_front_coded: false,
                        block_size: 0,
                    },
                },
            ],
            root: TableSchema {
                column_count: 2,
                root: StructSchema {
                    nullable: false,
                    presence_col: None,
                    fields: vec![StructField {
                        name: String::from("location"),
                        col_type: ColumnType::Struct(StructSchema {
                            nullable: true,
                            presence_col: None,
                            fields: vec![StructField {
                                name: String::from("time_zone"),
                                col_type: ColumnType::DictRef {
                                    dict_id: 1,
                                    id_width: IdWidth::U16,
                                    nullable: true,
                                    col_id: 0,
                                },
                            }],
                            dict_groups: vec![DictGroup {
                                dict_id: 0,
                                id_width: IdWidth::U32,
                                col_id: 1,
                                field_names: vec![
                                    String::from("latitude"),
                                    String::from("longitude"),
                                ],
                            }],
                        }),
                    }],
                    dict_groups: vec![],
                },
            },
        };
        let sbytes = schema.encode();
        let sdec = Schema::decode(&sbytes).unwrap();
        assert_eq!(sdec, schema);
    }
}