maxminddb/result.rs
1//! Lookup result types for deferred decoding.
2//!
3//! This module provides `LookupResult`, which enables lazy decoding of
4//! MaxMind DB records. Instead of immediately deserializing data, you
5//! get a lightweight handle that can be decoded later or navigated
6//! selectively via paths.
7
8use std::net::IpAddr;
9
10use ipnetwork::IpNetwork;
11use serde::Deserialize;
12
13use crate::decoder::{TYPE_ARRAY, TYPE_MAP};
14use crate::error::MaxMindDbError;
15use crate::reader::Reader;
16
17/// The result of looking up an IP address in a MaxMind DB.
18///
19/// This is a lightweight handle (~40 bytes) that stores the lookup result
20/// without immediately decoding the data. You can:
21///
22/// - Check if data exists with [`has_data()`](Self::has_data)
23/// - Get the network containing the IP with [`network()`](Self::network)
24/// - Decode the full record with [`decode()`](Self::decode)
25/// - Decode a specific path with [`decode_path()`](Self::decode_path)
26///
27/// # Example
28///
29/// ```
30/// use maxminddb::{geoip2, path, Reader};
31/// use std::net::IpAddr;
32///
33/// let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
34/// let ip: IpAddr = "89.160.20.128".parse().unwrap();
35///
36/// let result = reader.lookup(ip).unwrap();
37///
38/// if result.has_data() {
39/// // Full decode
40/// let city: geoip2::City = result.decode().unwrap().unwrap();
41///
42/// // Or selective decode via path
43/// let country_code: Option<String> = result
44/// .decode_path(&path!["country", "iso_code"])
45/// .unwrap();
46/// println!("Country: {:?}", country_code);
47/// }
48/// ```
49pub struct LookupResult<'a, S: AsRef<[u8]>> {
50 reader: &'a Reader<S>,
51 /// Offset into the data section, or None if not found.
52 data_offset: Option<usize>,
53 prefix_len: u8,
54 ip: IpAddr,
55 source: LookupSource,
56 network_kind: NetworkKind,
57}
58
59// `Clone`, `Copy` and `Debug` are implemented by hand. Deriving them would
60// require `S: Clone`, `S: Copy` and `S: Debug`, even though the struct only
61// holds a shared reference to the reader. That made results from
62// `Reader<Vec<u8>>` and `Reader<Mmap>` impossible to copy.
63impl<S: AsRef<[u8]>> Clone for LookupResult<'_, S> {
64 #[inline]
65 fn clone(&self) -> Self {
66 *self
67 }
68}
69
70impl<S: AsRef<[u8]>> Copy for LookupResult<'_, S> {}
71
72impl<S: AsRef<[u8]>> std::fmt::Debug for LookupResult<'_, S> {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 f.debug_struct("LookupResult")
75 .field("reader", &self.reader)
76 .field("data_offset", &self.data_offset)
77 .field("prefix_len", &self.prefix_len)
78 .field("ip", &self.ip)
79 .field("source", &self.source)
80 .field("network_kind", &self.network_kind)
81 .finish()
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub(crate) enum LookupSource {
87 Lookup,
88 Iter,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub(crate) enum NetworkKind {
93 V4,
94 V6,
95 V4InV6Subtree,
96}
97
98impl<'a, S: AsRef<[u8]>> LookupResult<'a, S> {
99 #[inline]
100 fn decoder(&self, offset: usize) -> Result<super::decoder::Decoder<'a>, MaxMindDbError> {
101 Ok(super::decoder::Decoder::new(
102 self.reader.data_section()?,
103 offset,
104 ))
105 }
106
107 /// Creates a new LookupResult for a found IP.
108 pub(crate) fn new_found(
109 reader: &'a Reader<S>,
110 data_offset: usize,
111 prefix_len: u8,
112 ip: IpAddr,
113 source: LookupSource,
114 network_kind: NetworkKind,
115 ) -> Self {
116 LookupResult {
117 reader,
118 data_offset: Some(data_offset),
119 prefix_len,
120 ip,
121 source,
122 network_kind,
123 }
124 }
125
126 /// Creates a new LookupResult for an IP not in the database.
127 pub(crate) fn new_not_found(
128 reader: &'a Reader<S>,
129 prefix_len: u8,
130 ip: IpAddr,
131 source: LookupSource,
132 network_kind: NetworkKind,
133 ) -> Self {
134 LookupResult {
135 reader,
136 data_offset: None,
137 prefix_len,
138 ip,
139 source,
140 network_kind,
141 }
142 }
143
144 /// Returns true if the database contains data for this IP address.
145 ///
146 /// Note that `false` means the database has no data for this IP,
147 /// which is different from an error during lookup.
148 #[inline]
149 pub fn has_data(&self) -> bool {
150 self.data_offset.is_some()
151 }
152
153 /// Returns the network containing the looked-up IP address.
154 ///
155 /// This is the most specific network in the database that contains
156 /// the IP, regardless of whether data was found.
157 ///
158 /// The returned network preserves the IP version of the original lookup:
159 /// - IPv4 lookups return IPv4 networks (unless the match occurs before the
160 /// IPv4 subtree begins, see below)
161 /// - IPv6 lookups return IPv6 networks (including IPv4-mapped addresses)
162 ///
163 /// Special case: If an IPv4 address is looked up in an IPv6 database but
164 /// the matching record is above the IPv4 subtree (e.g., a database with
165 /// no IPv4 subtree), an IPv6 network is returned since there's no valid
166 /// IPv4 representation.
167 pub fn network(&self) -> Result<IpNetwork, MaxMindDbError> {
168 let (ip, prefix) = match (self.source, self.network_kind, self.ip) {
169 (_, NetworkKind::V4, IpAddr::V4(v4)) => (IpAddr::V4(v4), self.prefix_len),
170 (_, NetworkKind::V4InV6Subtree, IpAddr::V4(v4)) => (
171 IpAddr::V4(v4),
172 self.prefix_len - self.reader.ipv4_start_bit_depth as u8,
173 ),
174 (LookupSource::Lookup, NetworkKind::V6, IpAddr::V4(_)) => {
175 use std::net::Ipv6Addr;
176 (IpAddr::V6(Ipv6Addr::UNSPECIFIED), self.prefix_len)
177 }
178 (_, NetworkKind::V6, IpAddr::V6(v6)) => (IpAddr::V6(v6), self.prefix_len),
179 (_, _, ip) => unreachable!("unexpected lookup result state for network: {ip:?}"),
180 };
181
182 // Mask the IP to the network address
183 let network_ip = mask_ip(ip, prefix);
184 IpNetwork::new(network_ip, prefix).map_err(MaxMindDbError::InvalidNetwork)
185 }
186
187 /// Returns the data section offset if found, for use as a cache key.
188 ///
189 /// Multiple IP addresses often point to the same data record. This
190 /// offset can be used to deduplicate decoding or cache results.
191 ///
192 /// Returns `None` if the IP was not found.
193 #[inline]
194 pub fn offset(&self) -> Option<usize> {
195 self.data_offset
196 }
197
198 /// Decodes the full record into the specified type.
199 ///
200 /// Returns:
201 /// - `Ok(Some(T))` if found and successfully decoded
202 /// - `Ok(None)` if the IP was not found in the database
203 /// - `Err(...)` if decoding fails
204 ///
205 /// Any operation that enters an MMDB map or array has an expansion budget
206 /// of 65,536 logical values and 2 MiB of string and bytes payload. Dynamic
207 /// `deserialize_any`, enum, and raw-string-helper entry points activate the
208 /// budget before the value's type is known. Only scalar values requested
209 /// directly through a typed scalar entry point avoid this bookkeeping. The
210 /// decoder reserves a container's declared children before Serde can
211 /// allocate for them, repeated pointer targets are charged on every
212 /// expansion, and ignored fields do not expand pointer targets. Exceeding
213 /// either decoder-wide operation limit returns
214 /// [`MaxMindDbError::ResourceLimit`] rather than treating the database as
215 /// necessarily corrupt.
216 ///
217 /// Concrete-schema identifiers get a 32-byte allowance per logical value
218 /// before using the 2 MiB payload counter, whether they are encoded inline
219 /// or behind a pointer. The logical-value limit bounds all such allowances
220 /// to another 2 MiB. Thus, after an operation activates its budget,
221 /// expanded string and byte payload remains bounded to at most 4 MiB even
222 /// for custom identifier visitors. A scalar-only typed decode remains
223 /// limited only by the MMDB format's maximum encoded payload size.
224 ///
225 /// Maps, arrays, and pointers may nest at most 512 levels deep, the limit
226 /// libmaxminddb and the Go reader use. Each map, array, and pointer counts
227 /// as one level, so a pointer and the container it points to take two,
228 /// and a pointer to a string or number takes one. Pointers to struct field
229 /// or enum variant names do not count. Decoding into a newtype enum
230 /// variant adds one level of its own. The decoder reports deeper data as
231 /// [`MaxMindDbError::InvalidDatabase`], though a `Deserialize` impl that
232 /// catches errors, such as an untagged enum, may replace that error.
233 /// Values skipped as unknown fields or [`serde::de::IgnoredAny`] have a
234 /// separate limit of 128 levels, counted from where skipping starts.
235 ///
236 /// Decoding recurses once per level, so the stack it needs grows with
237 /// nesting and with the target type's own `Deserialize` frames. In Cargo's
238 /// default `dev` profile on x86-64 Linux, decoding 512 levels takes about
239 /// 0.6 to 0.8 MiB of stack for `serde_json::Value`, 0.85 MiB for a
240 /// one-field derived recursive struct, 1.2 MiB for one that also skips a
241 /// 128-level unknown field, and 1.3 MiB for a derived newtype over a
242 /// `HashMap`. These fit the 2 MiB default for spawned threads. A derived
243 /// struct's own frame grows with its field count in that profile, so a
244 /// recursive struct with a dozen fields can need 2.5 MiB or more. An
245 /// optimized build needs a small fraction of these figures. A main thread
246 /// with a smaller stack, such as the usual 1 MiB on Windows, a wide or
247 /// custom recursive `Deserialize`, or an unoptimized build with debug
248 /// assertions turned off may need a larger stack.
249 ///
250 /// These general limits do not replace tighter bounds implied by an
251 /// application's schema. A collection with a small semantic maximum should
252 /// enforce it in its `Deserialize` implementation or a Serde
253 /// `deserialize_with` visitor, before allocating or consuming its elements.
254 /// The built-in [`crate::geoip2::City`] and [`crate::geoip2::Enterprise`]
255 /// schemas cap their subdivision lists at
256 /// [`crate::geoip2::MAX_SUBDIVISIONS`] in every Serde format. An otherwise
257 /// valid oversized MMDB list that reaches the schema visitor returns
258 /// [`MaxMindDbError::Decoding`]; malformed data and decoder-wide limits may
259 /// fail earlier with their corresponding error variants.
260 /// Custom deserializers that bypass Serde's map and sequence entry points
261 /// remain responsible for bounding their own traversal over untrusted data.
262 ///
263 /// # Example
264 ///
265 /// ```
266 /// use maxminddb::{Reader, geoip2};
267 /// use std::net::IpAddr;
268 ///
269 /// let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
270 /// let ip: IpAddr = "89.160.20.128".parse().unwrap();
271 ///
272 /// let result = reader.lookup(ip).unwrap();
273 /// if let Some(city) = result.decode::<geoip2::City>()? {
274 /// println!("Found city data");
275 /// }
276 /// # Ok::<(), maxminddb::MaxMindDbError>(())
277 /// ```
278 #[inline]
279 pub fn decode<T>(&self) -> Result<Option<T>, MaxMindDbError>
280 where
281 T: Deserialize<'a>,
282 {
283 let Some(offset) = self.data_offset else {
284 return Ok(None);
285 };
286
287 let mut decoder = self.decoder(offset)?;
288 T::deserialize(&mut decoder)
289 .map(Some)
290 .map_err(|error| error.with_invalid_database_offset_base(self.reader.pointer_base))
291 }
292
293 /// Decodes a value at a specific path within the record.
294 ///
295 /// Returns:
296 /// - `Ok(Some(T))` if the path exists and was successfully decoded
297 /// - `Ok(None)` if the path doesn't exist (key missing, index out of bounds)
298 /// - `Err(...)` if there's a type mismatch during navigation (e.g., `Key` on an array)
299 ///
300 /// If `has_data() == false`, returns `Ok(None)`.
301 /// Path traversal does not expand skipped pointer targets. Navigation and
302 /// the selected value share the container and payload budgets described by
303 /// [`decode()`](Self::decode); resource-limit errors include the path reached
304 /// when the limit was detected.
305 ///
306 /// # Path Elements
307 ///
308 /// - `PathElement::Key("name")` - Navigate into a map by key
309 /// - `PathElement::Index(0)` - Navigate into an array by index (0 = first element)
310 /// - `PathElement::IndexFromEnd(0)` - Navigate from the end (0 = last element)
311 ///
312 /// # Example
313 ///
314 /// ```
315 /// use maxminddb::{path, Reader};
316 /// use std::net::IpAddr;
317 ///
318 /// let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
319 /// let ip: IpAddr = "89.160.20.128".parse().unwrap();
320 ///
321 /// let result = reader.lookup(ip).unwrap();
322 ///
323 /// // Navigate to country.iso_code
324 /// let iso_code: Option<String> = result
325 /// .decode_path(&path!["country", "iso_code"])
326 /// .unwrap();
327 ///
328 /// // Navigate to subdivisions[0].names.en
329 /// let subdiv_name: Option<String> = result
330 /// .decode_path(&path!["subdivisions", 0, "names", "en"])
331 /// .unwrap();
332 /// ```
333 pub fn decode_path<T>(&self, path: &[PathElement<'_>]) -> Result<Option<T>, MaxMindDbError>
334 where
335 T: Deserialize<'a>,
336 {
337 self.decode_path_relative(path)
338 .map_err(|error| error.with_invalid_database_offset_base(self.reader.pointer_base))
339 }
340
341 #[inline]
342 fn decode_path_relative<T>(&self, path: &[PathElement<'_>]) -> Result<Option<T>, MaxMindDbError>
343 where
344 T: Deserialize<'a>,
345 {
346 let Some(offset) = self.data_offset else {
347 return Ok(None);
348 };
349
350 let mut decoder = self.decoder(offset)?;
351
352 // Navigate through the path, tracking position for error context
353 for (i, element) in path.iter().enumerate() {
354 // Closure to add path context to errors during navigation.
355 // Shows path up to and including the current element where the error occurred.
356 let with_path =
357 |e: crate::decoder::DecoderError| add_path_context(e.into(), &path[..=i]);
358
359 match *element {
360 PathElement::Key(key) => {
361 let header_offset = decoder.offset();
362 let (size, type_num) = decoder.consume_container_header().map_err(with_path)?;
363 if type_num != TYPE_MAP {
364 return Err(container_type_mismatch(
365 type_num,
366 header_offset,
367 &path[..=i],
368 format!("expected map for Key(\"{key}\"), got type {type_num}"),
369 ));
370 }
371
372 let mut found = false;
373 let key_bytes = key.as_bytes();
374 for _ in 0..size {
375 let k = decoder.read_str_as_bytes().map_err(with_path)?;
376 if k == key_bytes {
377 found = true;
378 break;
379 } else {
380 decoder.skip_value().map_err(with_path)?;
381 }
382 }
383
384 if !found {
385 decoder.validate_skip_end().map_err(with_path)?;
386 return Ok(None);
387 }
388 }
389 PathElement::Index(idx) | PathElement::IndexFromEnd(idx) => {
390 let header_offset = decoder.offset();
391 let (size, type_num) = decoder.consume_container_header().map_err(with_path)?;
392 if type_num != TYPE_ARRAY {
393 let elem = match *element {
394 PathElement::Index(i) => format!("Index({i})"),
395 PathElement::IndexFromEnd(i) => format!("IndexFromEnd({i})"),
396 PathElement::Key(_) => unreachable!(),
397 };
398 return Err(container_type_mismatch(
399 type_num,
400 header_offset,
401 &path[..=i],
402 format!("expected array for {elem}, got type {type_num}"),
403 ));
404 }
405
406 if idx >= size {
407 return Ok(None); // Out of bounds
408 }
409
410 let actual_idx = match *element {
411 PathElement::Index(i) => i,
412 PathElement::IndexFromEnd(i) => size - 1 - i,
413 PathElement::Key(_) => unreachable!(),
414 };
415
416 // Skip to the target index
417 for _ in 0..actual_idx {
418 decoder.skip_value().map_err(with_path)?;
419 }
420 }
421 }
422 }
423
424 // Decode the value at the current position
425 T::deserialize(&mut decoder)
426 .map(Some)
427 .map_err(|error| add_path_context(error.into(), path))
428 }
429}
430
431#[cold]
432fn container_type_mismatch(
433 type_num: usize,
434 offset: usize,
435 path: &[PathElement<'_>],
436 message: String,
437) -> MaxMindDbError {
438 if type_num > usize::from(u8::MAX) {
439 MaxMindDbError::invalid_database_at(format!("unknown data type: {type_num}"), offset)
440 } else {
441 MaxMindDbError::decoding_at_path(message, offset, render_path(path))
442 }
443}
444
445/// Adds path context to a decoding or resource-limit error if it does not
446/// already have one.
447fn add_path_context(err: MaxMindDbError, path: &[PathElement<'_>]) -> MaxMindDbError {
448 match err {
449 MaxMindDbError::Decoding {
450 message,
451 offset,
452 path: None,
453 } => MaxMindDbError::Decoding {
454 message,
455 offset,
456 path: Some(render_path(path)),
457 },
458 MaxMindDbError::ResourceLimit {
459 message,
460 offset,
461 path: None,
462 } => MaxMindDbError::ResourceLimit {
463 message,
464 offset,
465 path: Some(render_path(path)),
466 },
467 _ => err,
468 }
469}
470
471/// Renders path elements as a JSON-pointer-like string (e.g., "/city/names/0").
472fn render_path(path: &[PathElement<'_>]) -> String {
473 use std::fmt::Write;
474 let mut s = String::new();
475 for elem in path {
476 s.push('/');
477 match elem {
478 PathElement::Key(k) => s.push_str(k),
479 PathElement::Index(i) => write!(s, "{i}").unwrap(),
480 PathElement::IndexFromEnd(i) => write!(s, "-{}", (*i as u128) + 1).unwrap(),
481 }
482 }
483 s
484}
485
486/// A path element for navigating into nested data structures.
487///
488/// Used with [`LookupResult::decode_path()`] to selectively decode
489/// specific fields without parsing the entire record.
490///
491/// # Creating Path Elements
492///
493/// You can create path elements directly or use the [`path!`](crate::path) macro
494/// for a more convenient syntax:
495///
496/// ```
497/// use maxminddb::{path, PathElement};
498///
499/// // Direct construction
500/// let path = [PathElement::Key("country"), PathElement::Key("iso_code")];
501///
502/// // Using the macro - string literals become Keys, integers become Indexes
503/// let path = path!["country", "iso_code"];
504/// let path = path!["subdivisions", 0, "names"]; // Mixed keys and indexes
505/// let path = path!["array", -1]; // Negative indexes count from the end
506/// ```
507#[derive(Debug, Clone, PartialEq, Eq)]
508pub enum PathElement<'a> {
509 /// Navigate into a map by key.
510 Key(&'a str),
511 /// Navigate into an array by index (0-based from the start).
512 ///
513 /// - `Index(0)` - first element
514 /// - `Index(1)` - second element
515 Index(usize),
516 /// Navigate into an array by index from the end.
517 ///
518 /// - `IndexFromEnd(0)` - last element
519 /// - `IndexFromEnd(1)` - second-to-last element
520 IndexFromEnd(usize),
521}
522
523impl<'a> From<&'a str> for PathElement<'a> {
524 fn from(s: &'a str) -> Self {
525 PathElement::Key(s)
526 }
527}
528
529impl From<i32> for PathElement<'_> {
530 /// Converts an integer to a path element.
531 ///
532 /// - Non-negative values become `Index(n)`
533 /// - Negative values become `IndexFromEnd(-n - 1)`, so `-1` is the last element
534 fn from(n: i32) -> Self {
535 signed_index_to_path_element(n as isize)
536 }
537}
538
539impl From<usize> for PathElement<'_> {
540 fn from(n: usize) -> Self {
541 PathElement::Index(n)
542 }
543}
544
545impl From<isize> for PathElement<'_> {
546 /// Converts a signed integer to a path element.
547 ///
548 /// - Non-negative values become `Index(n)`
549 /// - Negative values become `IndexFromEnd(-n - 1)`, so `-1` is the last element
550 /// - `isize::MIN` saturates to `IndexFromEnd(usize::MAX)` because its
551 /// absolute value is unrepresentable as `isize`
552 fn from(n: isize) -> Self {
553 signed_index_to_path_element(n)
554 }
555}
556
557fn signed_index_to_path_element<'a>(n: isize) -> PathElement<'a> {
558 if n >= 0 {
559 PathElement::Index(n as usize)
560 } else {
561 let index = n
562 .checked_neg()
563 .and_then(|n| n.checked_sub(1))
564 .map(|n| n as usize)
565 .unwrap_or(usize::MAX);
566 PathElement::IndexFromEnd(index)
567 }
568}
569
570/// Creates a path for use with [`LookupResult::decode_path()`](crate::LookupResult::decode_path).
571///
572/// This macro provides a convenient way to construct paths with mixed string keys
573/// and integer indexes.
574///
575/// # Syntax
576///
577/// - String literals become [`PathElement::Key`]
578/// - Non-negative integers become [`PathElement::Index`]
579/// - Negative integers become [`PathElement::IndexFromEnd`] (e.g., `-1` is the last element)
580///
581/// # Examples
582///
583/// ```
584/// use maxminddb::{Reader, path};
585/// use std::net::IpAddr;
586///
587/// let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
588/// let ip: IpAddr = "89.160.20.128".parse().unwrap();
589/// let result = reader.lookup(ip).unwrap();
590///
591/// // Navigate to country.iso_code
592/// let iso_code: Option<String> = result.decode_path(&path!["country", "iso_code"]).unwrap();
593///
594/// // Navigate to subdivisions[0].names.en
595/// let subdiv: Option<String> = result.decode_path(&path!["subdivisions", 0, "names", "en"]).unwrap();
596/// ```
597///
598/// ```
599/// use maxminddb::{Reader, path};
600/// use std::net::IpAddr;
601///
602/// let reader = Reader::open_readfile("test-data/test-data/MaxMind-DB-test-decoder.mmdb").unwrap();
603/// let ip: IpAddr = "::1.1.1.0".parse().unwrap();
604/// let result = reader.lookup(ip).unwrap();
605///
606/// // Access the last element of an array
607/// let last: Option<u32> = result.decode_path(&path!["array", -1]).unwrap();
608/// assert_eq!(last, Some(3));
609///
610/// // Access the second-to-last element
611/// let second_to_last: Option<u32> = result.decode_path(&path!["array", -2]).unwrap();
612/// assert_eq!(second_to_last, Some(2));
613/// ```
614#[macro_export]
615macro_rules! path {
616 ($($elem:expr),* $(,)?) => {
617 [$($crate::PathElement::from($elem)),*]
618 };
619}
620
621/// Masks an IP address to its network address given a prefix length.
622fn mask_ip(ip: IpAddr, prefix: u8) -> IpAddr {
623 match ip {
624 IpAddr::V4(v4) => {
625 if prefix >= 32 {
626 IpAddr::V4(v4)
627 } else {
628 let int: u32 = v4.into();
629 let mask = if prefix == 0 {
630 0
631 } else {
632 !0u32 << (32 - prefix)
633 };
634 IpAddr::V4((int & mask).into())
635 }
636 }
637 IpAddr::V6(v6) => {
638 if prefix >= 128 {
639 IpAddr::V6(v6)
640 } else {
641 let int: u128 = v6.into();
642 let mask = if prefix == 0 {
643 0
644 } else {
645 !0u128 << (128 - prefix)
646 };
647 IpAddr::V6((int & mask).into())
648 }
649 }
650 }
651}
652
653#[cfg(test)]
654mod tests {
655 use super::*;
656
657 #[test]
658 fn test_mask_ipv4() {
659 let ip: IpAddr = "192.168.1.100".parse().unwrap();
660 assert_eq!(mask_ip(ip, 24), "192.168.1.0".parse::<IpAddr>().unwrap());
661 assert_eq!(mask_ip(ip, 16), "192.168.0.0".parse::<IpAddr>().unwrap());
662 assert_eq!(mask_ip(ip, 32), "192.168.1.100".parse::<IpAddr>().unwrap());
663 assert_eq!(mask_ip(ip, 0), "0.0.0.0".parse::<IpAddr>().unwrap());
664 }
665
666 #[test]
667 fn test_mask_ipv6() {
668 let ip: IpAddr = "2001:db8:85a3::8a2e:370:7334".parse().unwrap();
669 assert_eq!(
670 mask_ip(ip, 64),
671 "2001:db8:85a3::".parse::<IpAddr>().unwrap()
672 );
673 assert_eq!(mask_ip(ip, 32), "2001:db8::".parse::<IpAddr>().unwrap());
674 }
675
676 #[test]
677 fn test_path_element_debug() {
678 assert_eq!(format!("{:?}", PathElement::Key("test")), "Key(\"test\")");
679 assert_eq!(format!("{:?}", PathElement::Index(5)), "Index(5)");
680 assert_eq!(
681 format!("{:?}", PathElement::IndexFromEnd(0)),
682 "IndexFromEnd(0)"
683 );
684 }
685
686 #[test]
687 fn test_path_element_from_str() {
688 let elem: PathElement = "key".into();
689 assert_eq!(elem, PathElement::Key("key"));
690 }
691
692 #[test]
693 fn test_path_element_from_i32() {
694 // Positive values become Index
695 let elem: PathElement = PathElement::from(0i32);
696 assert_eq!(elem, PathElement::Index(0));
697
698 let elem: PathElement = PathElement::from(5i32);
699 assert_eq!(elem, PathElement::Index(5));
700
701 // Negative values become IndexFromEnd
702 // -1 → IndexFromEnd(0) (last element)
703 let elem: PathElement = PathElement::from(-1i32);
704 assert_eq!(elem, PathElement::IndexFromEnd(0));
705
706 // -2 → IndexFromEnd(1) (second-to-last)
707 let elem: PathElement = PathElement::from(-2i32);
708 assert_eq!(elem, PathElement::IndexFromEnd(1));
709
710 // -3 → IndexFromEnd(2)
711 let elem: PathElement = PathElement::from(-3i32);
712 assert_eq!(elem, PathElement::IndexFromEnd(2));
713 }
714
715 #[test]
716 fn test_path_element_from_usize() {
717 let elem: PathElement = PathElement::from(0usize);
718 assert_eq!(elem, PathElement::Index(0));
719
720 let elem: PathElement = PathElement::from(42usize);
721 assert_eq!(elem, PathElement::Index(42));
722 }
723
724 #[test]
725 fn test_path_element_from_isize() {
726 let elem: PathElement = PathElement::from(0isize);
727 assert_eq!(elem, PathElement::Index(0));
728
729 let elem: PathElement = PathElement::from(-1isize);
730 assert_eq!(elem, PathElement::IndexFromEnd(0));
731
732 let elem: PathElement = PathElement::from(isize::MIN);
733 assert_eq!(elem, PathElement::IndexFromEnd(usize::MAX));
734 }
735
736 #[test]
737 fn test_path_macro_keys_only() {
738 let p = path!["country", "iso_code"];
739 assert_eq!(p.len(), 2);
740 assert_eq!(p[0], PathElement::Key("country"));
741 assert_eq!(p[1], PathElement::Key("iso_code"));
742 }
743
744 #[test]
745 fn test_path_macro_mixed() {
746 let p = path!["subdivisions", 0, "names", "en"];
747 assert_eq!(p.len(), 4);
748 assert_eq!(p[0], PathElement::Key("subdivisions"));
749 assert_eq!(p[1], PathElement::Index(0));
750 assert_eq!(p[2], PathElement::Key("names"));
751 assert_eq!(p[3], PathElement::Key("en"));
752 }
753
754 #[test]
755 fn test_path_macro_negative_indexes() {
756 let p = path!["array", -1];
757 assert_eq!(p.len(), 2);
758 assert_eq!(p[0], PathElement::Key("array"));
759 assert_eq!(p[1], PathElement::IndexFromEnd(0)); // last element
760
761 let p = path!["data", -2, "value"];
762 assert_eq!(p[1], PathElement::IndexFromEnd(1)); // second-to-last
763 }
764
765 #[test]
766 fn test_path_macro_trailing_comma() {
767 let p = path!["a", "b",];
768 assert_eq!(p.len(), 2);
769 }
770
771 #[test]
772 fn test_path_macro_empty() {
773 let p: [PathElement; 0] = path![];
774 assert_eq!(p.len(), 0);
775 }
776
777 #[test]
778 fn test_render_path() {
779 assert_eq!(render_path(&[]), "");
780 assert_eq!(render_path(&[PathElement::Key("city")]), "/city");
781 assert_eq!(
782 render_path(&[PathElement::Key("city"), PathElement::Key("names")]),
783 "/city/names"
784 );
785 assert_eq!(
786 render_path(&[PathElement::Key("arr"), PathElement::Index(0)]),
787 "/arr/0"
788 );
789 assert_eq!(
790 render_path(&[PathElement::Key("arr"), PathElement::Index(42)]),
791 "/arr/42"
792 );
793 // IndexFromEnd(0) = last = -1, IndexFromEnd(1) = second-to-last = -2
794 assert_eq!(
795 render_path(&[PathElement::Key("arr"), PathElement::IndexFromEnd(0)]),
796 "/arr/-1"
797 );
798 assert_eq!(
799 render_path(&[PathElement::Key("arr"), PathElement::IndexFromEnd(1)]),
800 "/arr/-2"
801 );
802 assert_eq!(
803 render_path(&[PathElement::IndexFromEnd(isize::MAX as usize)]),
804 format!("/-{}", (isize::MAX as u128) + 1)
805 );
806 assert_eq!(
807 render_path(&[PathElement::IndexFromEnd(usize::MAX)]),
808 format!("/-{}", (usize::MAX as u128) + 1)
809 );
810 }
811
812 #[test]
813 fn test_decode_path_error_includes_path() {
814 use crate::Reader;
815
816 let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
817 let ip: IpAddr = "89.160.20.128".parse().unwrap();
818 let result = reader.lookup(ip).unwrap();
819
820 // Try to navigate with Index on a map (root is a map, not array)
821 let err = result
822 .decode_path::<String>(&[PathElement::Index(0)])
823 .unwrap_err();
824 let err_str = err.to_string();
825 assert!(
826 err_str.contains("path: /0"),
827 "error should include path context: {err_str}"
828 );
829 assert!(
830 err_str.contains("expected array"),
831 "error should mention expected type: {err_str}"
832 );
833
834 // Try to navigate deeper and fail at second element
835 let err = result
836 .decode_path::<String>(&[PathElement::Key("city"), PathElement::Index(0)])
837 .unwrap_err();
838 let err_str = err.to_string();
839 assert!(
840 err_str.contains("path: /city/0"),
841 "error should include full path to failure: {err_str}"
842 );
843 }
844
845 #[test]
846 fn test_overflowing_extended_navigation_type_is_invalid_database() {
847 let err = container_type_mismatch(
848 256,
849 7,
850 &[PathElement::Key("city")],
851 "unused mismatch".to_owned(),
852 );
853
854 assert!(matches!(err, MaxMindDbError::InvalidDatabase { .. }));
855 assert!(err.to_string().contains("unknown data type: 256"));
856 }
857
858 #[test]
859 fn test_resource_limit_error_includes_path() {
860 let err = add_path_context(
861 MaxMindDbError::resource_limit_at("too many values", 7),
862 &[PathElement::Key("subdivisions")],
863 );
864
865 assert!(matches!(
866 err,
867 MaxMindDbError::ResourceLimit {
868 path: Some(ref path),
869 ..
870 } if path == "/subdivisions"
871 ));
872 }
873}