coip-reader 0.2.0

High-performance read-only reader for COI (.coi) columnar IP databases with projection, LRU caching, and serde support
Documentation
//! High-performance, thread-safe read-only reader for COI (`.coi`) v1.0 columnar IP databases.
//!
//! # Features
//!
//! - `mmap` *(default)*: zero-copy memory-mapped file opening via [`Reader::open`]
//! - `serde` *(default)*: direct zero-intermediate-allocation streaming deserialization via
//!   [`Reader::lookup`] and [`Reader::lookup_with_projection`]
//! - `zstd-c` *(optional)*: switch from pure-Rust `ruzstd` to C `libzstd` for maximum cold throughput
//!
//! # Example
//!
//! ```
//! use std::collections::BTreeMap;
//! use std::net::{IpAddr, Ipv4Addr};
//! use coip_builder::{BuildOptions, CoipBuilder};
//! use coip_reader::{Reader, Value};
//!
//! let mut builder = CoipBuilder::new(BuildOptions::compact());
//! let mut rec = BTreeMap::new();
//! rec.insert("iso_code".into(), Value::Utf8("US".into()));
//! rec.insert("asn".into(), Value::U32(15169));
//! builder.insert_ipv4_cidr(Ipv4Addr::new(8, 8, 8, 0), 24, rec).unwrap();
//! let (bytes, _) = builder.build().unwrap();
//!
//! let reader = Reader::from_bytes(&bytes).unwrap();
//! let proj = reader.compile_projection(["iso_code"]).unwrap();
//! let hit = reader
//!     .lookup_projected(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), &proj)
//!     .unwrap()
//!     .unwrap();
//! assert_eq!(hit.as_map().unwrap().get("iso_code"), Some(&Value::Utf8("US".into())));
//! assert!(!hit.as_map().unwrap().contains_key("asn"));
//! ```

pub mod cache;
pub mod codec;
pub mod error;
pub mod index_reader;
pub mod projection;
pub mod reader;
#[cfg(feature = "serde")]
pub mod serde_de;
pub mod source;
pub mod table_reader;

pub use coip_format::{FileHeader, Schema, SectionEntry, SectionKind, Value};
pub use error::{ReaderError, Result};
pub use projection::Projection;
pub use reader::{Reader, ReaderOptions};

#[cfg(test)]
mod tests {
    use super::*;
    use coip_builder::{BuildOptions, CoipBuilder};
    use coip_format::AliasRule;
    use std::collections::BTreeMap;
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

    fn make_rec(
        country: Option<&str>,
        lat: Option<f64>,
        lon: Option<f64>,
        is_anycast: Option<bool>,
        en_city: Option<&str>,
        zh_city: Option<&str>,
    ) -> BTreeMap<String, Value> {
        let mut root = BTreeMap::new();
        if let Some(iso) = country {
            let mut c = BTreeMap::new();
            c.insert("iso_code".into(), Value::Utf8(iso.into()));
            c.insert("geoname_id".into(), Value::U32(6252001));
            c.insert("is_in_european_union".into(), Value::Bool(false));
            let mut names = BTreeMap::new();
            names.insert("en".into(), Value::Utf8(format!("Country-{iso}")));
            names.insert("zh-CN".into(), Value::Utf8(format!("国家-{iso}")));
            names.insert("de".into(), Value::Utf8(format!("Land-{iso}")));
            names.insert("ja".into(), Value::Utf8(format!("国-{iso}")));
            c.insert("names".into(), Value::Map(names));
            root.insert("country".into(), Value::Map(c));
        }
        if lat.is_some() || lon.is_some() {
            let mut loc = BTreeMap::new();
            if let Some(la) = lat {
                loc.insert("latitude".into(), Value::F64(la));
            }
            if let Some(lo) = lon {
                loc.insert("longitude".into(), Value::F64(lo));
            }
            loc.insert("accuracy_radius".into(), Value::U16(20));
            loc.insert(
                "time_zone".into(),
                Value::Utf8("America/Los_Angeles".into()),
            );
            root.insert("location".into(), Value::Map(loc));
        }
        if let Some(any) = is_anycast {
            let mut t = BTreeMap::new();
            t.insert("is_anycast".into(), Value::Bool(any));
            root.insert("traits".into(), Value::Map(t));
        }
        if en_city.is_some() || zh_city.is_some() {
            let mut city = BTreeMap::new();
            let mut names = BTreeMap::new();
            if let Some(en) = en_city {
                names.insert("en".into(), Value::Utf8(en.into()));
            }
            if let Some(zh) = zh_city {
                names.insert("zh-CN".into(), Value::Utf8(zh.into()));
            }
            names.insert("fr".into(), Value::Utf8("Ville".into()));
            names.insert("de".into(), Value::Utf8("Stadt".into()));
            city.insert("names".into(), Value::Map(names));
            city.insert("geoname_id".into(), Value::U32(5375480));
            root.insert("city".into(), Value::Map(city));
        }
        root
    }

    #[test]
    fn test_full_roundtrip_projection_aliases_and_serde() {
        let mut builder = CoipBuilder::new(BuildOptions::default());
        builder.set_build_epoch(1_750_000_000);
        builder.set_metadata_field("database_type", serde_json::json!("Test-City"));

        // Add IPv4-mapped alias ::ffff:0:0/96
        builder.add_ipv6_alias(AliasRule {
            prefix: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0],
            prefix_len: 96,
            v4_bit_offset: 96,
        });

        // Insert 30 IPv4 networks to trigger dict normalization & DictGroup
        let rec_anycast = make_rec(None, None, None, Some(true), None, None);
        builder
            .insert_ipv4_cidr(Ipv4Addr::new(1, 1, 1, 0), 24, rec_anycast.clone())
            .unwrap();

        let rec_exact = make_rec(
            Some("US"),
            Some(37.7510123),
            Some(-122.4194155),
            Some(false),
            Some("Mountain View"),
            Some("山景城"),
        );
        builder
            .insert_ipv4_cidr(Ipv4Addr::new(8, 8, 8, 0), 24, rec_exact.clone())
            .unwrap();

        for i in 10u8..40 {
            let r = make_rec(
                Some(if i % 2 == 0 { "US" } else { "JP" }),
                Some(37.7510123),
                Some(-122.4194155),
                None,
                Some("Mountain View"),
                Some("山景城"),
            );
            builder
                .insert_ipv4_cidr(Ipv4Addr::new(10, i, 0, 0), 16, r)
                .unwrap();
        }

        // Native IPv6 /48 and fine-grained /128 host ext
        builder
            .insert_ipv6_cidr(
                "2606:4700::".parse::<Ipv6Addr>().unwrap(),
                48,
                rec_anycast.clone(),
            )
            .unwrap();
        builder
            .insert_ipv6_cidr(
                "2001:db8::1".parse::<Ipv6Addr>().unwrap(),
                128,
                rec_exact.clone(),
            )
            .unwrap();

        let (bytes, stats) = builder.build().unwrap();
        assert!(stats.record_count >= 3);

        let reader = Reader::from_bytes(&bytes).unwrap();
        reader.verify_checksums().unwrap();

        // 1. Exact bit-for-bit equality check including None vs false and 7-decimal f64
        assert_eq!(
            reader
                .lookup_value(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 1)))
                .unwrap(),
            None
        );
        assert_eq!(
            reader
                .lookup_value(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)))
                .unwrap(),
            Some(Value::Map(rec_anycast.clone()))
        );
        assert_eq!(
            reader
                .lookup_value(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)))
                .unwrap(),
            Some(Value::Map(rec_exact.clone()))
        );
        assert_eq!(
            reader
                .lookup_value(IpAddr::V4(Ipv4Addr::new(8, 8, 9, 1)))
                .unwrap(),
            None
        );

        // 2. IPv6 alias ::ffff:8.8.8.8 -> matches 8.8.8.8
        assert_eq!(
            reader
                .lookup_value(IpAddr::V6("::ffff:8.8.8.8".parse().unwrap()))
                .unwrap(),
            Some(Value::Map(rec_exact.clone()))
        );

        // 3. Native IPv6 + > /64 host ext
        assert_eq!(
            reader
                .lookup_value(IpAddr::V6("2606:4700::1111".parse().unwrap()))
                .unwrap(),
            Some(Value::Map(rec_anycast))
        );
        assert_eq!(
            reader
                .lookup_value(IpAddr::V6("2001:db8::1".parse().unwrap()))
                .unwrap(),
            Some(Value::Map(rec_exact))
        );
        assert_eq!(
            reader
                .lookup_value(IpAddr::V6("2001:db8::2".parse().unwrap()))
                .unwrap(),
            None
        );

        // 4. Column Projection (only country.iso_code, location.latitude, city.names.zh-CN)
        let proj = reader
            .compile_projection(["country.iso_code", "location.latitude", "city.names.zh-CN"])
            .unwrap();
        let projected = reader
            .lookup_projected(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), &proj)
            .unwrap()
            .unwrap();
        let pmap = projected.as_map().unwrap();
        assert_eq!(pmap.len(), 3);
        assert_eq!(
            pmap["country"].as_map().unwrap().get("iso_code"),
            Some(&Value::Utf8("US".into()))
        );
        assert!(!pmap["country"].as_map().unwrap().contains_key("geoname_id"));
        assert_eq!(
            pmap["location"].as_map().unwrap().get("latitude"),
            Some(&Value::F64(37.7510123))
        );
        assert!(!pmap["location"].as_map().unwrap().contains_key("longitude"));
        assert_eq!(
            pmap["city"].as_map().unwrap()["names"]
                .as_map()
                .unwrap()
                .len(),
            1
        );
        assert_eq!(
            pmap["city"].as_map().unwrap()["names"]
                .as_map()
                .unwrap()
                .get("zh-CN"),
            Some(&Value::Utf8("山景城".into()))
        );

        // 5. Typed serde deserialization with projection
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct FastGeo {
            country: Option<CountryIso>,
            location: Option<LatOnly>,
        }
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct CountryIso {
            iso_code: Option<String>,
        }
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct LatOnly {
            latitude: Option<f64>,
        }
        let typed: FastGeo = reader
            .lookup_with_projection(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), &proj)
            .unwrap()
            .unwrap();
        assert_eq!(
            typed,
            FastGeo {
                country: Some(CountryIso {
                    iso_code: Some("US".into())
                }),
                location: Some(LatOnly {
                    latitude: Some(37.7510123)
                })
            }
        );
    }
}