maxminddb/lib.rs
1#![deny(trivial_casts, trivial_numeric_casts, unused_import_braces)]
2// docs.rs builds on nightly with `--cfg docsrs`. `doc_cfg` labels items gated
3// on a feature, such as the `mmap` API, with the feature they need.
4#![cfg_attr(docsrs, feature(doc_cfg))]
5//! # MaxMind DB Reader
6//!
7//! This library reads the MaxMind DB format, including the GeoIP2 and GeoLite2 databases.
8//!
9//! ## Features
10//!
11//! This crate provides several optional features for performance and functionality:
12//!
13//! - **`mmap`** (default: disabled): Enable memory-mapped file access for
14//! better performance in long-running applications
15//! - **`unsafe-str-decode`** (default: disabled): Skip UTF-8 validation
16//! when deserializing trusted database strings into Rust `str` or `String`
17//! values. Cross-runtime format adapters should prefer
18//! [`deserialize_any_with_raw_strings()`] and validate while constructing
19//! the target runtime's string type.
20//!
21//! ## Database Compatibility
22//!
23//! This library supports all MaxMind DB format databases:
24//! - **GeoIP2** databases (City, Country, Enterprise, ISP, etc.)
25//! - **GeoLite2** databases (free versions)
26//! - Custom MaxMind DB format databases
27//!
28//! ## Thread Safety
29//!
30//! `Reader<S>` is `Send` when `S` is `Send`, and `Sync` when `S` is `Sync`.
31//! `Reader<Vec<u8>>`, returned by [`Reader::open_readfile`], implements both:
32//!
33//! ```
34//! fn assert_send_sync<T: Send + Sync>() {}
35//! assert_send_sync::<maxminddb::Reader<Vec<u8>>>();
36//! ```
37//!
38//! Custom sources passed to [`Reader::from_source`] determine these traits.
39//! For example, a source of type `std::rc::Rc<[u8]>` makes the reader neither
40//! `Send` nor `Sync`.
41//!
42//! ## Quick Start
43//!
44//! ```rust
45//! use maxminddb::{Reader, geoip2};
46//! use std::net::IpAddr;
47//!
48//! fn main() -> Result<(), Box<dyn std::error::Error>> {
49//! // Open database file
50//! # let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb")?;
51//! # /*
52//! let reader = Reader::open_readfile("/path/to/GeoIP2-City.mmdb")?;
53//! # */
54//!
55//! // Look up an IP address
56//! let ip: IpAddr = "89.160.20.128".parse()?;
57//! let result = reader.lookup(ip)?;
58//!
59//! if let Some(city) = result.decode::<geoip2::City>()? {
60//! // Access nested structs directly - no Option unwrapping needed
61//! println!("Country: {}", city.country.iso_code.unwrap_or("Unknown"));
62//! }
63//!
64//! Ok(())
65//! }
66//! ```
67//!
68//! ## Selective Field Access
69//!
70//! Use `decode_path` to extract specific fields without deserializing the entire record:
71//!
72//! ```rust
73//! use maxminddb::{path, Reader};
74//! use std::net::IpAddr;
75//!
76//! let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
77//! let ip: IpAddr = "89.160.20.128".parse().unwrap();
78//!
79//! let result = reader.lookup(ip).unwrap();
80//! let country_code: Option<String> = result.decode_path(&path!["country", "iso_code"]).unwrap();
81//!
82//! println!("Country: {:?}", country_code);
83//! ```
84
85mod decoder;
86mod error;
87pub mod geoip2;
88mod metadata;
89mod reader;
90mod result;
91mod within;
92
93// Re-export public types
94pub use decoder::deserialize_any_with_raw_strings;
95pub use error::MaxMindDbError;
96pub use metadata::Metadata;
97pub use reader::Reader;
98pub use result::{LookupResult, PathElement};
99pub use within::{Within, WithinOptions};
100
101#[cfg(feature = "mmap")]
102pub use memmap2::Mmap;
103
104/// Internal entry points for the cargo-fuzz targets.
105#[cfg(feature = "fuzzing")]
106#[doc(hidden)]
107pub mod fuzzing {
108 use serde::Deserialize;
109
110 use crate::decoder::{Decoder, VerificationState};
111 use crate::MaxMindDbError;
112
113 /// Deserialize one data-section value through the Serde decoder.
114 pub fn decode<'de, T>(data: &'de [u8]) -> Result<T, MaxMindDbError>
115 where
116 T: Deserialize<'de>,
117 {
118 T::deserialize(&mut Decoder::new(data, 0)).map_err(Into::into)
119 }
120
121 /// Validate one data-section value through the verification decoder.
122 pub fn verify(data: &[u8]) -> Result<(), MaxMindDbError> {
123 Decoder::new(data, 0)
124 .skip_value_for_verification(&mut VerificationState::new(data.len()))
125 .map_err(Into::into)
126 }
127}