Skip to main content

coip_reader/
lib.rs

1//! High-performance, thread-safe read-only reader for COI (`.coi`) v1.0 columnar IP databases.
2//!
3//! # Features
4//!
5//! - `mmap` *(default)*: zero-copy memory-mapped file opening via [`Reader::open`]
6//! - `serde` *(default)*: direct zero-intermediate-allocation streaming deserialization via
7//!   [`Reader::lookup`] and [`Reader::lookup_with_projection`]
8//! - `zstd-c` *(optional)*: switch from pure-Rust `ruzstd` to C `libzstd` for maximum cold throughput
9//!
10//! # Example
11//!
12//! ```
13//! use std::collections::BTreeMap;
14//! use std::net::{IpAddr, Ipv4Addr};
15//! use coip_builder::{BuildOptions, CoipBuilder};
16//! use coip_reader::{Reader, Value};
17//!
18//! let mut builder = CoipBuilder::new(BuildOptions::compact());
19//! let mut rec = BTreeMap::new();
20//! rec.insert("iso_code".into(), Value::Utf8("US".into()));
21//! rec.insert("asn".into(), Value::U32(15169));
22//! builder.insert_ipv4_cidr(Ipv4Addr::new(8, 8, 8, 0), 24, rec).unwrap();
23//! let (bytes, _) = builder.build().unwrap();
24//!
25//! let reader = Reader::from_bytes(&bytes).unwrap();
26//! let proj = reader.compile_projection(["iso_code"]).unwrap();
27//! let hit = reader
28//!     .lookup_projected(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), &proj)
29//!     .unwrap()
30//!     .unwrap();
31//! assert_eq!(hit.as_map().unwrap().get("iso_code"), Some(&Value::Utf8("US".into())));
32//! assert!(!hit.as_map().unwrap().contains_key("asn"));
33//! ```
34
35pub mod cache;
36pub mod codec;
37pub mod error;
38pub mod index_reader;
39pub mod projection;
40pub mod reader;
41#[cfg(feature = "serde")]
42pub mod serde_de;
43pub mod source;
44pub mod table_reader;
45
46pub use coip_format::{FileHeader, Schema, SectionEntry, SectionKind, Value};
47pub use error::{ReaderError, Result};
48pub use projection::Projection;
49pub use reader::{Reader, ReaderOptions};
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use coip_builder::{BuildOptions, CoipBuilder};
55    use coip_format::AliasRule;
56    use std::collections::BTreeMap;
57    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
58
59    fn make_rec(
60        country: Option<&str>,
61        lat: Option<f64>,
62        lon: Option<f64>,
63        is_anycast: Option<bool>,
64        en_city: Option<&str>,
65        zh_city: Option<&str>,
66    ) -> BTreeMap<String, Value> {
67        let mut root = BTreeMap::new();
68        if let Some(iso) = country {
69            let mut c = BTreeMap::new();
70            c.insert("iso_code".into(), Value::Utf8(iso.into()));
71            c.insert("geoname_id".into(), Value::U32(6252001));
72            c.insert("is_in_european_union".into(), Value::Bool(false));
73            let mut names = BTreeMap::new();
74            names.insert("en".into(), Value::Utf8(format!("Country-{iso}")));
75            names.insert("zh-CN".into(), Value::Utf8(format!("国家-{iso}")));
76            names.insert("de".into(), Value::Utf8(format!("Land-{iso}")));
77            names.insert("ja".into(), Value::Utf8(format!("国-{iso}")));
78            c.insert("names".into(), Value::Map(names));
79            root.insert("country".into(), Value::Map(c));
80        }
81        if lat.is_some() || lon.is_some() {
82            let mut loc = BTreeMap::new();
83            if let Some(la) = lat {
84                loc.insert("latitude".into(), Value::F64(la));
85            }
86            if let Some(lo) = lon {
87                loc.insert("longitude".into(), Value::F64(lo));
88            }
89            loc.insert("accuracy_radius".into(), Value::U16(20));
90            loc.insert(
91                "time_zone".into(),
92                Value::Utf8("America/Los_Angeles".into()),
93            );
94            root.insert("location".into(), Value::Map(loc));
95        }
96        if let Some(any) = is_anycast {
97            let mut t = BTreeMap::new();
98            t.insert("is_anycast".into(), Value::Bool(any));
99            root.insert("traits".into(), Value::Map(t));
100        }
101        if en_city.is_some() || zh_city.is_some() {
102            let mut city = BTreeMap::new();
103            let mut names = BTreeMap::new();
104            if let Some(en) = en_city {
105                names.insert("en".into(), Value::Utf8(en.into()));
106            }
107            if let Some(zh) = zh_city {
108                names.insert("zh-CN".into(), Value::Utf8(zh.into()));
109            }
110            names.insert("fr".into(), Value::Utf8("Ville".into()));
111            names.insert("de".into(), Value::Utf8("Stadt".into()));
112            city.insert("names".into(), Value::Map(names));
113            city.insert("geoname_id".into(), Value::U32(5375480));
114            root.insert("city".into(), Value::Map(city));
115        }
116        root
117    }
118
119    #[test]
120    fn test_full_roundtrip_projection_aliases_and_serde() {
121        let mut builder = CoipBuilder::new(BuildOptions::default());
122        builder.set_build_epoch(1_750_000_000);
123        builder.set_metadata_field("database_type", serde_json::json!("Test-City"));
124
125        // Add IPv4-mapped alias ::ffff:0:0/96
126        builder.add_ipv6_alias(AliasRule {
127            prefix: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0],
128            prefix_len: 96,
129            v4_bit_offset: 96,
130        });
131
132        // Insert 30 IPv4 networks to trigger dict normalization & DictGroup
133        let rec_anycast = make_rec(None, None, None, Some(true), None, None);
134        builder
135            .insert_ipv4_cidr(Ipv4Addr::new(1, 1, 1, 0), 24, rec_anycast.clone())
136            .unwrap();
137
138        let rec_exact = make_rec(
139            Some("US"),
140            Some(37.7510123),
141            Some(-122.4194155),
142            Some(false),
143            Some("Mountain View"),
144            Some("山景城"),
145        );
146        builder
147            .insert_ipv4_cidr(Ipv4Addr::new(8, 8, 8, 0), 24, rec_exact.clone())
148            .unwrap();
149
150        for i in 10u8..40 {
151            let r = make_rec(
152                Some(if i % 2 == 0 { "US" } else { "JP" }),
153                Some(37.7510123),
154                Some(-122.4194155),
155                None,
156                Some("Mountain View"),
157                Some("山景城"),
158            );
159            builder
160                .insert_ipv4_cidr(Ipv4Addr::new(10, i, 0, 0), 16, r)
161                .unwrap();
162        }
163
164        // Native IPv6 /48 and fine-grained /128 host ext
165        builder
166            .insert_ipv6_cidr(
167                "2606:4700::".parse::<Ipv6Addr>().unwrap(),
168                48,
169                rec_anycast.clone(),
170            )
171            .unwrap();
172        builder
173            .insert_ipv6_cidr(
174                "2001:db8::1".parse::<Ipv6Addr>().unwrap(),
175                128,
176                rec_exact.clone(),
177            )
178            .unwrap();
179
180        let (bytes, stats) = builder.build().unwrap();
181        assert!(stats.record_count >= 3);
182
183        let reader = Reader::from_bytes(&bytes).unwrap();
184        reader.verify_checksums().unwrap();
185
186        // 1. Exact bit-for-bit equality check including None vs false and 7-decimal f64
187        assert_eq!(
188            reader
189                .lookup_value(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 1)))
190                .unwrap(),
191            None
192        );
193        assert_eq!(
194            reader
195                .lookup_value(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)))
196                .unwrap(),
197            Some(Value::Map(rec_anycast.clone()))
198        );
199        assert_eq!(
200            reader
201                .lookup_value(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)))
202                .unwrap(),
203            Some(Value::Map(rec_exact.clone()))
204        );
205        assert_eq!(
206            reader
207                .lookup_value(IpAddr::V4(Ipv4Addr::new(8, 8, 9, 1)))
208                .unwrap(),
209            None
210        );
211
212        // 2. IPv6 alias ::ffff:8.8.8.8 -> matches 8.8.8.8
213        assert_eq!(
214            reader
215                .lookup_value(IpAddr::V6("::ffff:8.8.8.8".parse().unwrap()))
216                .unwrap(),
217            Some(Value::Map(rec_exact.clone()))
218        );
219
220        // 3. Native IPv6 + > /64 host ext
221        assert_eq!(
222            reader
223                .lookup_value(IpAddr::V6("2606:4700::1111".parse().unwrap()))
224                .unwrap(),
225            Some(Value::Map(rec_anycast))
226        );
227        assert_eq!(
228            reader
229                .lookup_value(IpAddr::V6("2001:db8::1".parse().unwrap()))
230                .unwrap(),
231            Some(Value::Map(rec_exact))
232        );
233        assert_eq!(
234            reader
235                .lookup_value(IpAddr::V6("2001:db8::2".parse().unwrap()))
236                .unwrap(),
237            None
238        );
239
240        // 4. Column Projection (only country.iso_code, location.latitude, city.names.zh-CN)
241        let proj = reader
242            .compile_projection(["country.iso_code", "location.latitude", "city.names.zh-CN"])
243            .unwrap();
244        let projected = reader
245            .lookup_projected(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), &proj)
246            .unwrap()
247            .unwrap();
248        let pmap = projected.as_map().unwrap();
249        assert_eq!(pmap.len(), 3);
250        assert_eq!(
251            pmap["country"].as_map().unwrap().get("iso_code"),
252            Some(&Value::Utf8("US".into()))
253        );
254        assert!(!pmap["country"].as_map().unwrap().contains_key("geoname_id"));
255        assert_eq!(
256            pmap["location"].as_map().unwrap().get("latitude"),
257            Some(&Value::F64(37.7510123))
258        );
259        assert!(!pmap["location"].as_map().unwrap().contains_key("longitude"));
260        assert_eq!(
261            pmap["city"].as_map().unwrap()["names"]
262                .as_map()
263                .unwrap()
264                .len(),
265            1
266        );
267        assert_eq!(
268            pmap["city"].as_map().unwrap()["names"]
269                .as_map()
270                .unwrap()
271                .get("zh-CN"),
272            Some(&Value::Utf8("山景城".into()))
273        );
274
275        // 5. Typed serde deserialization with projection
276        #[derive(Debug, serde::Deserialize, PartialEq)]
277        struct FastGeo {
278            country: Option<CountryIso>,
279            location: Option<LatOnly>,
280        }
281        #[derive(Debug, serde::Deserialize, PartialEq)]
282        struct CountryIso {
283            iso_code: Option<String>,
284        }
285        #[derive(Debug, serde::Deserialize, PartialEq)]
286        struct LatOnly {
287            latitude: Option<f64>,
288        }
289        let typed: FastGeo = reader
290            .lookup_with_projection(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), &proj)
291            .unwrap()
292            .unwrap();
293        assert_eq!(
294            typed,
295            FastGeo {
296                country: Some(CountryIso {
297                    iso_code: Some("US".into())
298                }),
299                location: Some(LatOnly {
300                    latitude: Some(37.7510123)
301                })
302            }
303        );
304    }
305}