Skip to main content

maxminddb/
decoder.rs

1//! Binary format decoder for MaxMind DB files.
2//!
3//! This module implements deserialization of the MaxMind DB binary format
4//! into Rust types via serde. The decoder handles all MaxMind DB data types
5//! including pointers, maps, arrays, and primitive types.
6//!
7//! Most users should not need to interact with this module directly.
8//! Use [`Reader::lookup()`](crate::Reader::lookup) for normal lookups.
9
10use serde::de::{
11    self, value::BorrowedBytesDeserializer, DeserializeSeed, Deserializer, MapAccess, SeqAccess,
12    Visitor,
13};
14use serde::forward_to_deserialize_any;
15
16use crate::error::MaxMindDbError;
17
18mod key;
19mod verification;
20use key::{CachedKey, KeyDeserializer};
21pub(crate) use verification::VerificationState;
22
23// MaxMind DB type constants
24const TYPE_EXTENDED: usize = 0;
25pub(crate) const TYPE_POINTER: usize = 1;
26const TYPE_STRING: usize = 2;
27const TYPE_DOUBLE: usize = 3;
28const TYPE_BYTES: usize = 4;
29const TYPE_UINT16: usize = 5;
30const TYPE_UINT32: usize = 6;
31pub(crate) const TYPE_MAP: usize = 7;
32const TYPE_INT32: usize = 8;
33const TYPE_UINT64: usize = 9;
34const TYPE_UINT128: usize = 10;
35pub(crate) const TYPE_ARRAY: usize = 11;
36const TYPE_BOOL: usize = 14;
37const TYPE_FLOAT: usize = 15;
38
39const RAW_STRINGS_NEWTYPE: &str = "$maxminddb::raw_strings";
40
41/// Maximum recursion depth for nested data structures.
42/// This matches the value used in libmaxminddb and the Go reader.
43///
44/// Decoding recurses once per level. An unoptimized build gives every local
45/// of an inlined callee its own stack slot, so the `inline(always)` header
46/// and scalar helpers made each level take about 5 KiB there, and 512 levels
47/// overflowed a 2 MiB thread stack. Builds with debug assertions mark three of
48/// them only `#[inline]`: the header reader, the pointer decoder, and the
49/// dynamic value decoder. An unoptimized build does not inline a hint, and an
50/// optimized one with debug assertions, such as a fuzz build, still may. Rust
51/// has no `cfg` for the optimization level, and debug assertions are on in
52/// Cargo's unoptimized profiles and off in its optimized ones, so release
53/// builds still force the inlining.
54const MAXIMUM_DATA_STRUCTURE_DEPTH: u16 = 512;
55
56/// Maximum number of logical values decoded in one container-shaped operation.
57/// A container reserves all of its children before the visitor enters it, so a
58/// pointer fan-out exhausts the budget without a counter update on every scalar
59/// header. A pointer and the value it resolves to are one logical occurrence.
60const MAXIMUM_DATA_STRUCTURE_VALUES: u32 = 1 << 16;
61
62/// Maximum total string and bytes payload delivered through budgeted decode
63/// paths. Re-decoding a shared target recharges its payload. Payload reached
64/// only through `skip_value`, including an unknown or `IgnoredAny` value, is not
65/// materialized or charged. Keys exposed to a dynamically shaped map visitor
66/// are conservatively precharged before the visitor's key seed runs, even when
67/// that seed ignores them.
68const MAXIMUM_DATA_STRUCTURE_BYTES: usize = 2 << 20;
69
70/// Identifier bytes covered by the logical-value budget rather than the
71/// payload counter. At most one identifier occurs per reserved logical value,
72/// so this allowance can add no more than another 2 MiB per operation while
73/// keeping ordinary short schema keys off the payload-accounting hot path.
74const MAXIMUM_UNCHARGED_IDENTIFIER_BYTES: usize =
75    MAXIMUM_DATA_STRUCTURE_BYTES / MAXIMUM_DATA_STRUCTURE_VALUES as usize;
76
77// Depth, the logical-value count, and the budget flags share one word,
78// preserving Decoder's existing size on 64-bit targets. Keeping the payload
79// allowance separate avoids extracting and replacing it for every string.
80const DEPTH_MASK: u32 = (1 << 10) - 1;
81const BUDGET_VALUES_SHIFT: u32 = 10;
82const BUDGET_VALUES_MASK: u32 = ((1 << 17) - 1) << BUDGET_VALUES_SHIFT;
83const BUDGET_ACTIVE_MASK: u32 = 1 << 27;
84
85/// Lower limit for values skipped through unknown fields or IgnoredAny.
86/// Skipping is recursive and can be reached by corrupt data that callers did
87/// not explicitly request, so keep the limit below small default thread stacks.
88const MAXIMUM_SKIPPED_DATA_STRUCTURE_DEPTH: u16 = 128;
89
90/// Whether a type is a known data type that is not valid as a map key. A key
91/// of any other type, apart from a string or a pointer, has a type this
92/// decoder doesn't know.
93fn is_known_non_key_type(type_num: usize) -> bool {
94    matches!(type_num, TYPE_DOUBLE..=TYPE_ARRAY | TYPE_BOOL | TYPE_FLOAT)
95}
96
97#[cfg(not(feature = "unsafe-str-decode"))]
98#[inline]
99fn is_ascii(bytes: &[u8]) -> bool {
100    // Overlapping word reads cover short strings without a byte-by-byte tail.
101    match bytes.len() {
102        4..=7 => {
103            let first = u32::from_ne_bytes(bytes[..4].try_into().unwrap());
104            let last = u32::from_ne_bytes(bytes[bytes.len() - 4..].try_into().unwrap());
105            (first | last) & 0x8080_8080 == 0
106        }
107        8..=16 => {
108            let first = u64::from_ne_bytes(bytes[..8].try_into().unwrap());
109            let last = u64::from_ne_bytes(bytes[bytes.len() - 8..].try_into().unwrap());
110            (first | last) & 0x8080_8080_8080_8080 == 0
111        }
112        _ => bytes.is_ascii(),
113    }
114}
115
116macro_rules! decode_int_like {
117    ($name:ident, $ty:ty, $max_size:expr, $label:literal, $zero:expr) => {
118        fn $name(&mut self, size: usize) -> DecodeResult<$ty> {
119            match size {
120                s if s <= $max_size => {
121                    let new_offset = self
122                        .current_ptr
123                        .checked_add(size)
124                        .filter(|&offset| offset <= self.limit)
125                        .ok_or_else(|| {
126                            self.invalid_db_error(&format!("{} of size {}", $label, size))
127                        })?;
128                    let value = self
129                        .slice(self.current_ptr, new_offset)
130                        .iter()
131                        .fold($zero, |acc, &b| (acc << 8) | <$ty>::from(b));
132                    self.current_ptr = new_offset;
133                    Ok(value)
134                }
135                s => Err(self.invalid_db_error(&format!("{} of size {}", $label, s))),
136            }
137        }
138    };
139}
140
141macro_rules! deserialize_direct_scalar {
142    ($name:ident, $expected_type:expr, $label:literal, $visit:ident, $decode:ident) => {
143        fn $name<V>(self, visitor: V) -> DecodeResult<V::Value>
144        where
145            V: Visitor<'de>,
146        {
147            let (size, type_num) = self.size_and_type()?;
148            self.decode_direct(size, type_num, $expected_type, $label, |de, size| {
149                visitor.$visit(de.$decode(size)?)
150            })
151        }
152    };
153}
154
155macro_rules! deserialize_direct_payload {
156    ($name:ident, $expected_type:expr, $label:literal, $visit:ident, $decode:ident) => {
157        #[cfg_attr(feature = "unsafe-str-decode", inline(always))]
158        fn $name<V>(self, visitor: V) -> DecodeResult<V::Value>
159        where
160            V: Visitor<'de>,
161        {
162            let (size, type_num) = self.size_and_type()?;
163            self.decode_direct(size, type_num, $expected_type, $label, |de, size| {
164                de.count_payload(size)?;
165                visitor.$visit(de.$decode(size)?)
166            })
167        }
168    };
169}
170
171enum Value<'a, 'de> {
172    Any { prev_ptr: usize },
173    Bytes(&'de [u8]),
174    String(&'de str),
175    RawString(&'de [u8]),
176    Bool(bool),
177    I32(i32),
178    U16(u16),
179    U32(u32),
180    U64(u64),
181    U128(u128),
182    F64(f64),
183    F32(f32),
184    Map(MapAccessor<'a, 'de, true>),
185    Array(ArrayAccess<'a, 'de>),
186}
187
188/// Decoder for MaxMind DB binary format.
189///
190/// Implements serde's `Deserializer` trait. Handles pointer resolution,
191/// type coercion, and nested data structures.
192#[derive(Debug)]
193pub(crate) struct Decoder<'de> {
194    buf: &'de [u8],
195    limit: usize,
196    current_ptr: usize,
197    state: u32,
198    payload_remaining: u32,
199}
200
201impl<'de> Decoder<'de> {
202    /// Creates a decoder over all of `buf`.
203    ///
204    /// `slice` and `eat_byte` use unchecked reads that rely on
205    /// `limit <= buf.len()`. Taking the limit from `buf` itself keeps that
206    /// invariant true without a separate check.
207    pub(crate) fn new(buf: &'de [u8], start_ptr: usize) -> Decoder<'de> {
208        Decoder {
209            buf,
210            limit: buf.len(),
211            current_ptr: start_ptr,
212            state: 0,
213            payload_remaining: MAXIMUM_DATA_STRUCTURE_BYTES as u32,
214        }
215    }
216
217    /// Creates a decoder that reads no further than `limit`.
218    ///
219    /// # Panics
220    ///
221    /// Panics if `limit > buf.len()`.
222    #[cfg(test)]
223    pub(crate) fn new_with_limit(buf: &'de [u8], start_ptr: usize, limit: usize) -> Decoder<'de> {
224        assert!(
225            limit <= buf.len(),
226            "decoder limit {limit} exceeds buffer length {}",
227            buf.len()
228        );
229        Decoder {
230            limit,
231            ..Decoder::new(buf, start_ptr)
232        }
233    }
234
235    #[inline(always)]
236    fn activate_budget(&mut self) {
237        if self.state & BUDGET_ACTIVE_MASK == 0 {
238            // The value that caused activation is the top-level budgeted value.
239            self.state |= BUDGET_ACTIVE_MASK | (1 << BUDGET_VALUES_SHIFT);
240        }
241    }
242
243    /// Check and increment depth, returning error if limit exceeded.
244    #[inline]
245    fn enter_nested(&mut self) -> DecodeResult<()> {
246        if self.state & DEPTH_MASK >= u32::from(MAXIMUM_DATA_STRUCTURE_DEPTH) {
247            return Err(self.invalid_db_error(
248                "exceeded maximum data structure depth; database is likely corrupt",
249            ));
250        }
251        self.state += 1;
252        Ok(())
253    }
254
255    /// Decrement depth when exiting a nested structure.
256    #[inline]
257    fn exit_nested(&mut self) {
258        if self.state & DEPTH_MASK != 0 {
259            self.state -= 1;
260        }
261    }
262
263    /// Reserve logical child values before entering a container. Charging the
264    /// complete child count up front bounds both flat containers and pointer
265    /// fan-out without touching the scalar decode hot path.
266    #[inline(always)]
267    fn reserve_values(&mut self, count: usize) -> DecodeResult<()> {
268        if self.state & BUDGET_ACTIVE_MASK == 0 {
269            return Ok(());
270        }
271        let values_used = ((self.state & BUDGET_VALUES_MASK) >> BUDGET_VALUES_SHIFT) as usize;
272        if count > MAXIMUM_DATA_STRUCTURE_VALUES as usize - values_used {
273            return Err(
274                self.resource_limit_error("exceeded maximum number of data structure values")
275            );
276        }
277        self.state += (count as u32) << BUDGET_VALUES_SHIFT;
278        Ok(())
279    }
280
281    #[inline(always)]
282    fn reserve_container_values(&mut self, size: usize, type_num: usize) -> DecodeResult<()> {
283        // A scalar decoded on its own cannot fan out. The first map or array is
284        // the point at which one encoded value can produce unbounded work, so
285        // activate the shared operation budget here for every Serde shape.
286        self.activate_budget();
287        let count = if type_num == TYPE_MAP {
288            size.saturating_mul(2)
289        } else {
290            debug_assert_eq!(type_num, TYPE_ARRAY);
291            size
292        };
293        self.reserve_values(count)
294    }
295
296    /// Charge a string or bytes payload against the per-decode byte budget,
297    /// returning an error once the total exceeds the limit. This bounds a
298    /// payload amplification: many pointers to one large value each recharge the
299    /// budget, so the decoder will not repeatedly deliver more payload than the
300    /// limit no matter how heavily a target is shared. A custom visitor may
301    /// still allocate a representation larger than the borrowed input. Small
302    /// fixed-width scalars are not charged.
303    #[inline(always)]
304    fn count_payload(&mut self, size: usize) -> DecodeResult<()> {
305        if self.state & BUDGET_ACTIVE_MASK == 0 {
306            return Ok(());
307        }
308        if size > self.payload_remaining as usize {
309            return Err(self.resource_limit_error(
310                "exceeded maximum size of data structure string and bytes values",
311            ));
312        }
313        self.payload_remaining -= size as u32;
314        Ok(())
315    }
316
317    /// Charge identifier payload beyond the portion already covered by the
318    /// logical-value budget. Ordinary short schema keys remain free from
319    /// payload-counter updates.
320    #[inline(always)]
321    fn count_identifier_payload(&mut self, size: usize) -> DecodeResult<()> {
322        if size <= MAXIMUM_UNCHARGED_IDENTIFIER_BYTES {
323            return Ok(());
324        }
325        self.count_long_identifier_payload(size)
326    }
327
328    #[cold]
329    #[inline(never)]
330    fn count_long_identifier_payload(&mut self, size: usize) -> DecodeResult<()> {
331        self.count_payload(size - MAXIMUM_UNCHARGED_IDENTIFIER_BYTES)
332    }
333
334    /// Charges a string or bytes value at the current position without
335    /// consuming it. Dynamically shaped maps use this for keys because a raw
336    /// identifier visitor may copy them without requesting a string decode.
337    /// Retains complete string bytes for identifier visitors to reuse.
338    #[inline]
339    fn count_payload_at_current(&mut self) -> DecodeResult<(bool, Option<CachedKey<'de>>)> {
340        let saved_ptr = self.current_ptr;
341        let result = self.count_payload_at_current_inner();
342        self.current_ptr = saved_ptr;
343        result
344    }
345
346    // Inline the parsing body so callers that do not use raw identifiers can
347    // eliminate the cached bytes and continuation. Keep cursor restoration in
348    // the outer method so it also runs when parsing fails.
349    #[inline(always)]
350    fn count_payload_at_current_inner(&mut self) -> DecodeResult<(bool, Option<CachedKey<'de>>)> {
351        let (mut size, mut type_num) = self.size_and_type()?;
352        let mut continuation = None;
353        if type_num == TYPE_POINTER {
354            let target = self.decode_pointer(size);
355            continuation = Some(self.current_ptr);
356            self.current_ptr = target;
357            (size, type_num) = self.size_and_type()?;
358            if type_num == TYPE_POINTER {
359                return Err(self.invalid_db_error("pointer points to another pointer"));
360            }
361        }
362        if type_num == TYPE_STRING || type_num == TYPE_BYTES {
363            self.count_payload(size)?;
364            // Cache only complete string payloads. Leave malformed lengths
365            // to the requested Serde entry point so its errors and cursor
366            // restoration remain unchanged.
367            let cached = if type_num == TYPE_STRING {
368                self.current_ptr
369                    .checked_add(size)
370                    .filter(|&end| end <= self.limit)
371                    .map(|end| CachedKey {
372                        bytes: self.slice(self.current_ptr, end),
373                        continuation: continuation.unwrap_or(end),
374                    })
375            } else {
376                None
377            };
378            return Ok((true, cached));
379        }
380        Ok((false, None))
381    }
382
383    // The error constructors below are cold and never inlined. This keeps
384    // successful decode paths small.
385
386    /// Create an InvalidDatabase error with current offset context.
387    #[cold]
388    #[inline(never)]
389    fn invalid_db_error(&self, msg: &str) -> DecoderError {
390        MaxMindDbError::invalid_database_at(msg, self.current_ptr).into()
391    }
392
393    /// Create a Decoding error with current offset context.
394    #[cold]
395    #[inline(never)]
396    fn decode_error(&self, msg: &str) -> DecoderError {
397        MaxMindDbError::decoding_at(msg, self.current_ptr).into()
398    }
399
400    /// Create a ResourceLimit error with current offset context.
401    #[cold]
402    #[inline(never)]
403    fn resource_limit_error(&self, msg: &str) -> DecoderError {
404        MaxMindDbError::resource_limit_at(msg, self.current_ptr).into()
405    }
406
407    #[cold]
408    #[inline(never)]
409    fn type_mismatch(&self, label: &str, type_num: usize) -> DecoderError {
410        if type_num > usize::from(u8::MAX) {
411            self.invalid_db_error(&format!("unknown data type: {type_num}"))
412        } else {
413            self.decode_error(&format!("expected {label}, got type {type_num}"))
414        }
415    }
416
417    #[inline]
418    pub(crate) fn offset(&self) -> usize {
419        self.current_ptr
420    }
421
422    #[inline(always)]
423    fn checked_offset(&self, size: usize, label: &str) -> DecodeResult<usize> {
424        let new_offset = self.current_ptr.wrapping_add(size);
425        if new_offset < self.current_ptr || new_offset > self.limit {
426            return Err(self.invalid_db_error(&format!("{label} of size {size}")));
427        }
428        Ok(new_offset)
429    }
430
431    #[inline(always)]
432    fn slice(&self, start: usize, end: usize) -> &'de [u8] {
433        debug_assert!(start <= end);
434        debug_assert!(end <= self.limit);
435        debug_assert!(self.limit <= self.buf.len());
436        // SAFETY: `Decoder::new` sets `limit` to `buf.len()`, and the
437        // test-only `new_with_limit` asserts `limit <= buf.len()`. All callers
438        // reach this helper only after checking `end <= limit`.
439        unsafe { self.buf.get_unchecked(start..end) }
440    }
441
442    #[inline(always)]
443    fn skip_bytes(&mut self, size: usize, label: &str) -> DecodeResult<()> {
444        debug_assert!(self.current_ptr <= self.limit);
445        if size > self.limit - self.current_ptr {
446            return Err(self.invalid_db_error(&format!("{label} of size {size}")));
447        }
448        self.current_ptr += size;
449        Ok(())
450    }
451
452    #[inline(always)]
453    fn eat_byte(&mut self) -> DecodeResult<u8> {
454        if self.current_ptr >= self.limit {
455            return Err(self.invalid_db_error("unexpected end of buffer"));
456        }
457        debug_assert!(self.limit <= self.buf.len());
458        // SAFETY: The check above proves `current_ptr < limit`. `Decoder::new`
459        // sets `limit` to `buf.len()`, and the test-only `new_with_limit`
460        // asserts `limit <= buf.len()`.
461        let b = unsafe { *self.buf.get_unchecked(self.current_ptr) };
462        self.current_ptr += 1;
463        Ok(b)
464    }
465
466    #[inline(always)]
467    fn size_from_ctrl_byte(&mut self, ctrl_byte: u8, type_num: usize) -> DecodeResult<usize> {
468        let size = (ctrl_byte & 0x1f) as usize;
469        if size < 29 {
470            return Ok(size);
471        }
472        self.extended_size(size, type_num)
473    }
474
475    // Kept separate from size_from_ctrl_byte for speed. The same code written
476    // inline there made the lookup and decode benchmarks 2-10% slower.
477    #[inline(always)]
478    fn extended_size(&mut self, size: usize, type_num: usize) -> DecodeResult<usize> {
479        debug_assert!((29..=31).contains(&size));
480        // Pointers use the five bits as SSVVV, not as an extended length:
481        // sizes 29-31 are four-byte pointers whose low three bits are ignored.
482        if type_num == TYPE_POINTER {
483            return Ok(size);
484        }
485        match size {
486            29 => Ok(29_usize + self.eat_byte()? as usize),
487            30 => {
488                let b0 = self.eat_byte()? as usize;
489                let b1 = self.eat_byte()? as usize;
490                Ok(285_usize + (b0 << 8) + b1)
491            }
492            _ => {
493                let b0 = self.eat_byte()? as usize;
494                let b1 = self.eat_byte()? as usize;
495                let b2 = self.eat_byte()? as usize;
496                Ok(65_821_usize + (b0 << 16) + (b1 << 8) + b2)
497            }
498        }
499    }
500
501    // Only a hint in debug builds. See MAXIMUM_DATA_STRUCTURE_DEPTH.
502    #[cfg_attr(debug_assertions, inline)]
503    #[cfg_attr(not(debug_assertions), inline(always))]
504    fn size_and_type(&mut self) -> DecodeResult<(usize, usize)> {
505        let ctrl_byte = self.eat_byte()?;
506        let mut type_num = usize::from(ctrl_byte >> 5);
507        // Extended type: type 0 means read next byte for actual type
508        if type_num == TYPE_EXTENDED {
509            // Widen before adding so malformed bytes cannot overflow.
510            type_num = usize::from(self.eat_byte()?) + TYPE_MAP;
511        }
512        self.size_from_ctrl_byte(ctrl_byte, type_num)
513            .map(|size| (size, type_num))
514    }
515
516    fn decode_any<V: Visitor<'de>>(&mut self, visitor: V) -> DecodeResult<V::Value> {
517        self.activate_budget();
518        self.decode_any_impl::<false, V>(visitor)
519    }
520
521    fn decode_any_impl<const RAW_STRINGS: bool, V: Visitor<'de>>(
522        &mut self,
523        visitor: V,
524    ) -> DecodeResult<V::Value> {
525        match self.decode_any_value::<RAW_STRINGS>()? {
526            Value::Any { prev_ptr } => {
527                // Pointer dereference - track depth
528                self.enter_nested()?;
529                let res = self.decode_any_impl::<RAW_STRINGS, V>(visitor);
530                self.exit_nested();
531                self.current_ptr = prev_ptr;
532                res
533            }
534            Value::Bool(x) => visitor.visit_bool(x),
535            Value::Bytes(x) => visitor.visit_borrowed_bytes(x),
536            Value::String(x) => visitor.visit_borrowed_str(x),
537            Value::RawString(x) => {
538                visitor.visit_newtype_struct(BorrowedBytesDeserializer::<DecoderError>::new(x))
539            }
540            Value::I32(x) => visitor.visit_i32(x),
541            Value::U16(x) => visitor.visit_u16(x),
542            Value::U32(x) => visitor.visit_u32(x),
543            Value::U64(x) => visitor.visit_u64(x),
544            Value::U128(x) => visitor.visit_u128(x),
545            Value::F64(x) => visitor.visit_f64(x),
546            Value::F32(x) => visitor.visit_f32(x),
547            // Maps and arrays enter_nested in decode_any_value; exit when done
548            Value::Map(x) => {
549                let res = visitor.visit_map(x);
550                self.exit_nested();
551                res
552            }
553            Value::Array(x) => {
554                let res = visitor.visit_seq(x);
555                self.exit_nested();
556                res
557            }
558        }
559    }
560
561    fn deserialize_fixed_size_array<V>(&mut self, len: usize, visitor: V) -> DecodeResult<V::Value>
562    where
563        V: Visitor<'de>,
564    {
565        let (size, type_num) = self.size_and_type()?;
566        self.decode_direct(size, type_num, TYPE_ARRAY, "array", |de, size| {
567            if size != len {
568                return Err(de.decode_error(&format!(
569                    "expected tuple of length {len}, got array of length {size}"
570                )));
571            }
572
573            de.reserve_container_values(size, TYPE_ARRAY)?;
574            de.enter_nested()?;
575            let res = visitor.visit_seq(ArrayAccess { de, count: size });
576            de.exit_nested();
577            res
578        })
579    }
580
581    // Only a hint in debug builds. See MAXIMUM_DATA_STRUCTURE_DEPTH.
582    #[cfg_attr(debug_assertions, inline)]
583    #[cfg_attr(not(debug_assertions), inline(always))]
584    fn decode_any_value<const RAW_STRINGS: bool>(&mut self) -> DecodeResult<Value<'_, 'de>> {
585        let (size, type_num) = self.size_and_type()?;
586
587        Ok(match type_num {
588            TYPE_POINTER => {
589                let new_ptr = self.decode_pointer(size);
590                let prev_ptr = self.current_ptr;
591                self.current_ptr = new_ptr;
592
593                Value::Any { prev_ptr }
594            }
595            TYPE_STRING if RAW_STRINGS => {
596                self.count_payload(size)?;
597                Value::RawString(self.read_string_bytes(size)?)
598            }
599            TYPE_STRING => {
600                self.count_payload(size)?;
601                Value::String(self.decode_string(size)?)
602            }
603            TYPE_DOUBLE => Value::F64(self.decode_double(size)?),
604            TYPE_BYTES => {
605                self.count_payload(size)?;
606                Value::Bytes(self.decode_bytes(size)?)
607            }
608            TYPE_UINT16 => Value::U16(self.decode_uint16(size)?),
609            TYPE_UINT32 => Value::U32(self.decode_uint32(size)?),
610            TYPE_MAP => {
611                self.reserve_container_values(size, TYPE_MAP)?;
612                self.enter_nested()?;
613                self.decode_map(size)
614            }
615            TYPE_INT32 => Value::I32(self.decode_int(size)?),
616            TYPE_UINT64 => Value::U64(self.decode_uint64(size)?),
617            TYPE_UINT128 => Value::U128(self.decode_uint128(size)?),
618            TYPE_ARRAY => {
619                self.reserve_container_values(size, TYPE_ARRAY)?;
620                self.enter_nested()?;
621                self.decode_array(size)
622            }
623            TYPE_BOOL => Value::Bool(self.decode_bool(size)?),
624            TYPE_FLOAT => Value::F32(self.decode_float(size)?),
625            u => return Err(self.invalid_db_error(&format!("unknown data type: {u}"))),
626        })
627    }
628
629    fn decode_array(&mut self, size: usize) -> Value<'_, 'de> {
630        Value::Array(ArrayAccess {
631            de: self,
632            count: size,
633        })
634    }
635
636    fn decode_bool(&mut self, size: usize) -> DecodeResult<bool> {
637        match size {
638            0 | 1 => Ok(size != 0),
639            s => Err(self.invalid_db_error(&format!("bool of size {s}"))),
640        }
641    }
642
643    fn decode_bytes(&mut self, size: usize) -> DecodeResult<&'de [u8]> {
644        let new_offset = self.checked_offset(size, "bytes")?;
645        let u8_slice = self.slice(self.current_ptr, new_offset);
646        self.current_ptr = new_offset;
647
648        Ok(u8_slice)
649    }
650
651    fn decode_float(&mut self, size: usize) -> DecodeResult<f32> {
652        let new_offset = self.checked_offset(size, "float")?;
653        let value: [u8; 4] = self
654            .slice(self.current_ptr, new_offset)
655            .try_into()
656            .map_err(|_| self.invalid_db_error(&format!("float of size {size}")))?;
657        self.current_ptr = new_offset;
658        let float_value = f32::from_be_bytes(value);
659        Ok(float_value)
660    }
661
662    fn decode_double(&mut self, size: usize) -> DecodeResult<f64> {
663        let new_offset = self.checked_offset(size, "double")?;
664        let value: [u8; 8] = self
665            .slice(self.current_ptr, new_offset)
666            .try_into()
667            .map_err(|_| self.invalid_db_error(&format!("double of size {size}")))?;
668        self.current_ptr = new_offset;
669        let float_value = f64::from_be_bytes(value);
670        Ok(float_value)
671    }
672
673    decode_int_like!(decode_uint64, u64, 8, "u64", 0_u64);
674    decode_int_like!(decode_uint128, u128, 16, "u128", 0_u128);
675
676    #[inline(always)]
677    fn read_u32_be(&mut self, size: usize, label: &str) -> DecodeResult<u32> {
678        if size > 4 {
679            return Err(self.invalid_db_error(&format!("{label} of size {size}")));
680        }
681        let new_offset = self
682            .current_ptr
683            .checked_add(size)
684            .filter(|&offset| offset <= self.limit)
685            .ok_or_else(|| self.invalid_db_error(&format!("{label} of size {}", size)))?;
686        let p = self.current_ptr;
687        let value = match size {
688            0 => 0,
689            1 => self.buf[p] as u32,
690            2 => ((self.buf[p] as u32) << 8) | self.buf[p + 1] as u32,
691            3 => {
692                ((self.buf[p] as u32) << 16)
693                    | ((self.buf[p + 1] as u32) << 8)
694                    | self.buf[p + 2] as u32
695            }
696            _ => {
697                ((self.buf[p] as u32) << 24)
698                    | ((self.buf[p + 1] as u32) << 16)
699                    | ((self.buf[p + 2] as u32) << 8)
700                    | self.buf[p + 3] as u32
701            }
702        };
703        self.current_ptr = new_offset;
704        Ok(value)
705    }
706
707    #[inline(always)]
708    fn decode_uint32(&mut self, size: usize) -> DecodeResult<u32> {
709        self.read_u32_be(size, "u32")
710    }
711
712    #[inline(always)]
713    fn decode_uint16(&mut self, size: usize) -> DecodeResult<u16> {
714        if size > 2 {
715            return Err(self.invalid_db_error(&format!("u16 of size {size}")));
716        }
717        let new_offset = self
718            .current_ptr
719            .checked_add(size)
720            .filter(|&offset| offset <= self.limit)
721            .ok_or_else(|| self.invalid_db_error(&format!("u16 of size {}", size)))?;
722        let p = self.current_ptr;
723        let value = match size {
724            0 => 0,
725            1 => self.buf[p] as u16,
726            _ => ((self.buf[p] as u16) << 8) | self.buf[p + 1] as u16,
727        };
728        self.current_ptr = new_offset;
729        Ok(value)
730    }
731
732    fn decode_int(&mut self, size: usize) -> DecodeResult<i32> {
733        self.read_u32_be(size, "i32").map(|value| value as i32)
734    }
735
736    fn decode_map(&mut self, size: usize) -> Value<'_, 'de> {
737        Value::Map(MapAccessor {
738            de: self,
739            count: size * 2,
740        })
741    }
742
743    // Only a hint in debug builds. See MAXIMUM_DATA_STRUCTURE_DEPTH.
744    #[cfg_attr(debug_assertions, inline)]
745    #[cfg_attr(not(debug_assertions), inline(always))]
746    fn decode_pointer(&mut self, size: usize) -> usize {
747        let pointer_size = ((size >> 3) & 0x3) + 1;
748        let p = self.current_ptr;
749        let limit = self.limit;
750        let new_offset = match p.checked_add(pointer_size) {
751            Some(offset) if offset <= limit => offset,
752            _ => {
753                // Clamp to the end of the buffer so the next decode step fails
754                // with a normal bounds error instead of panicking here.
755                self.current_ptr = limit;
756                return limit;
757            }
758        };
759        let pointer_bytes = self.slice(p, new_offset);
760        self.current_ptr = new_offset;
761
762        match pointer_size {
763            1 => ((size & 0x7) << 8) | usize::from(pointer_bytes[0]),
764            2 => {
765                (((size & 0x7) << 16)
766                    | (usize::from(pointer_bytes[0]) << 8)
767                    | usize::from(pointer_bytes[1]))
768                    + 2048
769            }
770            3 => {
771                (((size & 0x7) << 24)
772                    | (usize::from(pointer_bytes[0]) << 16)
773                    | (usize::from(pointer_bytes[1]) << 8)
774                    | usize::from(pointer_bytes[2]))
775                    + 526_336
776            }
777            _ => {
778                (usize::from(pointer_bytes[0]) << 24)
779                    | (usize::from(pointer_bytes[1]) << 16)
780                    | (usize::from(pointer_bytes[2]) << 8)
781                    | usize::from(pointer_bytes[3])
782            }
783        }
784    }
785
786    #[cfg(feature = "unsafe-str-decode")]
787    #[inline(always)]
788    fn decode_string(&mut self, size: usize) -> DecodeResult<&'de str> {
789        use std::str::from_utf8_unchecked;
790
791        let new_offset = self.checked_offset(size, "string")?;
792        let bytes = self.slice(self.current_ptr, new_offset);
793        self.current_ptr = new_offset;
794        // SAFETY:
795        // A corrupt maxminddb will cause undefined behaviour.
796        // If the caller has verified the integrity of their database and trusts their upstream
797        // provider, they can opt-into the performance gains provided by this unsafe function via
798        // the `unsafe-str-decode` feature flag.
799        let v = unsafe { from_utf8_unchecked(bytes) };
800        Ok(v)
801    }
802
803    #[cfg(not(feature = "unsafe-str-decode"))]
804    #[inline(always)]
805    fn decode_string(&mut self, size: usize) -> DecodeResult<&'de str> {
806        use std::str::from_utf8;
807        use std::str::from_utf8_unchecked;
808
809        let new_offset = self.checked_offset(size, "string")?;
810        let bytes = self.slice(self.current_ptr, new_offset);
811        self.current_ptr = new_offset;
812        if is_ascii(bytes) {
813            // ASCII is valid UTF-8, so this avoids the full validator fast path.
814            // SAFETY: `is_ascii()` guarantees UTF-8 validity.
815            let v = unsafe { from_utf8_unchecked(bytes) };
816            return Ok(v);
817        }
818        match from_utf8(bytes) {
819            Ok(v) => Ok(v),
820            Err(_) => Err(self.invalid_db_error("invalid UTF-8 in string")),
821        }
822    }
823
824    // ========== Navigation methods for path decoding and verification ==========
825
826    /// Peeks at the type and size without consuming it.
827    /// Returns (size, type_num) and restores the position.
828    pub(crate) fn peek_type(&mut self) -> DecodeResult<(usize, usize)> {
829        let saved_ptr = self.current_ptr;
830        let result = self.size_and_type_following_pointers()?;
831        self.current_ptr = saved_ptr;
832        Ok(result)
833    }
834
835    /// Consumes a map or array header in one pass, following a pointer if needed.
836    pub(crate) fn consume_container_header(&mut self) -> DecodeResult<(usize, usize)> {
837        let (size, type_num) = self.size_and_type_following_pointers()?;
838        if type_num == TYPE_MAP || type_num == TYPE_ARRAY {
839            self.reserve_container_values(size, type_num)?;
840        }
841        Ok((size, type_num))
842    }
843
844    /// Gets size and type, following any pointers.
845    fn size_and_type_following_pointers(&mut self) -> DecodeResult<(usize, usize)> {
846        let (size, type_num) = self.size_and_type()?;
847        if type_num != TYPE_POINTER {
848            return Ok((size, type_num));
849        }
850
851        self.current_ptr = self.decode_pointer(size);
852        let (size, type_num) = self.size_and_type()?;
853        if type_num == TYPE_POINTER {
854            return Err(self.invalid_db_error("pointer points to another pointer"));
855        }
856
857        Ok((size, type_num))
858    }
859
860    #[inline(always)]
861    fn decode_direct<T, F>(
862        &mut self,
863        size: usize,
864        type_num: usize,
865        expected_type: usize,
866        label: &str,
867        decode: F,
868    ) -> DecodeResult<T>
869    where
870        F: FnOnce(&mut Self, usize) -> DecodeResult<T>,
871    {
872        let (size, continuation) = match type_num {
873            TYPE_POINTER => {
874                let new_ptr = self.decode_pointer(size);
875                let saved_ptr = self.current_ptr;
876                self.current_ptr = new_ptr;
877                if let Err(error) = self.enter_nested() {
878                    self.current_ptr = saved_ptr;
879                    return Err(error);
880                }
881                let header = self.size_and_type().and_then(|(size, type_num)| {
882                    if type_num == TYPE_POINTER {
883                        Err(self.invalid_db_error("pointer points to another pointer"))
884                    } else if type_num != expected_type {
885                        Err(self.type_mismatch(label, type_num))
886                    } else {
887                        Ok(size)
888                    }
889                });
890                match header {
891                    Ok(size) => (size, Some(saved_ptr)),
892                    Err(error) => {
893                        self.exit_nested();
894                        self.current_ptr = saved_ptr;
895                        return Err(error);
896                    }
897                }
898            }
899            t if t == expected_type => (size, None),
900            _ => return Err(self.type_mismatch(label, type_num)),
901        };
902        // One payload call lets visitor code inline without duplicating it
903        // for pointers and inline values.
904        let result = decode(self, size);
905        if let Some(saved_ptr) = continuation {
906            self.exit_nested();
907            self.current_ptr = saved_ptr;
908        }
909        result
910    }
911
912    #[inline(always)]
913    fn read_string_bytes(&mut self, size: usize) -> DecodeResult<&'de [u8]> {
914        let new_offset = self
915            .current_ptr
916            .checked_add(size)
917            .ok_or_else(|| self.invalid_db_error("string length exceeds buffer"))?;
918        if new_offset > self.limit {
919            return Err(self.invalid_db_error("string length exceeds buffer"));
920        }
921        let bytes = self.slice(self.current_ptr, new_offset);
922        self.current_ptr = new_offset;
923        Ok(bytes)
924    }
925
926    /// Reads a string's bytes directly, following pointers if needed.
927    /// Does NOT validate UTF-8.
928    #[inline]
929    pub(crate) fn read_str_as_bytes(&mut self) -> DecodeResult<&'de [u8]> {
930        // Keys are strings, optionally behind one pointer. Handle those
931        // headers directly, including extended lengths, without retrying a
932        // general decode for valid inline strings or wider pointers.
933        let offset = self.current_ptr;
934        let ctrl = self.eat_byte()?;
935        match usize::from(ctrl >> 5) {
936            TYPE_STRING => {
937                let size = self.size_from_ctrl_byte(ctrl, TYPE_STRING)?;
938                self.count_payload(size)?;
939                return self.read_string_bytes(size);
940            }
941            TYPE_POINTER => {
942                let target = self.decode_pointer(usize::from(ctrl & 0x1f));
943                let continuation = self.current_ptr;
944                self.current_ptr = target;
945                let ctrl = self.eat_byte()?;
946                if usize::from(ctrl >> 5) == TYPE_STRING {
947                    let size = self.size_from_ctrl_byte(ctrl, TYPE_STRING)?;
948                    let result = self
949                        .count_payload(size)
950                        .and_then(|()| self.read_string_bytes(size));
951                    self.current_ptr = continuation;
952                    return result;
953                }
954            }
955            _ => {}
956        }
957        self.current_ptr = offset;
958        self.read_str_as_bytes_slow()
959    }
960
961    // Preserve the general parser's error details and cursor behavior for
962    // unexpected types. Tests also use this as a reference for valid keys.
963    #[cold]
964    fn read_str_as_bytes_slow(&mut self) -> DecodeResult<&'de [u8]> {
965        let (size, type_num) = self.size_and_type()?;
966        match type_num {
967            TYPE_POINTER => {
968                let new_ptr = self.decode_pointer(size);
969                let saved_ptr = self.current_ptr;
970                self.current_ptr = new_ptr;
971                let (size, type_num) = self.size_and_type()?;
972                let result = if type_num == TYPE_POINTER {
973                    Err(self.invalid_db_error("pointer points to another pointer"))
974                } else if type_num == TYPE_STRING {
975                    self.count_payload(size)
976                        .and_then(|()| self.read_string_bytes(size))
977                } else {
978                    Err(self.invalid_db_error(&format!("expected string, got type {type_num}")))
979                };
980                self.current_ptr = saved_ptr;
981                result
982            }
983            TYPE_STRING => {
984                self.count_payload(size)?;
985                self.read_string_bytes(size)
986            }
987            _ => Err(self.invalid_db_error(&format!("expected string, got type {type_num}"))),
988        }
989    }
990
991    /// Fast-path identifier decoding:
992    /// - Returns `Ok(Some(bytes))` and consumes the identifier when it is a string.
993    /// - Returns `Ok(None)` and restores `current_ptr` when the next value is not a string.
994    /// - Returns `Err` for malformed pointer chains or invalid string lengths.
995    #[inline(always)]
996    fn try_read_identifier_bytes(&mut self) -> DecodeResult<Option<&'de [u8]>> {
997        let saved_ptr = self.current_ptr;
998        let (size, type_num) = self.size_and_type()?;
999        match type_num {
1000            TYPE_STRING => {
1001                self.count_identifier_payload(size)?;
1002                self.read_string_bytes(size).map(Some)
1003            }
1004            TYPE_POINTER => {
1005                let new_ptr = self.decode_pointer(size);
1006                let after_pointer = self.current_ptr;
1007                self.current_ptr = new_ptr;
1008                let (inner_size, inner_type) = self.size_and_type()?;
1009                let result = if inner_type == TYPE_POINTER {
1010                    Err(self.invalid_db_error("pointer points to another pointer"))
1011                } else if inner_type == TYPE_STRING {
1012                    let payload_result = self.count_identifier_payload(inner_size);
1013                    match payload_result {
1014                        Ok(()) => self.read_string_bytes(inner_size).map(Some),
1015                        Err(error) => Err(error),
1016                    }
1017                } else {
1018                    Ok(None)
1019                };
1020                // decode_pointer(size) temporarily dereferences by moving current_ptr
1021                // to new_ptr; after size_and_type/read_string_bytes on the pointed
1022                // value, restoring current_ptr = after_pointer resumes parsing right
1023                // after the original pointer bytes. When result is Ok(None), also
1024                // reset current_ptr = saved_ptr so the non-string identifier can be
1025                // parsed normally by the caller without consuming the pointer token.
1026                self.current_ptr = after_pointer;
1027                if matches!(result, Ok(None)) {
1028                    self.current_ptr = saved_ptr;
1029                }
1030                result
1031            }
1032            _ => {
1033                self.current_ptr = saved_ptr;
1034                Ok(None)
1035            }
1036        }
1037    }
1038
1039    /// Skips the current encoded value without expanding pointer targets.
1040    pub(crate) fn skip_value(&mut self) -> DecodeResult<()> {
1041        let (size, type_num) = self.size_and_type()?;
1042        self.skip_value_inner(size, type_num, 0)
1043    }
1044
1045    /// Skips the current value and validates any referenced pointer targets.
1046    pub(crate) fn skip_value_for_verification(
1047        &mut self,
1048        state: &mut VerificationState,
1049    ) -> DecodeResult<()> {
1050        let offset = self.current_ptr;
1051        let key = VerificationState::key(offset)?;
1052        // A root starts at depth zero, and a cached height always fits there
1053        // because it was validated at some depth of at least zero.
1054        if state.validated.contains_key(&key) {
1055            return Ok(());
1056        }
1057        if !state.active.insert(offset) {
1058            return Err(
1059                self.invalid_db_error(&format!("cyclic data pointer references offset {offset}"))
1060            );
1061        }
1062
1063        state.deepest = 0;
1064        let result: DecodeResult<usize> = (|| {
1065            let (size, type_num) = self.size_and_type()?;
1066            self.skip_value_inner_for_verification(size, type_num, 0, state)?;
1067            self.validate_skip_end()?;
1068            Ok(type_num)
1069        })();
1070
1071        state.active.remove(&offset);
1072        let type_num = result?;
1073        // A root may be a pointer, but a pointer target may not. Don't cache a
1074        // root pointer, so a later pointer to it still fails the pointer-chain
1075        // check in `verify_pointer_target`.
1076        if type_num != TYPE_POINTER {
1077            state.validated.insert(key, state.deepest);
1078        }
1079        Ok(())
1080    }
1081
1082    #[inline(always)]
1083    pub(crate) fn validate_skip_end(&mut self) -> DecodeResult<()> {
1084        if self.current_ptr > self.limit {
1085            return Err(self.invalid_db_error("skipped value extends beyond buffer"));
1086        }
1087        Ok(())
1088    }
1089
1090    #[inline(always)]
1091    fn check_skip_depth(&self, skip_depth: u16) -> DecodeResult<u16> {
1092        if skip_depth == MAXIMUM_SKIPPED_DATA_STRUCTURE_DEPTH {
1093            return self.skip_depth_error();
1094        }
1095        Ok(skip_depth + 1)
1096    }
1097
1098    #[cold]
1099    fn skip_depth_error(&self) -> DecodeResult<u16> {
1100        Self::skip_depth_error_at(self.current_ptr)
1101    }
1102
1103    #[cold]
1104    #[inline(never)]
1105    fn skip_depth_error_at<T>(offset: usize) -> DecodeResult<T> {
1106        Err(MaxMindDbError::invalid_database_at(
1107            "exceeded maximum data structure depth; database is likely corrupt",
1108            offset,
1109        )
1110        .into())
1111    }
1112
1113    #[inline(always)]
1114    fn skip_value_inner(
1115        &mut self,
1116        size: usize,
1117        type_num: usize,
1118        skip_depth: u16,
1119    ) -> DecodeResult<()> {
1120        // Headers and scalar payloads validate every cursor advance. A
1121        // successful recursive skip therefore already guarantees that the
1122        // cursor remains within the decoder limit.
1123        match type_num {
1124            TYPE_POINTER => {
1125                // The pointer token is the complete skipped value. Its target
1126                // is not materialized, so following it would only amplify work
1127                // the destination did not request. Full database verification
1128                // still validates referenced targets.
1129                let pointer_size = ((size >> 3) & 0x3) + 1;
1130                self.checked_offset(pointer_size, "pointer")?;
1131                self.decode_pointer(size);
1132                Ok(())
1133            }
1134            TYPE_STRING | TYPE_BYTES => {
1135                // String or Bytes - skip size bytes
1136                let label = if type_num == TYPE_STRING {
1137                    "string"
1138                } else {
1139                    "bytes"
1140                };
1141                self.skip_bytes(size, label)
1142            }
1143            TYPE_DOUBLE => {
1144                // Double - must be exactly 8 bytes
1145                if size != 8 {
1146                    return Err(self.invalid_db_error(&format!("double of size {size}")));
1147                }
1148                self.skip_bytes(size, "double")
1149            }
1150            TYPE_FLOAT => {
1151                // Float - must be exactly 4 bytes
1152                if size != 4 {
1153                    return Err(self.invalid_db_error(&format!("float of size {size}")));
1154                }
1155                self.skip_bytes(size, "float")
1156            }
1157            TYPE_UINT16 | TYPE_UINT32 | TYPE_INT32 | TYPE_UINT64 | TYPE_UINT128 => {
1158                // Numeric types - skip size bytes
1159                let label = match type_num {
1160                    TYPE_UINT16 => "u16",
1161                    TYPE_UINT32 => "u32",
1162                    TYPE_INT32 => "i32",
1163                    TYPE_UINT64 => "u64",
1164                    TYPE_UINT128 => "u128",
1165                    _ => unreachable!(),
1166                };
1167                let max_size = match type_num {
1168                    TYPE_UINT16 => 2,
1169                    TYPE_UINT32 | TYPE_INT32 => 4,
1170                    TYPE_UINT64 => 8,
1171                    TYPE_UINT128 => 16,
1172                    _ => unreachable!(),
1173                };
1174                if size > max_size {
1175                    return Err(self.invalid_db_error(&format!("{label} of size {size}")));
1176                }
1177                self.skip_bytes(size, label)
1178            }
1179            TYPE_BOOL => {
1180                // Boolean - size field IS the value, no data bytes to skip
1181                self.decode_bool(size).map(|_| ())
1182            }
1183            TYPE_MAP => {
1184                // Map - skip size key-value pairs
1185                self.reserve_container_values(size, TYPE_MAP)?;
1186                let child_depth = self.check_skip_depth(skip_depth)?;
1187                for _ in 0..size {
1188                    // key
1189                    self.skip_value_with_depth(child_depth)?;
1190                    // value
1191                    self.skip_value_with_depth(child_depth)?;
1192                }
1193                Ok(())
1194            }
1195            TYPE_ARRAY => {
1196                // Array - skip size elements
1197                self.reserve_container_values(size, TYPE_ARRAY)?;
1198                let child_depth = self.check_skip_depth(skip_depth)?;
1199                for _ in 0..size {
1200                    self.skip_value_with_depth(child_depth)?;
1201                }
1202                Ok(())
1203            }
1204            u => Err(self.invalid_db_error(&format!("unknown data type: {u}"))),
1205        }
1206    }
1207
1208    #[inline(always)]
1209    fn skip_value_with_depth(&mut self, skip_depth: u16) -> DecodeResult<()> {
1210        let (size, type_num) = self.size_and_type()?;
1211        self.skip_value_inner(size, type_num, skip_depth)
1212    }
1213
1214    /// Verifies the current value at `skip_depth`, raising `state.deepest` to
1215    /// the deepest skip depth the value reaches. Maps, arrays and pointers,
1216    /// even empty ones, reach one level below `skip_depth`; scalars add none.
1217    /// A verified pointer target's height is the depth it reached minus the
1218    /// depth it started at. A value at depth `d` with height `h` fits the skip
1219    /// limit exactly when `d + h <= MAXIMUM_SKIPPED_DATA_STRUCTURE_DEPTH`, so a
1220    /// cached target can be rechecked at a new depth without traversing it.
1221    fn skip_value_inner_for_verification(
1222        &mut self,
1223        size: usize,
1224        type_num: usize,
1225        skip_depth: u16,
1226        state: &mut VerificationState,
1227    ) -> DecodeResult<()> {
1228        // Charge every visited value, including inline children and pointers
1229        // to cached targets, before traversal. Headers take constant work.
1230        state.charge(1, self.current_ptr)?;
1231        match type_num {
1232            TYPE_STRING => {
1233                let end = self.checked_offset(size, "string")?;
1234                state.charge(size, self.current_ptr)?;
1235                let bytes = self.slice(self.current_ptr, end);
1236                self.current_ptr = end;
1237                std::str::from_utf8(bytes)
1238                    .map(|_| ())
1239                    .map_err(|_| self.invalid_db_error("invalid UTF-8 in string"))
1240            }
1241            TYPE_POINTER => {
1242                let target = self.decode_pointer(size);
1243                let child_depth = self.check_skip_depth(skip_depth)?;
1244                self.verify_pointer_target(target, child_depth, state)
1245            }
1246            TYPE_MAP => {
1247                let child_depth = self.check_skip_depth(skip_depth)?;
1248                state.deepest = state.deepest.max(child_depth);
1249                for _ in 0..size {
1250                    self.verify_map_key(child_depth, state)?;
1251                    self.skip_value_with_verification(child_depth, state)?;
1252                }
1253                self.validate_skip_end()
1254            }
1255            TYPE_ARRAY => {
1256                let child_depth = self.check_skip_depth(skip_depth)?;
1257                state.deepest = state.deepest.max(child_depth);
1258                for _ in 0..size {
1259                    self.skip_value_with_verification(child_depth, state)?;
1260                }
1261                self.validate_skip_end()
1262            }
1263            _ => self.skip_value_inner(size, type_num, skip_depth),
1264        }
1265    }
1266
1267    /// Verifies a map key, which must be a string, either inline or behind
1268    /// one pointer. The type is checked before any size bytes are read, so a
1269    /// non-string key reports its type even when its size is truncated.
1270    fn verify_map_key(
1271        &mut self,
1272        skip_depth: u16,
1273        state: &mut VerificationState,
1274    ) -> DecodeResult<()> {
1275        let ctrl_byte = self.eat_byte()?;
1276        let type_num = usize::from(ctrl_byte >> 5);
1277        if type_num != TYPE_STRING && type_num != TYPE_POINTER {
1278            return Err(self.map_key_ctrl_error(type_num));
1279        }
1280        let size = self.size_from_ctrl_byte(ctrl_byte, type_num)?;
1281        match type_num {
1282            TYPE_STRING => {
1283                self.skip_value_inner_for_verification(size, type_num, skip_depth, state)
1284            }
1285            // The only other type that reaches here is a pointer.
1286            _ => {
1287                state.charge(1, self.current_ptr)?;
1288                let target = self.decode_pointer(size);
1289                let child_depth = self.check_skip_depth(skip_depth)?;
1290                // Check the target's type before the cache lookup. The same
1291                // target may already be validated as a non-key value.
1292                let continuation = self.current_ptr;
1293                self.current_ptr = target;
1294                // Only the type matters here, so a string target costs one
1295                // control byte. Other targets take the cold path for the error.
1296                let checked = match self.eat_byte() {
1297                    Ok(ctrl) if usize::from(ctrl >> 5) == TYPE_STRING => Ok(()),
1298                    Ok(_) => Err(self.map_key_target_error(target, continuation)),
1299                    Err(error) => Err(error),
1300                };
1301                self.current_ptr = continuation;
1302                checked?;
1303                self.verify_pointer_target(target, child_depth, state)
1304            }
1305        }
1306    }
1307
1308    /// Builds the error for a key pointer whose target is not a string. A
1309    /// pointer chain is reported just past the target's control byte, and an
1310    /// unknown type just past its size bytes, as for value pointers, since the
1311    /// target itself is invalid.
1312    /// A known non-string type points just past the key pointer, inside the
1313    /// map that misuses a valid value as a key. Only the target's type is
1314    /// read, so a truncated size does not hide the type error. A truncated
1315    /// extended type keeps the bounds error's own offset.
1316    #[cold]
1317    #[inline(never)]
1318    fn map_key_target_error(&mut self, target: usize, continuation: usize) -> DecoderError {
1319        self.current_ptr = target;
1320        let error = match self.target_type() {
1321            Ok(TYPE_POINTER) => self.invalid_db_error("pointer points to another pointer"),
1322            Ok(type_num) if is_known_non_key_type(type_num) => {
1323                self.current_ptr = continuation;
1324                self.map_key_type_error(type_num)
1325            }
1326            // Read the size bytes too, so the error matches a value pointer
1327            // to the same target.
1328            Ok(_) => {
1329                self.current_ptr = target;
1330                match self.size_and_type() {
1331                    Ok((_, type_num)) => self.map_key_type_error(type_num),
1332                    Err(error) => error,
1333                }
1334            }
1335            Err(error) => error,
1336        };
1337        self.current_ptr = continuation;
1338        error
1339    }
1340
1341    /// Reads the type at the cursor without its size bytes.
1342    #[cold]
1343    #[inline(never)]
1344    fn target_type(&mut self) -> DecodeResult<usize> {
1345        let type_num = usize::from(self.eat_byte()? >> 5);
1346        if type_num == TYPE_EXTENDED {
1347            return Ok(usize::from(self.eat_byte()?) + TYPE_MAP);
1348        }
1349        Ok(type_num)
1350    }
1351
1352    /// Builds the error for an inline key that is neither a string nor a
1353    /// pointer, reading the extended type byte if there is one.
1354    #[cold]
1355    #[inline(never)]
1356    fn map_key_ctrl_error(&mut self, type_num: usize) -> DecoderError {
1357        if type_num != TYPE_EXTENDED {
1358            return self.map_key_type_error(type_num);
1359        }
1360        match self.eat_byte() {
1361            Ok(byte) => self.map_key_type_error(usize::from(byte) + TYPE_MAP),
1362            Err(error) => error,
1363        }
1364    }
1365
1366    #[cold]
1367    #[inline(never)]
1368    fn map_key_type_error(&self, type_num: usize) -> DecoderError {
1369        // Strings are valid keys, and pointer keys take their own path, so
1370        // neither type reaches this function.
1371        debug_assert!(type_num != TYPE_STRING && type_num != TYPE_POINTER);
1372        if is_known_non_key_type(type_num) {
1373            self.invalid_db_error(&format!("expected string map key, got type {type_num}"))
1374        } else {
1375            // Match the skip path's error for types this decoder doesn't know.
1376            self.invalid_db_error(&format!("unknown data type: {type_num}"))
1377        }
1378    }
1379
1380    fn skip_value_with_verification(
1381        &mut self,
1382        skip_depth: u16,
1383        state: &mut VerificationState,
1384    ) -> DecodeResult<()> {
1385        let (size, type_num) = self.size_and_type()?;
1386        self.skip_value_inner_for_verification(size, type_num, skip_depth, state)
1387    }
1388
1389    /// Verifies the pointer target at `skip_depth`, caching its height and
1390    /// raising `state.deepest` to the depth it reaches.
1391    fn verify_pointer_target(
1392        &mut self,
1393        target: usize,
1394        skip_depth: u16,
1395        state: &mut VerificationState,
1396    ) -> DecodeResult<()> {
1397        let key = VerificationState::key(target)?;
1398        if let Some(&height) = state.validated.get(&key) {
1399            // The target itself is valid, but it must also fit below the depth
1400            // at which this pointer reaches it. Without this check, the result
1401            // would depend on which reference verified the target first. The
1402            // cursor is already past the pointer, so report the target.
1403            let reached = u32::from(skip_depth) + u32::from(height);
1404            if reached > u32::from(MAXIMUM_SKIPPED_DATA_STRUCTURE_DEPTH) {
1405                return Self::skip_depth_error_at(target);
1406            }
1407            state.deepest = state.deepest.max(skip_depth + height);
1408            return Ok(());
1409        }
1410        if !state.active.insert(target) {
1411            return Err(
1412                self.invalid_db_error(&format!("cyclic data pointer references offset {target}"))
1413            );
1414        }
1415
1416        // Measure the target on its own, then fold its depth back into the
1417        // value that points to it.
1418        let outer_deepest = state.deepest;
1419        state.deepest = skip_depth;
1420        let continuation = self.current_ptr;
1421        self.current_ptr = target;
1422        let result = (|| {
1423            let (size, type_num) = self.size_and_type()?;
1424            if type_num == TYPE_POINTER {
1425                return Err(self.invalid_db_error("pointer points to another pointer"));
1426            }
1427            self.skip_value_inner_for_verification(size, type_num, skip_depth, state)?;
1428            self.validate_skip_end()
1429        })();
1430        self.current_ptr = continuation;
1431
1432        state.active.remove(&target);
1433        result?;
1434        state.validated.insert(key, state.deepest - skip_depth);
1435        state.deepest = state.deepest.max(outer_deepest);
1436        Ok(())
1437    }
1438}
1439
1440// Keep successful scalar and visitor results small by boxing the error.
1441// Public reader methods return the original error after decoding finishes.
1442pub(crate) type DecoderError = Box<MaxMindDbError>;
1443
1444pub type DecodeResult<T> = Result<T, DecoderError>;
1445
1446/// Deserializes any MaxMind DB value while exposing strings as raw bytes.
1447///
1448/// This helper is intended for format adapters that validate strings while
1449/// converting them to another runtime's native string type. MMDB string values
1450/// are delivered to [`Visitor::visit_newtype_struct`], which the adapter's
1451/// visitor must implement. Its nested deserializer answers every
1452/// `deserialize_*` call with [`Visitor::visit_borrowed_bytes`]; calling
1453/// [`Deserializer::deserialize_bytes`] is the conventional choice. Genuine
1454/// MMDB byte values continue to be delivered directly to
1455/// [`Visitor::visit_borrowed_bytes`], so callers can distinguish the two
1456/// types. Values decoded through this helper share the operation's expansion
1457/// budget.
1458///
1459/// Callers decoding nested maps or arrays should invoke this helper again from
1460/// the [`DeserializeSeed`] used for each nested value. Map keys can be read as
1461/// unvalidated bytes with [`Deserializer::deserialize_identifier`]. Raw-string
1462/// mode applies only to the value for which this helper is invoked. Nested
1463/// values decoded without re-invoking it silently use normal string decoding,
1464/// including the `unsafe-str-decode` behavior when that feature is enabled.
1465/// Pointers are followed transparently and preserve the selected mode.
1466///
1467/// This function has its special effect only with this crate's deserializer;
1468/// other Serde deserializers may treat the request as an ordinary newtype
1469/// struct. The adapter is responsible for ensuring strict UTF-8 validation if
1470/// malformed database strings must remain errors, as some runtimes replace
1471/// invalid sequences instead. Unlike the `unsafe-str-decode` feature, this
1472/// function itself never constructs an unvalidated Rust `str`.
1473pub fn deserialize_any_with_raw_strings<'de, D, V>(
1474    deserializer: D,
1475    visitor: V,
1476) -> Result<V::Value, D::Error>
1477where
1478    D: Deserializer<'de>,
1479    V: Visitor<'de>,
1480{
1481    deserializer.deserialize_newtype_struct(RAW_STRINGS_NEWTYPE, visitor)
1482}
1483
1484impl<'de: 'a, 'a> de::Deserializer<'de> for &'a mut Decoder<'de> {
1485    type Error = DecoderError;
1486
1487    fn deserialize_any<V>(self, visitor: V) -> DecodeResult<V::Value>
1488    where
1489        V: Visitor<'de>,
1490    {
1491        self.decode_any(visitor)
1492    }
1493
1494    fn deserialize_option<V>(self, visitor: V) -> DecodeResult<V::Value>
1495    where
1496        V: Visitor<'de>,
1497    {
1498        visitor.visit_some(self)
1499    }
1500
1501    deserialize_direct_scalar!(deserialize_bool, TYPE_BOOL, "bool", visit_bool, decode_bool);
1502
1503    deserialize_direct_scalar!(
1504        deserialize_u16,
1505        TYPE_UINT16,
1506        "u16",
1507        visit_u16,
1508        decode_uint16
1509    );
1510
1511    deserialize_direct_scalar!(
1512        deserialize_u32,
1513        TYPE_UINT32,
1514        "u32",
1515        visit_u32,
1516        decode_uint32
1517    );
1518
1519    deserialize_direct_scalar!(
1520        deserialize_u64,
1521        TYPE_UINT64,
1522        "u64",
1523        visit_u64,
1524        decode_uint64
1525    );
1526
1527    deserialize_direct_scalar!(
1528        deserialize_u128,
1529        TYPE_UINT128,
1530        "u128",
1531        visit_u128,
1532        decode_uint128
1533    );
1534
1535    deserialize_direct_scalar!(deserialize_i32, TYPE_INT32, "i32", visit_i32, decode_int);
1536
1537    deserialize_direct_scalar!(
1538        deserialize_f32,
1539        TYPE_FLOAT,
1540        "float",
1541        visit_f32,
1542        decode_float
1543    );
1544
1545    deserialize_direct_scalar!(
1546        deserialize_f64,
1547        TYPE_DOUBLE,
1548        "double",
1549        visit_f64,
1550        decode_double
1551    );
1552
1553    deserialize_direct_payload!(
1554        deserialize_str,
1555        TYPE_STRING,
1556        "string",
1557        visit_borrowed_str,
1558        decode_string
1559    );
1560
1561    fn deserialize_string<V>(self, visitor: V) -> DecodeResult<V::Value>
1562    where
1563        V: Visitor<'de>,
1564    {
1565        self.deserialize_str(visitor)
1566    }
1567
1568    deserialize_direct_payload!(
1569        deserialize_bytes,
1570        TYPE_BYTES,
1571        "bytes",
1572        visit_borrowed_bytes,
1573        decode_bytes
1574    );
1575
1576    fn deserialize_byte_buf<V>(self, visitor: V) -> DecodeResult<V::Value>
1577    where
1578        V: Visitor<'de>,
1579    {
1580        self.deserialize_bytes(visitor)
1581    }
1582
1583    fn deserialize_seq<V>(self, visitor: V) -> DecodeResult<V::Value>
1584    where
1585        V: Visitor<'de>,
1586    {
1587        let (size, type_num) = self.size_and_type()?;
1588        self.decode_direct(size, type_num, TYPE_ARRAY, "array", |de, size| {
1589            de.reserve_container_values(size, TYPE_ARRAY)?;
1590            de.enter_nested()?;
1591            let res = visitor.visit_seq(ArrayAccess { de, count: size });
1592            de.exit_nested();
1593            res
1594        })
1595    }
1596
1597    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> DecodeResult<V::Value>
1598    where
1599        V: Visitor<'de>,
1600    {
1601        self.deserialize_fixed_size_array(len, visitor)
1602    }
1603
1604    fn deserialize_tuple_struct<V>(
1605        self,
1606        _name: &'static str,
1607        len: usize,
1608        visitor: V,
1609    ) -> DecodeResult<V::Value>
1610    where
1611        V: Visitor<'de>,
1612    {
1613        self.deserialize_fixed_size_array(len, visitor)
1614    }
1615
1616    fn deserialize_map<V>(self, visitor: V) -> DecodeResult<V::Value>
1617    where
1618        V: Visitor<'de>,
1619    {
1620        self.deserialize_map_impl(visitor)
1621    }
1622
1623    fn deserialize_struct<V>(
1624        self,
1625        _name: &'static str,
1626        _fields: &'static [&'static str],
1627        visitor: V,
1628    ) -> DecodeResult<V::Value>
1629    where
1630        V: Visitor<'de>,
1631    {
1632        self.deserialize_map_impl(visitor)
1633    }
1634
1635    fn is_human_readable(&self) -> bool {
1636        false
1637    }
1638
1639    fn deserialize_ignored_any<V>(self, visitor: V) -> DecodeResult<V::Value>
1640    where
1641        V: Visitor<'de>,
1642    {
1643        self.skip_value()?;
1644        visitor.visit_unit()
1645    }
1646
1647    fn deserialize_enum<V>(
1648        self,
1649        _name: &'static str,
1650        _variants: &'static [&'static str],
1651        visitor: V,
1652    ) -> DecodeResult<V::Value>
1653    where
1654        V: Visitor<'de>,
1655    {
1656        self.activate_budget();
1657        // MMDB has no enum type. Accept the externally tagged forms that the
1658        // format can express: a map with a single entry maps a variant name
1659        // to its payload, and any other value names a unit variant. The
1660        // variant visitor decides which other values it accepts, such as a
1661        // string name or an integer index.
1662        let (_, type_num) = self.peek_type()?;
1663        match type_num {
1664            TYPE_MAP => {
1665                let (size, type_num) = self.size_and_type()?;
1666                self.decode_direct(size, type_num, TYPE_MAP, "map", |de, size| {
1667                    if size != 1 {
1668                        return Err(de.decode_error(&format!(
1669                            "expected a single-entry map for an enum variant, got a map with {size} entries"
1670                        )));
1671                    }
1672                    de.reserve_container_values(size, TYPE_MAP)?;
1673                    de.enter_nested()?;
1674                    let res = visitor.visit_enum(MapVariantAccess { de });
1675                    de.exit_nested();
1676                    res
1677                })
1678            }
1679            _ => visitor.visit_enum(UnitVariantAccess { de: self }),
1680        }
1681    }
1682
1683    fn deserialize_identifier<V>(self, visitor: V) -> DecodeResult<V::Value>
1684    where
1685        V: Visitor<'de>,
1686    {
1687        match self.try_read_identifier_bytes()? {
1688            Some(bytes) => visitor.visit_borrowed_bytes(bytes),
1689            None => self.decode_any(visitor),
1690        }
1691    }
1692
1693    fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> DecodeResult<V::Value>
1694    where
1695        V: Visitor<'de>,
1696    {
1697        if name == RAW_STRINGS_NEWTYPE {
1698            self.activate_budget();
1699            self.decode_any_impl::<true, V>(visitor)
1700        } else {
1701            self.activate_budget();
1702            visitor.visit_newtype_struct(self)
1703        }
1704    }
1705
1706    forward_to_deserialize_any! {
1707        i8 i16 i64 i128 u8 char unit unit_struct
1708    }
1709}
1710
1711impl<'de> Decoder<'de> {
1712    fn deserialize_map_impl<V>(&mut self, visitor: V) -> DecodeResult<V::Value>
1713    where
1714        V: Visitor<'de>,
1715    {
1716        let (size, type_num) = self.size_and_type()?;
1717        self.decode_direct(size, type_num, TYPE_MAP, "map", |de, size| {
1718            de.reserve_container_values(size, TYPE_MAP)?;
1719            de.enter_nested()?;
1720            let res = visitor.visit_map(MapAccessor::<false> {
1721                de,
1722                count: size * 2,
1723            });
1724            de.exit_nested();
1725            res
1726        })
1727    }
1728}
1729
1730struct ArrayAccess<'a, 'de: 'a> {
1731    de: &'a mut Decoder<'de>,
1732    count: usize,
1733}
1734
1735// `SeqAccess` is provided to the `Visitor` to give it the ability to iterate
1736// through elements of the sequence.
1737impl<'de> SeqAccess<'de> for ArrayAccess<'_, 'de> {
1738    type Error = DecoderError;
1739
1740    #[inline(always)]
1741    fn size_hint(&self) -> Option<usize> {
1742        // Never let a corrupt declared count drive an allocation larger than
1743        // the remaining encoded data can possibly fill.
1744        // Cursor advances are checked, so ordinary subtraction is sufficient.
1745        debug_assert!(self.de.current_ptr <= self.de.limit);
1746        Some(self.count.min(self.de.limit - self.de.current_ptr))
1747    }
1748
1749    fn next_element_seed<T>(&mut self, seed: T) -> DecodeResult<Option<T::Value>>
1750    where
1751        T: DeserializeSeed<'de>,
1752    {
1753        // Check if there are no more elements.
1754        if self.count == 0 {
1755            if self.de.current_ptr > self.de.limit {
1756                return Err(self
1757                    .de
1758                    .invalid_db_error("skipped value extends beyond buffer"));
1759            }
1760            return Ok(None);
1761        }
1762        self.count -= 1;
1763
1764        // Deserialize an array element.
1765        seed.deserialize(&mut *self.de).map(Some)
1766    }
1767}
1768
1769struct MapAccessor<'a, 'de: 'a, const BUDGETED: bool = false> {
1770    de: &'a mut Decoder<'de>,
1771    count: usize,
1772}
1773
1774// `MapAccess` is provided to the `Visitor` to give it the ability to iterate
1775// through entries of the map.
1776impl<'de, const BUDGETED: bool> MapAccess<'de> for MapAccessor<'_, 'de, BUDGETED> {
1777    type Error = DecoderError;
1778
1779    #[inline(always)]
1780    fn size_hint(&self) -> Option<usize> {
1781        // Each map entry needs at least one control byte for both key and value.
1782        // Cursor advances are checked, so ordinary subtraction is sufficient.
1783        debug_assert!(self.de.current_ptr <= self.de.limit);
1784        Some((self.count / 2).min((self.de.limit - self.de.current_ptr) / 2))
1785    }
1786
1787    fn next_key_seed<K>(&mut self, seed: K) -> DecodeResult<Option<K::Value>>
1788    where
1789        K: DeserializeSeed<'de>,
1790    {
1791        // Check if there are no more entries.
1792        if self.count == 0 {
1793            if self.de.current_ptr > self.de.limit {
1794                return Err(self
1795                    .de
1796                    .invalid_db_error("skipped value extends beyond buffer"));
1797            }
1798            return Ok(None);
1799        }
1800        self.count -= 1;
1801
1802        if BUDGETED {
1803            let payload_remaining_before = self.de.payload_remaining;
1804            let (payload_precharged, cached) = self.de.count_payload_at_current()?;
1805            let payload_remaining_after = self.de.payload_remaining;
1806
1807            // Let the seed perform its ordinary payload charge, while retaining
1808            // the precharge if an identifier visitor does not request one. This
1809            // avoids disabling a budget that deserialize_any can reactivate and
1810            // keeps the ordinary payload counter free of a map-key-only branch.
1811            self.de.payload_remaining = payload_remaining_before;
1812            let result = seed
1813                .deserialize(KeyDeserializer {
1814                    decoder: self.de,
1815                    cached,
1816                })
1817                .map(Some);
1818            if payload_precharged {
1819                self.de.payload_remaining = self.de.payload_remaining.min(payload_remaining_after);
1820            }
1821            return result;
1822        }
1823
1824        // Deserialize a map key.
1825        seed.deserialize(&mut *self.de).map(Some)
1826    }
1827
1828    fn next_value_seed<V>(&mut self, seed: V) -> DecodeResult<V::Value>
1829    where
1830        V: DeserializeSeed<'de>,
1831    {
1832        // Check if there are no more entries.
1833        if self.count == 0 {
1834            return Err(self.de.decode_error("no more entries"));
1835        }
1836        self.count -= 1;
1837
1838        // Deserialize a map value.
1839        seed.deserialize(&mut *self.de)
1840    }
1841}
1842
1843/// Enum access for a variant encoded as a single value, usually a string.
1844/// Only unit variants can be encoded this way; there is no payload to read.
1845struct UnitVariantAccess<'a, 'de: 'a> {
1846    de: &'a mut Decoder<'de>,
1847}
1848
1849impl<'de> de::EnumAccess<'de> for UnitVariantAccess<'_, 'de> {
1850    type Error = DecoderError;
1851    type Variant = Self;
1852
1853    fn variant_seed<V>(self, seed: V) -> DecodeResult<(V::Value, Self::Variant)>
1854    where
1855        V: DeserializeSeed<'de>,
1856    {
1857        let variant = seed.deserialize(&mut *self.de)?;
1858        Ok((variant, self))
1859    }
1860}
1861
1862impl UnitVariantAccess<'_, '_> {
1863    #[cold]
1864    #[inline(never)]
1865    fn data_variant_error(&self) -> DecoderError {
1866        self.de.decode_error(
1867            "expected a single-entry map for an enum variant with data, got a value with no payload",
1868        )
1869    }
1870}
1871
1872impl<'de> de::VariantAccess<'de> for UnitVariantAccess<'_, 'de> {
1873    type Error = DecoderError;
1874
1875    fn unit_variant(self) -> DecodeResult<()> {
1876        Ok(())
1877    }
1878
1879    fn newtype_variant_seed<T>(self, _seed: T) -> DecodeResult<T::Value>
1880    where
1881        T: DeserializeSeed<'de>,
1882    {
1883        Err(self.data_variant_error())
1884    }
1885
1886    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> DecodeResult<V::Value>
1887    where
1888        V: Visitor<'de>,
1889    {
1890        Err(self.data_variant_error())
1891    }
1892
1893    fn struct_variant<V>(
1894        self,
1895        _fields: &'static [&'static str],
1896        _visitor: V,
1897    ) -> DecodeResult<V::Value>
1898    where
1899        V: Visitor<'de>,
1900    {
1901        Err(self.data_variant_error())
1902    }
1903}
1904
1905/// Enum access for a variant encoded as a single-entry map. The key names
1906/// the variant and the value holds its payload. The caller has already
1907/// checked the entry count, reserved both values, and entered the map.
1908struct MapVariantAccess<'a, 'de: 'a> {
1909    de: &'a mut Decoder<'de>,
1910}
1911
1912impl<'de> de::EnumAccess<'de> for MapVariantAccess<'_, 'de> {
1913    type Error = DecoderError;
1914    type Variant = Self;
1915
1916    fn variant_seed<V>(self, seed: V) -> DecodeResult<(V::Value, Self::Variant)>
1917    where
1918        V: DeserializeSeed<'de>,
1919    {
1920        let variant = seed.deserialize(&mut *self.de)?;
1921        Ok((variant, self))
1922    }
1923}
1924
1925impl<'de> de::VariantAccess<'de> for MapVariantAccess<'_, 'de> {
1926    type Error = DecoderError;
1927
1928    fn unit_variant(self) -> DecodeResult<()> {
1929        // MMDB has no null to use as a unit payload. Skip whatever value is
1930        // present so a `#[serde(other)]` variant can absorb an unknown data
1931        // variant from a newer database.
1932        self.de.skip_value()
1933    }
1934
1935    fn newtype_variant_seed<T>(self, seed: T) -> DecodeResult<T::Value>
1936    where
1937        T: DeserializeSeed<'de>,
1938    {
1939        seed.deserialize(&mut *self.de)
1940    }
1941
1942    fn tuple_variant<V>(self, len: usize, visitor: V) -> DecodeResult<V::Value>
1943    where
1944        V: Visitor<'de>,
1945    {
1946        self.de.deserialize_fixed_size_array(len, visitor)
1947    }
1948
1949    fn struct_variant<V>(
1950        self,
1951        _fields: &'static [&'static str],
1952        visitor: V,
1953    ) -> DecodeResult<V::Value>
1954    where
1955        V: Visitor<'de>,
1956    {
1957        de::Deserializer::deserialize_map(&mut *self.de, visitor)
1958    }
1959}
1960
1961#[cfg(test)]
1962mod tests {
1963    use std::fmt;
1964
1965    use serde::de::{DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
1966    use serde::Deserialize;
1967
1968    use crate::{deserialize_any_with_raw_strings, MaxMindDbError, Reader};
1969
1970    use super::{DecodeResult, Decoder, VerificationState};
1971
1972    #[derive(Debug, PartialEq)]
1973    enum RawValue<'de> {
1974        String(&'de [u8]),
1975        Bytes(&'de [u8]),
1976        Bool(bool),
1977        I32(i32),
1978        U16(u16),
1979        U32(u32),
1980        U64(u64),
1981        U128(u128),
1982        F32(f32),
1983        F64(f64),
1984        Array(Vec<RawValue<'de>>),
1985        Map(Vec<(Vec<u8>, RawValue<'de>)>),
1986    }
1987
1988    impl<'de> Deserialize<'de> for RawValue<'de> {
1989        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1990        where
1991            D: Deserializer<'de>,
1992        {
1993            RawValueSeed.deserialize(deserializer)
1994        }
1995    }
1996
1997    struct RawValueSeed;
1998
1999    impl<'de> DeserializeSeed<'de> for RawValueSeed {
2000        type Value = RawValue<'de>;
2001
2002        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
2003        where
2004            D: Deserializer<'de>,
2005        {
2006            deserialize_any_with_raw_strings(deserializer, RawValueVisitor)
2007        }
2008    }
2009
2010    struct RawValueVisitor;
2011
2012    impl<'de> Visitor<'de> for RawValueVisitor {
2013        type Value = RawValue<'de>;
2014
2015        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2016            formatter.write_str("an MMDB value")
2017        }
2018
2019        fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
2020        where
2021            D: Deserializer<'de>,
2022        {
2023            deserializer.deserialize_bytes(RawStringVisitor)
2024        }
2025
2026        fn visit_borrowed_bytes<E>(self, bytes: &'de [u8]) -> Result<Self::Value, E> {
2027            Ok(RawValue::Bytes(bytes))
2028        }
2029
2030        fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
2031            Ok(RawValue::Bool(value))
2032        }
2033
2034        fn visit_i32<E>(self, value: i32) -> Result<Self::Value, E> {
2035            Ok(RawValue::I32(value))
2036        }
2037
2038        fn visit_u16<E>(self, value: u16) -> Result<Self::Value, E> {
2039            Ok(RawValue::U16(value))
2040        }
2041
2042        fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E> {
2043            Ok(RawValue::U32(value))
2044        }
2045
2046        fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
2047            Ok(RawValue::U64(value))
2048        }
2049
2050        fn visit_u128<E>(self, value: u128) -> Result<Self::Value, E> {
2051            Ok(RawValue::U128(value))
2052        }
2053
2054        fn visit_f32<E>(self, value: f32) -> Result<Self::Value, E> {
2055            Ok(RawValue::F32(value))
2056        }
2057
2058        fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> {
2059            Ok(RawValue::F64(value))
2060        }
2061
2062        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2063        where
2064            A: MapAccess<'de>,
2065        {
2066            let mut entries = Vec::with_capacity(map.size_hint().unwrap_or(0));
2067            while let Some(key) = map.next_key_seed(RawIdentifierSeed)? {
2068                let value = map.next_value_seed(RawValueSeed)?;
2069                entries.push((key, value));
2070            }
2071            Ok(RawValue::Map(entries))
2072        }
2073
2074        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
2075        where
2076            A: SeqAccess<'de>,
2077        {
2078            let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or(0));
2079            while let Some(value) = sequence.next_element_seed(RawValueSeed)? {
2080                values.push(value);
2081            }
2082            Ok(RawValue::Array(values))
2083        }
2084    }
2085
2086    struct RawStringVisitor;
2087
2088    impl<'de> Visitor<'de> for RawStringVisitor {
2089        type Value = RawValue<'de>;
2090
2091        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2092            formatter.write_str("borrowed MMDB string bytes")
2093        }
2094
2095        fn visit_borrowed_bytes<E>(self, bytes: &'de [u8]) -> Result<Self::Value, E> {
2096            Ok(RawValue::String(bytes))
2097        }
2098    }
2099
2100    #[derive(Clone, Copy)]
2101    struct RawIdentifierSeed;
2102
2103    impl<'de> DeserializeSeed<'de> for RawIdentifierSeed {
2104        type Value = Vec<u8>;
2105
2106        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
2107        where
2108            D: Deserializer<'de>,
2109        {
2110            deserializer.deserialize_identifier(RawIdentifierVisitor)
2111        }
2112    }
2113
2114    struct RawIdentifierVisitor;
2115
2116    impl<'de> Visitor<'de> for RawIdentifierVisitor {
2117        type Value = Vec<u8>;
2118
2119        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2120            formatter.write_str("borrowed MMDB map-key bytes")
2121        }
2122
2123        fn visit_borrowed_bytes<E>(self, bytes: &'de [u8]) -> Result<Self::Value, E> {
2124            Ok(bytes.to_vec())
2125        }
2126    }
2127
2128    struct AnyIdentifierSeed;
2129
2130    impl<'de> DeserializeSeed<'de> for AnyIdentifierSeed {
2131        type Value = usize;
2132
2133        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
2134        where
2135            D: Deserializer<'de>,
2136        {
2137            deserializer.deserialize_any(AnyIdentifierVisitor)
2138        }
2139    }
2140
2141    struct AnyIdentifierVisitor;
2142
2143    impl<'de> Visitor<'de> for AnyIdentifierVisitor {
2144        type Value = usize;
2145
2146        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2147            formatter.write_str("an MMDB map key")
2148        }
2149
2150        fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E> {
2151            Ok(value.len())
2152        }
2153
2154        fn visit_borrowed_bytes<E>(self, value: &'de [u8]) -> Result<Self::Value, E> {
2155            Ok(value.len())
2156        }
2157    }
2158
2159    #[derive(Debug, PartialEq)]
2160    struct AnyKeyMap(usize);
2161
2162    struct AnyKeyMapVisitor;
2163
2164    impl<'de> Visitor<'de> for AnyKeyMapVisitor {
2165        type Value = AnyKeyMap;
2166
2167        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2168            formatter.write_str("an MMDB map")
2169        }
2170
2171        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2172        where
2173            A: MapAccess<'de>,
2174        {
2175            let mut count = 0;
2176            while let Some(key_size) = map.next_key_seed(AnyIdentifierSeed)? {
2177                assert_eq!(key_size, 4096);
2178                map.next_value::<serde::de::IgnoredAny>()?;
2179                count += 1;
2180            }
2181            Ok(AnyKeyMap(count))
2182        }
2183    }
2184
2185    #[allow(dead_code)]
2186    #[derive(Debug)]
2187    struct OwnedBytes(Vec<u8>);
2188
2189    impl<'de> Deserialize<'de> for OwnedBytes {
2190        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2191        where
2192            D: Deserializer<'de>,
2193        {
2194            deserializer.deserialize_byte_buf(OwnedBytesVisitor)
2195        }
2196    }
2197
2198    struct OwnedBytesVisitor;
2199
2200    impl<'de> Visitor<'de> for OwnedBytesVisitor {
2201        type Value = OwnedBytes;
2202
2203        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2204            formatter.write_str("an MMDB byte value")
2205        }
2206
2207        fn visit_borrowed_bytes<E>(self, value: &'de [u8]) -> Result<Self::Value, E> {
2208            Ok(OwnedBytes(value.to_vec()))
2209        }
2210
2211        fn visit_byte_buf<E>(self, value: Vec<u8>) -> Result<Self::Value, E> {
2212            Ok(OwnedBytes(value))
2213        }
2214    }
2215
2216    #[test]
2217    fn raw_string_mode_distinguishes_strings_from_bytes() {
2218        let mut string_decoder = Decoder::new(&[0x42, 0xff, 0xfe], 0);
2219        let string = RawValueSeed.deserialize(&mut string_decoder).unwrap();
2220        assert_eq!(string, RawValue::String(&[0xff, 0xfe]));
2221
2222        let mut bytes_decoder = Decoder::new(&[0x82, 0xff, 0xfe], 0);
2223        let bytes = RawValueSeed.deserialize(&mut bytes_decoder).unwrap();
2224        assert_eq!(bytes, RawValue::Bytes(&[0xff, 0xfe]));
2225    }
2226
2227    #[test]
2228    fn raw_string_mode_recurses_through_maps() {
2229        let encoded = [
2230            0x02, 0x00, // map with two entries
2231            0x44, b't', b'e', b'x', b't', // "text"
2232            0x41, 0xff, // invalid UTF-8 string value
2233            0x44, b'b', b'l', b'o', b'b', // "blob"
2234            0x81, 0xff, // byte value
2235        ];
2236        let mut decoder = Decoder::new(&encoded, 0);
2237
2238        let value = RawValueSeed.deserialize(&mut decoder).unwrap();
2239
2240        assert_eq!(
2241            value,
2242            RawValue::Map(vec![
2243                (b"text".to_vec(), RawValue::String(&[0xff])),
2244                (b"blob".to_vec(), RawValue::Bytes(&[0xff])),
2245            ])
2246        );
2247    }
2248
2249    #[test]
2250    fn raw_string_mode_recurses_through_arrays_and_pointers() {
2251        let encoded_array = [
2252            0x02, 0x04, // array with two elements
2253            0x41, 0xff, // invalid UTF-8 string value
2254            0x81, 0xff, // byte value
2255        ];
2256        let mut array_decoder = Decoder::new(&encoded_array, 0);
2257        let array = RawValueSeed.deserialize(&mut array_decoder).unwrap();
2258        assert_eq!(
2259            array,
2260            RawValue::Array(vec![RawValue::String(&[0xff]), RawValue::Bytes(&[0xff]),])
2261        );
2262
2263        let encoded_pointer = [
2264            0x20, 0x02, // pointer to offset two
2265            0x41, 0xff, // invalid UTF-8 string value
2266        ];
2267        let mut pointer_decoder = Decoder::new(&encoded_pointer, 0);
2268        let pointer = RawValueSeed.deserialize(&mut pointer_decoder).unwrap();
2269        assert_eq!(pointer, RawValue::String(&[0xff]));
2270    }
2271
2272    #[test]
2273    fn raw_string_mode_restores_pointer_continuation_in_maps() {
2274        let encoded = [
2275            0x02, 0x00, // map with two entries
2276            0x41, b'a', // "a"
2277            0x20, 0x0a, // pointer to the string at offset ten
2278            0x41, b'b', // "b"
2279            0x41, b'y', // "y"
2280            0x41, b'x', // pointed-to string "x"
2281        ];
2282        let mut decoder = Decoder::new(&encoded, 0);
2283
2284        let value = RawValueSeed.deserialize(&mut decoder).unwrap();
2285
2286        assert_eq!(
2287            value,
2288            RawValue::Map(vec![
2289                (b"a".to_vec(), RawValue::String(b"x")),
2290                (b"b".to_vec(), RawValue::String(b"y")),
2291            ])
2292        );
2293    }
2294
2295    #[test]
2296    fn raw_string_mode_decodes_all_scalar_types() {
2297        let mut encoded = vec![0x08, 0x00]; // map with eight entries
2298
2299        encoded.extend_from_slice(&[0x41, b'd', 0x68]);
2300        encoded.extend_from_slice(&1.5_f64.to_be_bytes());
2301        encoded.extend_from_slice(&[0x41, b's', 0xa2, 0x01, 0x02]);
2302        encoded.extend_from_slice(&[0x41, b'i', 0xc4, 0x01, 0x02, 0x03, 0x04]);
2303        encoded.extend_from_slice(&[0x41, b'n', 0x04, 0x01]);
2304        encoded.extend_from_slice(&(-2_i32).to_be_bytes());
2305        encoded.extend_from_slice(&[0x41, b'l', 0x08, 0x02]);
2306        encoded.extend_from_slice(&0x0102_0304_0506_0708_u64.to_be_bytes());
2307        encoded.extend_from_slice(&[0x41, b'x', 0x10, 0x03]);
2308        encoded.extend_from_slice(&0x0102_0304_0506_0708_1112_1314_1516_1718_u128.to_be_bytes());
2309        encoded.extend_from_slice(&[0x41, b'b', 0x01, 0x07]);
2310        encoded.extend_from_slice(&[0x41, b'f', 0x04, 0x08]);
2311        encoded.extend_from_slice(&2.5_f32.to_be_bytes());
2312
2313        let mut decoder = Decoder::new(&encoded, 0);
2314        let value = RawValueSeed.deserialize(&mut decoder).unwrap();
2315
2316        assert_eq!(
2317            value,
2318            RawValue::Map(vec![
2319                (b"d".to_vec(), RawValue::F64(1.5)),
2320                (b"s".to_vec(), RawValue::U16(0x0102)),
2321                (b"i".to_vec(), RawValue::U32(0x0102_0304)),
2322                (b"n".to_vec(), RawValue::I32(-2)),
2323                (b"l".to_vec(), RawValue::U64(0x0102_0304_0506_0708)),
2324                (
2325                    b"x".to_vec(),
2326                    RawValue::U128(0x0102_0304_0506_0708_1112_1314_1516_1718)
2327                ),
2328                (b"b".to_vec(), RawValue::Bool(true)),
2329                (b"f".to_vec(), RawValue::F32(2.5)),
2330            ])
2331        );
2332    }
2333
2334    #[test]
2335    fn raw_string_mode_rejects_excessive_pointer_depth_and_unknown_types() {
2336        run_on_bounded_stack(|| {
2337            let mut cyclic_decoder = Decoder::new(&[0x20, 0x00], 0);
2338            let depth_err = RawValueSeed.deserialize(&mut cyclic_decoder).unwrap_err();
2339            assert!(depth_err
2340                .to_string()
2341                .contains("exceeded maximum data structure depth"));
2342        });
2343
2344        let mut unknown_decoder = Decoder::new(&[0x00, 0x06], 0);
2345        let type_err = RawValueSeed.deserialize(&mut unknown_decoder).unwrap_err();
2346        assert!(type_err.to_string().contains("unknown data type: 13"));
2347    }
2348
2349    #[test]
2350    fn malformed_extended_types_return_errors_instead_of_overflowing() {
2351        for extended_type in 249..=u8::MAX {
2352            let encoded = [0x00, extended_type];
2353            let mut decoder = Decoder::new(&encoded, 0);
2354            let error = RawValueSeed.deserialize(&mut decoder).unwrap_err();
2355
2356            assert!(matches!(*error, MaxMindDbError::InvalidDatabase { .. }));
2357            assert!(error.to_string().contains(&format!(
2358                "unknown data type: {}",
2359                u16::from(extended_type) + 7
2360            )));
2361
2362            let mut typed_decoder = Decoder::new(&encoded, 0);
2363            let typed_error =
2364                <u32 as serde::Deserialize>::deserialize(&mut typed_decoder).unwrap_err();
2365            assert!(matches!(
2366                *typed_error,
2367                MaxMindDbError::InvalidDatabase { .. }
2368            ));
2369        }
2370    }
2371
2372    #[test]
2373    fn nested_values_without_raw_opt_in_use_normal_string_decoding() {
2374        struct NestedNormalVisitor;
2375
2376        impl<'de> Visitor<'de> for NestedNormalVisitor {
2377            type Value = &'de str;
2378
2379            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2380                formatter.write_str("an MMDB map containing a string")
2381            }
2382
2383            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2384            where
2385                A: MapAccess<'de>,
2386            {
2387                let Some(_key) = map.next_key_seed(RawIdentifierSeed)? else {
2388                    return Err(serde::de::Error::custom("expected one map entry"));
2389                };
2390                map.next_value::<&'de str>()
2391            }
2392        }
2393
2394        let encoded = [
2395            0x01, 0x00, // map with one entry
2396            0x41, b'k', // "k"
2397            0x45, b'h', b'e', b'l', b'l', b'o', // "hello"
2398        ];
2399        let mut decoder = Decoder::new(&encoded, 0);
2400        let value = deserialize_any_with_raw_strings(&mut decoder, NestedNormalVisitor).unwrap();
2401
2402        assert_eq!(value, "hello");
2403    }
2404
2405    fn raw_map_value<'value, 'de>(
2406        value: &'value RawValue<'de>,
2407        key: &[u8],
2408    ) -> &'value RawValue<'de> {
2409        let RawValue::Map(entries) = value else {
2410            panic!("expected map, got {value:?}");
2411        };
2412        entries
2413            .iter()
2414            .find_map(|(entry_key, value)| (entry_key == key).then_some(value))
2415            .unwrap_or_else(|| panic!("missing map key {:?}", String::from_utf8_lossy(key)))
2416    }
2417
2418    #[test]
2419    fn raw_string_mode_decodes_reader_lookup_results() {
2420        let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
2421        let lookup = reader.lookup("89.160.20.128".parse().unwrap()).unwrap();
2422        let value = lookup.decode::<RawValue<'_>>().unwrap().unwrap();
2423
2424        let city = raw_map_value(&value, b"city");
2425        let city_names = raw_map_value(city, b"names");
2426        assert_eq!(
2427            raw_map_value(city_names, b"en"),
2428            &RawValue::String("Linköping".as_bytes())
2429        );
2430
2431        let country = raw_map_value(&value, b"country");
2432        assert_eq!(
2433            raw_map_value(country, b"is_in_european_union"),
2434            &RawValue::Bool(true)
2435        );
2436
2437        let location = raw_map_value(&value, b"location");
2438        assert_eq!(
2439            raw_map_value(location, b"accuracy_radius"),
2440            &RawValue::U16(76)
2441        );
2442        assert_eq!(
2443            raw_map_value(location, b"latitude"),
2444            &RawValue::F64(58.4167)
2445        );
2446
2447        let subdivisions = raw_map_value(&value, b"subdivisions");
2448        let RawValue::Array(subdivisions) = subdivisions else {
2449            panic!("expected subdivisions array, got {subdivisions:?}");
2450        };
2451        assert!(!subdivisions.is_empty());
2452    }
2453
2454    #[test]
2455    fn ordinary_string_decoding_remains_validated() {
2456        // The old handwritten visitor accepted visit_borrowed_str directly
2457        // and hid the missing visit_newtype_struct callback.
2458        #[derive(Debug, Deserialize, PartialEq)]
2459        struct Ordinary<'a>(&'a str);
2460
2461        #[derive(Debug, Deserialize, PartialEq)]
2462        struct Owned(String);
2463
2464        let mut valid_decoder = Decoder::new(&[0x45, b'h', b'e', b'l', b'l', b'o'], 0);
2465        assert_eq!(String::deserialize(&mut valid_decoder).unwrap(), "hello");
2466
2467        let mut newtype_decoder = Decoder::new(&[0x45, b'h', b'e', b'l', b'l', b'o'], 0);
2468        assert_eq!(
2469            Ordinary::deserialize(&mut newtype_decoder).unwrap(),
2470            Ordinary("hello")
2471        );
2472
2473        let mut owned_decoder = Decoder::new(&[0x45, b'h', b'e', b'l', b'l', b'o'], 0);
2474        assert_eq!(
2475            Owned::deserialize(&mut owned_decoder).unwrap(),
2476            Owned("hello".to_owned())
2477        );
2478
2479        #[cfg(not(feature = "unsafe-str-decode"))]
2480        {
2481            let mut invalid_decoder = Decoder::new(&[0x41, 0xff], 0);
2482            let err = String::deserialize(&mut invalid_decoder).unwrap_err();
2483            assert!(err.to_string().contains("invalid UTF-8"));
2484
2485            let mut invalid_decoder = Decoder::new(&[0x41, 0xff], 0);
2486            let err = Ordinary::deserialize(&mut invalid_decoder).unwrap_err();
2487            assert!(err.to_string().contains("invalid UTF-8"));
2488
2489            let mut invalid_decoder = Decoder::new(&[0x41, 0xff], 0);
2490            let err = Owned::deserialize(&mut invalid_decoder).unwrap_err();
2491            assert!(err.to_string().contains("invalid UTF-8"));
2492        }
2493    }
2494
2495    #[test]
2496    fn test_decoder_accepts_tuple_with_matching_length() {
2497        #[derive(Debug, serde::Deserialize)]
2498        struct TupleRecord {
2499            array: (u32, u32, u32),
2500        }
2501
2502        #[derive(Debug, serde::Deserialize)]
2503        struct TupleStructRecord {
2504            array: TupleStruct,
2505        }
2506
2507        #[derive(Debug, serde::Deserialize)]
2508        struct TupleStruct(u32, u32, u32);
2509
2510        let reader =
2511            Reader::open_readfile("test-data/test-data/MaxMind-DB-test-decoder.mmdb").unwrap();
2512        let lookup = reader.lookup("1.1.1.0".parse().unwrap()).unwrap();
2513
2514        let tuple = lookup.decode::<TupleRecord>().unwrap().unwrap();
2515        assert_eq!(tuple.array, (1, 2, 3));
2516
2517        let tuple_struct = lookup.decode::<TupleStructRecord>().unwrap().unwrap();
2518        assert_eq!(tuple_struct.array.0, 1);
2519        assert_eq!(tuple_struct.array.1, 2);
2520        assert_eq!(tuple_struct.array.2, 3);
2521    }
2522
2523    #[test]
2524    fn test_decoder_rejects_tuple_length_mismatch() {
2525        #[allow(dead_code)]
2526        #[derive(Debug, serde::Deserialize)]
2527        struct TupleRecord {
2528            array: (u32, u32),
2529        }
2530
2531        #[allow(dead_code)]
2532        #[derive(Debug, serde::Deserialize)]
2533        struct TupleStructRecord {
2534            array: TupleStruct,
2535        }
2536
2537        #[allow(dead_code)]
2538        #[derive(Debug, serde::Deserialize)]
2539        struct TupleStruct(u32, u32);
2540
2541        let reader =
2542            Reader::open_readfile("test-data/test-data/MaxMind-DB-test-decoder.mmdb").unwrap();
2543        let lookup = reader.lookup("1.1.1.0".parse().unwrap()).unwrap();
2544
2545        let tuple_err = lookup.decode::<TupleRecord>().unwrap_err();
2546        assert!(tuple_err
2547            .to_string()
2548            .contains("expected tuple of length 2, got array of length 3"));
2549
2550        let tuple_struct_err = lookup.decode::<TupleStructRecord>().unwrap_err();
2551        assert!(tuple_struct_err
2552            .to_string()
2553            .contains("expected tuple of length 2, got array of length 3"));
2554    }
2555
2556    #[test]
2557    fn test_skip_value_for_verification_rejects_truncated_pointer_payload() {
2558        let mut decoder = Decoder::new(&[0x28], 0);
2559        let err = decoder
2560            .skip_value_for_verification(&mut VerificationState::new(decoder.limit))
2561            .unwrap_err();
2562
2563        assert!(matches!(*err, MaxMindDbError::InvalidDatabase { .. }));
2564    }
2565
2566    #[test]
2567    fn four_byte_pointers_ignore_low_control_bits() {
2568        for ctrl_byte in 0x38..=0x3f {
2569            let buf = [
2570                ctrl_byte, 0, 0, 0, 7, // four-byte pointer to offset seven
2571                0xa1, 42, // next inline uint16
2572                0xa1, 99, // pointed-to uint16
2573            ];
2574            let mut decoder = Decoder::new(&buf, 0);
2575            assert_eq!(u16::deserialize(&mut decoder).unwrap(), 99);
2576            assert_eq!(decoder.offset(), 5);
2577            assert_eq!(u16::deserialize(&mut decoder).unwrap(), 42);
2578
2579            let mut decoder = Decoder::new(&buf, 0);
2580            assert_eq!(serde_json::Value::deserialize(&mut decoder).unwrap(), 99);
2581            assert_eq!(decoder.offset(), 5);
2582        }
2583    }
2584
2585    #[test]
2586    fn four_byte_pointers_ignore_low_control_bits_in_keys_and_skips() {
2587        #[derive(Deserialize)]
2588        struct Record {
2589            a: u16,
2590        }
2591
2592        for ctrl_byte in 0x38..=0x3f {
2593            let buf = [
2594                0xe2, // map with two entries
2595                ctrl_byte, 0, 0, 0, 15, // key: four-byte pointer to "a"
2596                0xa1, 42, // value: inline uint16
2597                0x41, b'x', // key: inline "x"
2598                ctrl_byte, 0, 0, 0, 17, // value: four-byte pointer to uint16
2599                0x41, b'a', // offset 15
2600                0xa1, 99, // offset 17
2601            ];
2602
2603            // Map keys go through try_read_identifier_bytes, and the unknown
2604            // field "x" goes through skip_value.
2605            let mut decoder = Decoder::new(&buf, 0);
2606            assert_eq!(Record::deserialize(&mut decoder).unwrap().a, 42);
2607            assert_eq!(decoder.offset(), 15);
2608
2609            let mut decoder = Decoder::new(&buf, 1);
2610            let (charged, cached) = decoder.count_payload_at_current().unwrap();
2611            assert!(charged);
2612            let cached = cached.unwrap();
2613            assert_eq!(cached.bytes, b"a");
2614            assert_eq!(cached.continuation, 6);
2615            assert_eq!(decoder.offset(), 1);
2616
2617            let mut decoder = Decoder::new(&buf, 0);
2618            decoder
2619                .skip_value_for_verification(&mut VerificationState::new(decoder.limit))
2620                .unwrap();
2621            assert_eq!(decoder.offset(), 15);
2622        }
2623    }
2624
2625    #[test]
2626    fn pointer_widths_preserve_offsets_and_decoder_limits() {
2627        let cases: &[(usize, &[u8], usize)] = &[
2628            (0x00, &[0x00], 0),
2629            (0x07, &[0xff], 2_047),
2630            (0x08, &[0x00, 0x00], 2_048),
2631            (0x0f, &[0xff, 0xff], 526_335),
2632            (0x10, &[0x00, 0x00, 0x00], 526_336),
2633            (0x10, &[0x01, 0x02, 0x03], 592_387),
2634            (0x17, &[0xff, 0xff, 0xff], 134_744_063),
2635            (0x18, &[0x00, 0x00, 0x00, 0x00], 0),
2636            (0x1f, &[0xff, 0xff, 0xff, 0xff], 4_294_967_295),
2637        ];
2638        for &(size, payload, target) in cases {
2639            let mut buf = vec![0];
2640            buf.extend_from_slice(payload);
2641            let continuation = buf.len();
2642            buf.extend([0xa1, 42]);
2643            let mut decoder = Decoder::new(&buf, 1);
2644            assert_eq!(decoder.decode_pointer(size), target);
2645            assert_eq!(decoder.offset(), continuation);
2646            assert_eq!(u16::deserialize(&mut decoder).unwrap(), 42);
2647
2648            for limit in 1..continuation {
2649                let mut decoder = Decoder::new_with_limit(&buf, 1, limit);
2650                assert_eq!(decoder.decode_pointer(size), limit);
2651                assert_eq!(decoder.offset(), limit);
2652                assert!(u16::deserialize(&mut decoder).is_err());
2653            }
2654        }
2655    }
2656
2657    fn compare_key_decoders(buf: &[u8], start: usize, limit: usize, remaining: u32) {
2658        for budgeted in [false, true] {
2659            let mut fast = Decoder::new_with_limit(buf, start, limit);
2660            let mut general = Decoder::new_with_limit(buf, start, limit);
2661            if budgeted {
2662                fast.activate_budget();
2663                general.activate_budget();
2664            }
2665            fast.payload_remaining = remaining;
2666            general.payload_remaining = remaining;
2667            let actual = fast.read_str_as_bytes().map_err(|e| format!("{e:?}"));
2668            let expected = general
2669                .read_str_as_bytes_slow()
2670                .map_err(|e| format!("{e:?}"));
2671            assert_eq!(
2672                actual, expected,
2673                "start={start}, limit={limit}, remaining={remaining}, budgeted={budgeted}"
2674            );
2675            assert_eq!(fast.current_ptr, general.current_ptr);
2676            assert_eq!(fast.state, general.state);
2677            assert_eq!(fast.payload_remaining, general.payload_remaining);
2678        }
2679    }
2680
2681    #[test]
2682    #[cfg_attr(miri, ignore = "too slow under Miri")]
2683    fn key_decoding_preserves_values_errors_cursors_and_budgets() {
2684        let mut buf = [0x61; 80];
2685        buf[..2].copy_from_slice(&[0x20, 10]);
2686        for control in 0..=255 {
2687            buf[10] = control;
2688            for limit in 0..=buf.len() {
2689                for remaining in [0, 1, 2, 28, 29, 4096] {
2690                    compare_key_decoders(&buf, 0, limit, remaining);
2691                    compare_key_decoders(&buf, 10, limit, remaining);
2692                }
2693            }
2694        }
2695
2696        for pointer in 0..2048 {
2697            let mut buf = [0x61; 2112];
2698            buf[2080..2082].copy_from_slice(&[0x20 | ((pointer >> 8) as u8), pointer as u8]);
2699            // Raw keys need not be valid UTF-8. Keep the pointer token after
2700            // every possible target so it cannot overlap the string payload.
2701            buf[pointer..pointer + 3].copy_from_slice(&[0x42, 0xFF, 0xFE]);
2702            compare_key_decoders(&buf, 2080, buf.len(), 1);
2703            compare_key_decoders(&buf, 2080, buf.len(), 2);
2704        }
2705    }
2706
2707    // Kept out of the exhaustive test above so Miri still checks the
2708    // unchecked reads at the buffer edges, on fewer random buffers.
2709    #[test]
2710    fn key_decoding_preserves_edge_cursors_on_random_buffers() {
2711        let rounds = if cfg!(miri) { 4 } else { 8192 };
2712        let mut buf = [0; 80];
2713        let mut state = 0x4D59_5DF4_D0F3_3173_u64;
2714        for _ in 0..rounds {
2715            for byte in &mut buf {
2716                state = state
2717                    .wrapping_mul(6_364_136_223_846_793_005)
2718                    .wrapping_add(1_442_695_040_888_963_407);
2719                *byte = (state >> 32) as u8;
2720            }
2721            for start in [0, 1, 10, 79, 80, usize::MAX] {
2722                compare_key_decoders(&buf, start, buf.len(), 0);
2723                compare_key_decoders(&buf, start, buf.len(), 4096);
2724            }
2725        }
2726    }
2727
2728    // Each control byte as the last or second-to-last byte, where a read past
2729    // the limit would leave the buffer. Small enough to run under Miri.
2730    #[test]
2731    fn key_decoding_handles_every_control_byte_at_the_buffer_end() {
2732        let mut buf = [0x61; 80];
2733        for control in 0..=255 {
2734            for start in [78, 79] {
2735                buf[start] = control;
2736                compare_key_decoders(&buf, start, buf.len(), 4096);
2737                buf[start] = 0x61;
2738            }
2739        }
2740    }
2741
2742    #[test]
2743    #[cfg_attr(miri, ignore = "too slow under Miri")]
2744    fn key_decoders_agree_on_pointer_widths_and_extended_strings() {
2745        let pointers: &[(&[u8], usize)] = &[
2746            (&[0x20, 8], 8),
2747            (&[0x28, 0, 0], 2048),
2748            (&[0x30, 0, 0, 0], 526_336),
2749            (&[0x38, 0, 0, 0, 8], 8),
2750        ];
2751        for &(pointer, target) in pointers {
2752            for size in [0, 1, 28, 29, 285] {
2753                let mut buf = pointer.to_vec();
2754                buf.resize(target, 0);
2755                match size {
2756                    0..=28 => buf.push(0x40 | size as u8),
2757                    29 => buf.extend_from_slice(&[0x5D, 0]),
2758                    285 => buf.extend_from_slice(&[0x5E, 0, 0]),
2759                    _ => unreachable!(),
2760                }
2761                buf.resize(buf.len() + size, b'k');
2762                for limit in [pointer.len() - 1, target, buf.len() - 1, buf.len()] {
2763                    for remaining in [0, 28, 4096] {
2764                        compare_key_decoders(&buf, 0, limit, remaining);
2765                    }
2766                }
2767            }
2768        }
2769    }
2770
2771    #[test]
2772    fn typed_pointer_errors_restore_continuation_and_depth() {
2773        let targets: &[&[u8]] = &[
2774            &[],           // Missing target header.
2775            &[0x5d],       // Truncated extended string length.
2776            &[0xc0],       // Wrong type: uint32 instead of string.
2777            &[0x20, 0],    // Pointer to another pointer.
2778            &[0x41],       // Truncated string payload.
2779            &[0x41, b'x'], // Valid string.
2780        ];
2781        for &target in targets {
2782            let mut buf = vec![0x20, 4, 0xa1, 42];
2783            buf.extend_from_slice(target);
2784            let mut decoder = Decoder::new(&buf, 0);
2785            let result = <&str>::deserialize(&mut decoder);
2786            if target == [0x41, b'x'] {
2787                assert_eq!(result.unwrap(), "x");
2788            } else {
2789                assert!(result.is_err());
2790            }
2791            assert_eq!(decoder.offset(), 2);
2792            assert_eq!(decoder.state & super::DEPTH_MASK, 0);
2793            assert_eq!(u16::deserialize(&mut decoder).unwrap(), 42);
2794        }
2795    }
2796
2797    #[test]
2798    fn typed_pointer_depth_limit_restores_continuation() {
2799        let buf = [0x20, 4, 0xa1, 42, 0x41, b'x'];
2800        let mut decoder = Decoder::new(&buf, 0);
2801        for _ in 0..super::MAXIMUM_DATA_STRUCTURE_DEPTH {
2802            decoder.enter_nested().unwrap();
2803        }
2804
2805        let error = <&str>::deserialize(&mut decoder).unwrap_err();
2806        assert!(matches!(
2807            *error,
2808            MaxMindDbError::InvalidDatabase {
2809                offset: Some(4),
2810                ..
2811            }
2812        ));
2813        assert!(error
2814            .to_string()
2815            .contains("exceeded maximum data structure depth"));
2816        assert_eq!(decoder.offset(), 2);
2817        assert_eq!(
2818            decoder.state & super::DEPTH_MASK,
2819            u32::from(super::MAXIMUM_DATA_STRUCTURE_DEPTH)
2820        );
2821        assert_eq!(u16::deserialize(&mut decoder).unwrap(), 42);
2822    }
2823
2824    #[cfg(not(feature = "unsafe-str-decode"))]
2825    #[test]
2826    #[cfg_attr(miri, ignore = "too slow under Miri")]
2827    fn ascii_check_covers_every_byte_at_word_boundaries() {
2828        for len in 0..=80 {
2829            let mut storage = vec![0x7f; len + 7];
2830            for offset in 0..8 {
2831                let bytes = &mut storage[offset..offset + len];
2832                assert!(super::is_ascii(bytes));
2833                for index in 0..len {
2834                    for byte in 0x80..=0xff {
2835                        bytes[index] = byte;
2836                        assert!(
2837                            !super::is_ascii(bytes),
2838                            "accepted non-ASCII byte {byte} at index {index}, length {len}, offset {offset}"
2839                        );
2840                    }
2841                    bytes[index] = 0x7f;
2842                }
2843            }
2844        }
2845    }
2846
2847    #[test]
2848    fn ignored_any_skips_pointer_targets_but_verification_follows_them() {
2849        for (pointer_size, control) in [(1, 0x20), (2, 0x28), (3, 0x30), (4, 0x38)] {
2850            // Each pointer targets a location outside this buffer. Skipping
2851            // must resume at the next value without expanding that target.
2852            let mut encoded = vec![control];
2853            encoded.resize(pointer_size + 1, 0xff);
2854            let continuation = encoded.len();
2855            encoded.extend([0xa1, 42]); // uint16 with a one-byte payload
2856            let mut decoder = Decoder::new(&encoded, 0);
2857            serde::de::IgnoredAny::deserialize(&mut decoder).unwrap();
2858            assert_eq!(decoder.offset(), continuation);
2859            assert_eq!(u16::deserialize(&mut decoder).unwrap(), 42);
2860            assert_eq!(decoder.offset(), encoded.len());
2861
2862            let mut decoder = Decoder::new(&encoded, 0);
2863            let err = decoder
2864                .skip_value_for_verification(&mut VerificationState::new(decoder.limit))
2865                .unwrap_err();
2866            assert!(matches!(*err, MaxMindDbError::InvalidDatabase { .. }));
2867
2868            // Every truncated payload must fail without advancing beyond the
2869            // header, even when bytes exist outside the decoder's limit.
2870            for limit in 1..continuation {
2871                for buf in [&encoded[..limit], &encoded[..]] {
2872                    let mut decoder = Decoder::new_with_limit(buf, 0, limit);
2873                    let err = serde::de::IgnoredAny::deserialize(&mut decoder).unwrap_err();
2874                    assert!(matches!(
2875                        *err,
2876                        MaxMindDbError::InvalidDatabase { message, offset: Some(1) }
2877                            if message == format!("pointer of size {pointer_size}")
2878                    ));
2879                    assert_eq!(decoder.offset(), 1);
2880                }
2881            }
2882        }
2883    }
2884
2885    #[test]
2886    fn test_decoder_caps_impossible_container_size_hint() {
2887        // Extended array with 284 declared elements and no element payload.
2888        let mut decoder = Decoder::new(&[0x1d, 0x04, 0xff], 0);
2889        let err = Vec::<serde::de::IgnoredAny>::deserialize(&mut decoder).unwrap_err();
2890
2891        assert!(matches!(*err, MaxMindDbError::InvalidDatabase { .. }));
2892        assert!(err.to_string().contains("unexpected end of buffer"));
2893    }
2894
2895    #[test]
2896    fn ignored_any_rejects_excessive_inline_container_work() {
2897        // Extended array with 65,536 declared elements and no payload. An
2898        // ignored inline container still requires one loop iteration per
2899        // child, so it shares the logical-value operation budget.
2900        let mut decoder = Decoder::new(&[0x1e, 0x04, 0xfe, 0xe3], 0);
2901        let err = serde::de::IgnoredAny::deserialize(&mut decoder).unwrap_err();
2902
2903        assert!(err
2904            .to_string()
2905            .contains("maximum number of data structure values"));
2906    }
2907
2908    #[test]
2909    fn ignored_any_rejects_excessive_inline_map_work() {
2910        // A 32,768-entry map contains 65,536 children in addition to the map
2911        // itself, so it cannot fit within the logical-value operation budget.
2912        let mut decoder = Decoder::new(&[0xfe, 0x7e, 0xe3], 0);
2913        let err = serde::de::IgnoredAny::deserialize(&mut decoder).unwrap_err();
2914
2915        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
2916        assert!(err
2917            .to_string()
2918            .contains("maximum number of data structure values"));
2919    }
2920
2921    #[test]
2922    fn navigation_rejects_excessive_declared_container_work() {
2923        let mut decoder = Decoder::new(&[0x1e, 0x04, 0xfe, 0xe3], 0);
2924        let err = decoder.consume_container_header().unwrap_err();
2925
2926        assert!(err
2927            .to_string()
2928            .contains("maximum number of data structure values"));
2929    }
2930
2931    #[test]
2932    fn oversized_containers_fail_before_visitor_entry() {
2933        use std::cell::Cell;
2934
2935        struct EntryVisitor<'a>(&'a Cell<bool>);
2936        impl<'de> Visitor<'de> for EntryVisitor<'_> {
2937            type Value = ();
2938
2939            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2940                formatter.write_str("a container")
2941            }
2942
2943            fn visit_seq<A: SeqAccess<'de>>(self, _: A) -> Result<(), A::Error> {
2944                self.0.set(true);
2945                Ok(())
2946            }
2947
2948            fn visit_map<A: MapAccess<'de>>(self, _: A) -> Result<(), A::Error> {
2949                self.0.set(true);
2950                Ok(())
2951            }
2952        }
2953
2954        let mut array = vec![0x1e, 0x04, 0xfe, 0xe3]; // 65,536 elements
2955        array.extend([0x00, 0x07].repeat(65_536)); // false
2956        let mut map = vec![0xfe, 0x7e, 0xe3]; // 32,768 entries
2957        map.extend([0x40, 0x00, 0x07].repeat(32_768)); // empty string => false
2958
2959        // Complete payloads leave room for a large size hint. Neither concrete
2960        // nor dynamic entry points may expose it to a visitor before rejecting.
2961        for (is_map, bytes) in [(false, array), (true, map)] {
2962            for dynamic in [false, true] {
2963                let entered = Cell::new(false);
2964                let mut decoder = Decoder::new(&bytes, 0);
2965                let visitor = EntryVisitor(&entered);
2966                let result = if dynamic {
2967                    decoder.deserialize_any(visitor)
2968                } else if is_map {
2969                    decoder.deserialize_map(visitor)
2970                } else {
2971                    decoder.deserialize_seq(visitor)
2972                };
2973                assert!(matches!(
2974                    result.map_err(|error| *error),
2975                    Err(MaxMindDbError::ResourceLimit { .. })
2976                ));
2977                assert!(
2978                    !entered.get(),
2979                    "visitor entered: map={is_map}, dynamic={dynamic}"
2980                );
2981            }
2982        }
2983    }
2984
2985    #[test]
2986    fn city_subdivisions_reject_declared_size_before_allocating() {
2987        // Extended array with 65,536 elements and no payload. Concrete Vec
2988        // decoding must reject its declared children before Serde sees the
2989        // size hint and can allocate for them.
2990        let mut decoder = Decoder::new(&[0x1e, 0x04, 0xfe, 0xe3], 0);
2991        let err =
2992            Vec::<crate::geoip2::city::Subdivision<'_>>::deserialize(&mut decoder).unwrap_err();
2993
2994        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
2995        assert!(err
2996            .to_string()
2997            .contains("maximum number of data structure values"));
2998    }
2999
3000    #[test]
3001    fn concrete_map_rejects_declared_size_before_allocating() {
3002        // Extended map with 32,768 entries and no payload. Map children include
3003        // both keys and values, so this exceeds the 65,536-value operation
3004        // budget once the top-level map itself is included. The rejection must
3005        // happen before HashMap receives a size hint and can allocate.
3006        let mut decoder = Decoder::new(&[0xfe, 0x7e, 0xe3], 0);
3007        let err =
3008            std::collections::HashMap::<String, serde::de::IgnoredAny>::deserialize(&mut decoder)
3009                .unwrap_err();
3010
3011        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3012        assert!(err
3013            .to_string()
3014            .contains("maximum number of data structure values"));
3015    }
3016
3017    #[test]
3018    #[cfg_attr(miri, ignore = "too slow under Miri")]
3019    fn concrete_sequence_charges_repeated_shared_struct_maps() {
3020        #[derive(Debug, Deserialize)]
3021        struct EmptyRecord {}
3022
3023        // A shared 200-entry map followed by an array of 300 pointers to that
3024        // map. Every map entry is unknown to EmptyRecord. Ignoring its value is
3025        // cheap, but the requested struct still has to examine every key each
3026        // time the pointer target is decoded. Aggregate container reservation
3027        // rejects that fan-out after bounded work.
3028        let mut buf = vec![0xfd, 171]; // map size: 29 + 171 = 200
3029        for _ in 0..200 {
3030            buf.extend_from_slice(&[0x40, 0xe0]); // empty string => empty map
3031        }
3032        let array_offset = buf.len();
3033        buf.extend_from_slice(&[0x1e, 0x04, 0x00, 0x0f]); // array size: 300
3034        for _ in 0..300 {
3035            append_pointer(&mut buf, 0);
3036        }
3037
3038        let mut decoder = Decoder::new(&buf, array_offset);
3039        let err = Vec::<EmptyRecord>::deserialize(&mut decoder).unwrap_err();
3040
3041        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3042        assert!(err
3043            .to_string()
3044            .contains("maximum number of data structure values"));
3045    }
3046
3047    #[test]
3048    #[cfg_attr(miri, ignore = "too slow under Miri")]
3049    fn concrete_sequence_charges_repeated_string_payloads() {
3050        // One 4 KiB string followed by an array of 600 pointers to it. The
3051        // array activates the operation budget, and direct &str decoding must
3052        // recharge the shared payload for every logical occurrence.
3053        let (buf, array_offset) = repeated_4k_payload_array(0x5e, 600);
3054
3055        let mut decoder = Decoder::new(&buf, array_offset);
3056        let err = Vec::<&str>::deserialize(&mut decoder).unwrap_err();
3057
3058        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3059        assert!(err
3060            .to_string()
3061            .contains("maximum size of data structure string and bytes"));
3062    }
3063
3064    #[test]
3065    fn direct_byte_buf_decoding_charges_repeated_payloads() {
3066        let (buf, array_offset) = repeated_4k_payload_array(0x9e, 600);
3067        let mut decoder = Decoder::new(&buf, array_offset);
3068        let err = Vec::<OwnedBytes>::deserialize(&mut decoder).unwrap_err();
3069
3070        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3071        assert!(err
3072            .to_string()
3073            .contains("maximum size of data structure string and bytes"));
3074    }
3075
3076    #[test]
3077    fn raw_string_decoding_charges_repeated_payloads() {
3078        let (buf, array_offset) = repeated_4k_payload_array(0x5e, 600);
3079        let mut decoder = Decoder::new(&buf, array_offset);
3080        let err = RawValueSeed.deserialize(&mut decoder).unwrap_err();
3081
3082        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3083        assert!(err
3084            .to_string()
3085            .contains("maximum size of data structure string and bytes"));
3086    }
3087
3088    #[derive(Debug, Deserialize)]
3089    enum StandaloneScalarEnum {
3090        Known,
3091    }
3092
3093    fn large_string(size: usize) -> Vec<u8> {
3094        assert!((65_821..=65_821 + 0xff_ff_ff).contains(&size));
3095        let encoded_size = (size - 65_821) as u32;
3096        let mut buf = vec![0x5f]; // string with a three-byte extended size
3097        buf.extend_from_slice(&encoded_size.to_be_bytes()[1..]);
3098        buf.resize(buf.len() + size, b'a');
3099        buf
3100    }
3101
3102    #[test]
3103    #[cfg_attr(miri, ignore = "too slow under Miri")]
3104    fn partial_struct_skips_unknown_inline_payload_over_budget() {
3105        #[derive(Deserialize)]
3106        struct PartialRecord {
3107            known: bool,
3108        }
3109
3110        let payload_size = super::MAXIMUM_DATA_STRUCTURE_BYTES + 1;
3111        for control in [0x5f, 0x9f] {
3112            let mut payload = large_string(payload_size);
3113            payload[0] = control; // string or bytes with a three-byte extended size
3114
3115            let mut buf = vec![0xe2, 0x47]; // two-entry map, seven-byte key
3116            buf.extend_from_slice(b"unknown");
3117            buf.extend_from_slice(&payload);
3118            buf.extend_from_slice(&[0x45]); // five-byte key
3119            buf.extend_from_slice(b"known");
3120            buf.extend_from_slice(&[0x01, 0x07]); // true
3121
3122            let mut decoder = Decoder::new(&buf, 0);
3123            let decoded = PartialRecord::deserialize(&mut decoder).unwrap();
3124            assert!(decoded.known);
3125        }
3126    }
3127
3128    #[test]
3129    #[cfg_attr(miri, ignore = "too slow under Miri")]
3130    fn budgeted_standalone_scalar_entry_points_enforce_payload_limit() {
3131        // The enum identifier receives the 32-byte allowance, so exceed both
3132        // that allowance and the ordinary 2 MiB payload budget by one byte.
3133        let size =
3134            super::MAXIMUM_DATA_STRUCTURE_BYTES + super::MAXIMUM_UNCHARGED_IDENTIFIER_BYTES + 1;
3135        let buf = large_string(size);
3136
3137        let mut decoder = Decoder::new(&buf, 0);
3138        let err = serde_json::Value::deserialize(&mut decoder).unwrap_err();
3139        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3140
3141        let mut decoder = Decoder::new(&buf, 0);
3142        let err = RawValueSeed.deserialize(&mut decoder).unwrap_err();
3143        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3144
3145        let mut decoder = Decoder::new(&buf, 0);
3146        let err = StandaloneScalarEnum::deserialize(&mut decoder).unwrap_err();
3147        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3148
3149        // A directly requested typed scalar intentionally retains its
3150        // unbudgeted fast path because one scalar cannot amplify through
3151        // container or pointer fan-out.
3152        let mut decoder = Decoder::new(&buf, 0);
3153        let decoded = <&str>::deserialize(&mut decoder).unwrap();
3154        assert_eq!(decoded.len(), size);
3155    }
3156
3157    #[test]
3158    #[cfg_attr(miri, ignore = "too slow under Miri")]
3159    fn standalone_scalar_retains_unbudgeted_fast_path() {
3160        let size = super::MAXIMUM_DATA_STRUCTURE_BYTES + 1;
3161        let buf = large_string(size);
3162
3163        let mut decoder = Decoder::new(&buf, 0);
3164        let decoded = <&str>::deserialize(&mut decoder).unwrap();
3165        assert_eq!(decoded.len(), size);
3166    }
3167
3168    fn repeated_4k_payload_array(control: u8, element_count: usize) -> (Vec<u8>, usize) {
3169        // A shared 4 KiB string or bytes value followed by an array of pointers
3170        // to it. Both payload types use the same extended-size representation.
3171        assert!(matches!(control, 0x5e | 0x9e));
3172        let mut buf = vec![control, 0x0e, 0xe3]; // size: 285 + 3,811 = 4,096
3173        buf.resize(buf.len() + 4096, b'a');
3174        let array_offset = buf.len();
3175
3176        assert!((285..=u16::MAX as usize + 285).contains(&element_count));
3177        buf.extend_from_slice(&[0x1e, 0x04]); // array with a two-byte extended size
3178        buf.extend_from_slice(&((element_count - 285) as u16).to_be_bytes());
3179        for _ in 0..element_count {
3180            append_pointer(&mut buf, 0);
3181        }
3182
3183        (buf, array_offset)
3184    }
3185
3186    fn pointer_key_map(entry_count: usize) -> (Vec<u8>, usize) {
3187        // A shared 4 KiB string followed by a map whose keys all point to it.
3188        let mut buf = vec![0x5e, 0x0e, 0xe3]; // string size: 285 + 3,811 = 4,096
3189        buf.resize(buf.len() + 4096, b'k');
3190        let map_offset = buf.len();
3191
3192        assert!((285..=u16::MAX as usize + 285).contains(&entry_count));
3193        buf.push(0xfe); // map with a two-byte extended size
3194        buf.extend_from_slice(&((entry_count - 285) as u16).to_be_bytes());
3195        for _ in 0..entry_count {
3196            append_pointer(&mut buf, 0);
3197            buf.extend_from_slice(&[0x00, 0x07]); // false
3198        }
3199
3200        (buf, map_offset)
3201    }
3202
3203    fn repeated_inline_key_map_array(element_count: usize) -> (Vec<u8>, usize) {
3204        // A one-entry map with a 4 KiB inline key, followed by an array of
3205        // pointers that repeatedly expands that map.
3206        let mut buf = vec![0xe1, 0x5e, 0x0e, 0xe3]; // map(1), string(4,096)
3207        buf.resize(buf.len() + 4096, b'k');
3208        buf.extend_from_slice(&[0x00, 0x07]); // false
3209        let array_offset = buf.len();
3210
3211        assert!((285..=u16::MAX as usize + 285).contains(&element_count));
3212        buf.extend_from_slice(&[0x1e, 0x04]); // array with a two-byte extended size
3213        buf.extend_from_slice(&((element_count - 285) as u16).to_be_bytes());
3214        for _ in 0..element_count {
3215            append_pointer(&mut buf, 0);
3216        }
3217
3218        (buf, array_offset)
3219    }
3220
3221    #[test]
3222    fn dynamic_map_keys_are_charged_once() {
3223        // 512 copies of a 4 KiB key exactly fill the 2 MiB payload budget.
3224        // Dynamic maps precharge keys before invoking an identifier visitor;
3225        // the visitor must not charge the same payload a second time.
3226        let (buf, map_offset) = pointer_key_map(512);
3227        let mut decoder = Decoder::new(&buf, map_offset);
3228        let value = RawValueSeed.deserialize(&mut decoder).unwrap();
3229
3230        let RawValue::Map(entries) = value else {
3231            panic!("expected map");
3232        };
3233        assert_eq!(entries.len(), 512);
3234
3235        // Raw identifiers have a small uncharged allowance. The full dynamic
3236        // precharge must still reject the first key beyond the payload budget.
3237        let (buf, map_offset) = pointer_key_map(513);
3238        let mut decoder = Decoder::new(&buf, map_offset);
3239        let err = RawValueSeed.deserialize(&mut decoder).unwrap_err();
3240        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3241        assert!(err
3242            .to_string()
3243            .contains("maximum size of data structure string and bytes"));
3244    }
3245
3246    fn compare_cached_key<'de, K>(
3247        buf: &'de [u8],
3248        start: usize,
3249        limit: usize,
3250        remaining: u32,
3251        seed: K,
3252    ) where
3253        K: DeserializeSeed<'de> + Copy,
3254        K::Value: fmt::Debug + PartialEq,
3255    {
3256        let mut cached = Decoder::new_with_limit(buf, start, limit);
3257        let mut original = Decoder::new_with_limit(buf, start, limit);
3258        for decoder in [&mut cached, &mut original] {
3259            decoder.activate_budget();
3260            decoder.payload_remaining = remaining;
3261        }
3262
3263        let actual = super::MapAccessor::<true> {
3264            de: &mut cached,
3265            count: 2,
3266        }
3267        .next_key_seed(seed)
3268        .map_err(|error| format!("{error:?}"));
3269        // Reference the previous map-key algorithm: precharge, decode from the
3270        // original cursor, then retain whichever payload charge is larger.
3271        let expected = (|| {
3272            let (charged, _) = original.count_payload_at_current()?;
3273            let after = original.payload_remaining;
3274            original.payload_remaining = remaining;
3275            let result = seed.deserialize(&mut original).map(Some);
3276            if charged {
3277                original.payload_remaining = original.payload_remaining.min(after);
3278            }
3279            result
3280        })()
3281        .map_err(|error: super::DecoderError| format!("{error:?}"));
3282
3283        assert_eq!(
3284            actual, expected,
3285            "start={start}, limit={limit}, remaining={remaining}"
3286        );
3287        assert_eq!(cached.current_ptr, original.current_ptr);
3288        assert_eq!(cached.state, original.state);
3289        assert_eq!(cached.payload_remaining, original.payload_remaining);
3290    }
3291
3292    #[test]
3293    #[cfg_attr(miri, ignore = "too slow under Miri")]
3294    fn cached_map_keys_preserve_values_errors_cursors_and_budgets() {
3295        let mut buf = [0x61; 80];
3296        buf[..2].copy_from_slice(&[0x20, 10]);
3297        for control in 0..=255 {
3298            buf[10] = control;
3299            for limit in 0..=buf.len() {
3300                for remaining in [0, 1, 28, 32, 4096] {
3301                    compare_cached_key(&buf, 0, limit, remaining, RawIdentifierSeed);
3302                    compare_cached_key(&buf, 10, limit, remaining, RawIdentifierSeed);
3303                }
3304            }
3305        }
3306        for &(pointer, target) in &[
3307            (&[0x20, 8][..], 8),
3308            (&[0x28, 0, 0][..], 2048),
3309            (&[0x30, 0, 0, 0][..], 526_336),
3310            (&[0x38, 0, 0, 0, 8][..], 8),
3311        ] {
3312            let mut buf = pointer.to_vec();
3313            buf.resize(target, 0);
3314            buf.extend([0x5e, 0, 0]); // 285-byte string
3315            buf.resize(buf.len() + 285, 0xff); // identifiers preserve raw UTF-8 bytes
3316            for limit in [pointer.len() - 1, target, buf.len() - 1, buf.len()] {
3317                for remaining in [0, 284, 285, 4096] {
3318                    compare_cached_key(&buf, 0, limit, remaining, RawIdentifierSeed);
3319                }
3320            }
3321        }
3322    }
3323
3324    #[test]
3325    fn cached_map_keys_preserve_other_serde_entry_points() {
3326        use std::marker::PhantomData;
3327
3328        let cases: &[&[u8]] = &[
3329            &[0x41, b'x'],
3330            &[0x20, 4, 0xa1, 42, 0x41, b'x'],
3331            &[0x20, 4, 0xa1, 42, 0x41],
3332            &[0x81, 0xff], // bytes are not string identifiers
3333            &[0xa1, 42],
3334            &[0xe0],
3335        ];
3336        for &buf in cases {
3337            for remaining in [0, 1, 4096] {
3338                compare_cached_key(buf, 0, buf.len(), remaining, PhantomData::<String>);
3339                compare_cached_key(
3340                    buf,
3341                    0,
3342                    buf.len(),
3343                    remaining,
3344                    PhantomData::<serde_json::Value>,
3345                );
3346                compare_cached_key(
3347                    buf,
3348                    0,
3349                    buf.len(),
3350                    remaining,
3351                    PhantomData::<serde::de::IgnoredAny>,
3352                );
3353            }
3354        }
3355    }
3356
3357    #[test]
3358    #[cfg(not(feature = "unsafe-str-decode"))]
3359    fn cached_map_keys_do_not_bypass_utf8_validation_for_strings() {
3360        use std::marker::PhantomData;
3361
3362        for buf in [&[0x41, 0xff][..], &[0x20, 2, 0x41, 0xff][..]] {
3363            compare_cached_key(buf, 0, buf.len(), 4096, PhantomData::<String>);
3364            compare_cached_key(buf, 0, buf.len(), 4096, PhantomData::<serde_json::Value>);
3365            compare_cached_key(buf, 0, buf.len(), 4096, RawIdentifierSeed);
3366        }
3367    }
3368
3369    #[test]
3370    #[cfg_attr(miri, ignore = "too slow under Miri")]
3371    fn dynamic_any_map_keys_are_charged_once() {
3372        // deserialize_any activates the budget itself. The map accessor's
3373        // precharge must still suppress exactly one payload charge rather than
3374        // charging each 4 KiB key twice.
3375        let (buf, map_offset) = pointer_key_map(512);
3376        let mut decoder = Decoder::new(&buf, map_offset);
3377        assert_eq!(
3378            decoder.deserialize_any(AnyKeyMapVisitor).unwrap(),
3379            AnyKeyMap(512)
3380        );
3381
3382        // The precharge remains effective: one additional key exceeds 2 MiB.
3383        let (buf, map_offset) = pointer_key_map(513);
3384        let mut decoder = Decoder::new(&buf, map_offset);
3385        let err = decoder.deserialize_any(AnyKeyMapVisitor).unwrap_err();
3386        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3387        assert!(err
3388            .to_string()
3389            .contains("maximum size of data structure string and bytes"));
3390    }
3391
3392    #[test]
3393    fn navigation_charges_repeated_pointer_keys() {
3394        let (buf, map_offset) = pointer_key_map(513);
3395        let mut decoder = Decoder::new(&buf, map_offset);
3396        let (size, type_num) = decoder.consume_container_header().unwrap();
3397        assert_eq!((size, type_num), (513, super::TYPE_MAP));
3398
3399        for _ in 0..512 {
3400            assert_eq!(decoder.read_str_as_bytes().unwrap().len(), 4096);
3401            decoder.skip_value().unwrap();
3402        }
3403        let err = decoder.read_str_as_bytes().unwrap_err();
3404
3405        assert!(err
3406            .to_string()
3407            .contains("maximum size of data structure string and bytes"));
3408    }
3409
3410    #[test]
3411    #[cfg_attr(miri, ignore = "too slow under Miri")]
3412    fn flattened_pointer_keys_cannot_bypass_payload_budget() {
3413        #[derive(Debug, Deserialize)]
3414        struct Flattened {
3415            #[serde(flatten)]
3416            fields: std::collections::HashMap<String, serde::de::IgnoredAny>,
3417        }
3418
3419        // Each key charges 4,096 - 32 = 4,064 bytes after the per-identifier
3420        // allowance. 516 copies leave 128 bytes in the 2 MiB payload budget.
3421        let (buf, map_offset) = pointer_key_map(516);
3422        let mut decoder = Decoder::new(&buf, map_offset);
3423        let decoded = Flattened::deserialize(&mut decoder).unwrap();
3424        assert_eq!(decoded.fields.len(), 1);
3425
3426        // The 517th copy exceeds that budget. Serde buffers flattened keys, so
3427        // concrete struct identifier decoding must charge long keys while
3428        // ordinary short City keys stay on the uncharged fast path.
3429        let (buf, map_offset) = pointer_key_map(517);
3430        let mut decoder = Decoder::new(&buf, map_offset);
3431        let err = Flattened::deserialize(&mut decoder).unwrap_err();
3432
3433        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3434        assert!(err
3435            .to_string()
3436            .contains("maximum size of data structure string and bytes"));
3437    }
3438
3439    #[test]
3440    #[cfg_attr(miri, ignore = "too slow under Miri")]
3441    fn repeated_maps_with_inline_keys_cannot_bypass_payload_budget() {
3442        #[derive(Debug, Deserialize)]
3443        struct Flattened {
3444            #[serde(flatten)]
3445            fields: std::collections::HashMap<String, serde::de::IgnoredAny>,
3446        }
3447
3448        // The inline path has the same exact boundary as pointer-backed keys.
3449        let (buf, array_offset) = repeated_inline_key_map_array(516);
3450        let mut decoder = Decoder::new(&buf, array_offset);
3451        let decoded = Vec::<Flattened>::deserialize(&mut decoder).unwrap();
3452        assert_eq!(decoded.len(), 516);
3453        assert!(decoded.iter().all(|value| value.fields.len() == 1));
3454
3455        // One additional expansion exceeds the aggregate identifier budget.
3456        let (buf, array_offset) = repeated_inline_key_map_array(517);
3457        let mut decoder = Decoder::new(&buf, array_offset);
3458        let err = Vec::<Flattened>::deserialize(&mut decoder).unwrap_err();
3459
3460        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3461        assert!(err
3462            .to_string()
3463            .contains("maximum size of data structure string and bytes"));
3464    }
3465
3466    #[allow(dead_code)]
3467    #[derive(Debug, Deserialize)]
3468    enum RecursiveEnum {
3469        Next(Box<RecursiveEnum>),
3470        End,
3471    }
3472
3473    fn recursive_enum_chain(in_array: bool) -> (Vec<u8>, usize) {
3474        // {"Next": <pointer to this map>}
3475        let mut buf = vec![0xe1, 0x44, b'N', b'e', b'x', b't'];
3476        append_pointer(&mut buf, 0);
3477        if !in_array {
3478            return (buf, 0);
3479        }
3480        let start = buf.len();
3481        buf.extend_from_slice(&[0x01, 0x04]); // one-element array
3482        append_pointer(&mut buf, 0);
3483        (buf, start)
3484    }
3485
3486    #[test]
3487    fn recursive_newtype_enum_is_depth_bounded() {
3488        run_on_bounded_stack(|| {
3489            let (buf, start) = recursive_enum_chain(false);
3490            let mut decoder = Decoder::new(&buf, start);
3491            let err = RecursiveEnum::deserialize(&mut decoder).unwrap_err();
3492
3493            assert!(err
3494                .to_string()
3495                .contains("exceeded maximum data structure depth"));
3496        });
3497    }
3498
3499    #[test]
3500    fn recursive_newtype_enum_inside_array_is_depth_bounded() {
3501        run_on_bounded_stack(|| {
3502            let (buf, start) = recursive_enum_chain(true);
3503            let mut decoder = Decoder::new(&buf, start);
3504            let err = Vec::<RecursiveEnum>::deserialize(&mut decoder).unwrap_err();
3505
3506            assert!(err
3507                .to_string()
3508                .contains("exceeded maximum data structure depth"));
3509        });
3510    }
3511
3512    #[derive(Debug, Deserialize)]
3513    struct NestedHashMap(#[allow(dead_code)] std::collections::HashMap<String, NestedHashMap>);
3514    #[derive(Debug, Deserialize)]
3515    struct NestedArray(#[allow(dead_code)] Vec<NestedArray>);
3516
3517    #[derive(Debug, Deserialize)]
3518    struct NestedMap {
3519        #[allow(dead_code)]
3520        a: Option<Box<NestedMap>>,
3521    }
3522
3523    /// `depth` nested arrays, each holding the next. The innermost is empty.
3524    fn nested_arrays(depth: usize) -> Vec<u8> {
3525        let mut buf = [0x01, 0x04].repeat(depth - 1); // one-element array
3526        buf.extend_from_slice(&[0x00, 0x04]); // empty array
3527        buf
3528    }
3529
3530    /// `depth` nested maps, each holding the next under the key "a". The
3531    /// innermost map is `innermost`.
3532    fn nested_maps(depth: usize, innermost: &[u8]) -> Vec<u8> {
3533        let mut buf = [0xe1, 0x41, b'a'].repeat(depth - 1);
3534        buf.extend_from_slice(innermost);
3535        buf
3536    }
3537
3538    /// Pointer and array pairs, each adding two levels. The innermost array
3539    /// holds `innermost` as its one element, or nothing.
3540    fn nested_pointer_arrays(pairs: usize, innermost: Option<&[u8]>) -> Vec<u8> {
3541        let mut buf = Vec::new();
3542        for pair in 0..pairs {
3543            let target = pair * 4 + 2;
3544            // One-byte pointer offsets stop at 2047.
3545            assert!(target < 2048);
3546            buf.extend_from_slice(&[0x20 | (target >> 8) as u8, target as u8]);
3547            if pair + 1 < pairs || innermost.is_some() {
3548                buf.extend_from_slice(&[0x01, 0x04]);
3549            } else {
3550                buf.extend_from_slice(&[0x00, 0x04]);
3551            }
3552        }
3553        buf.extend_from_slice(innermost.unwrap_or_default());
3554        buf
3555    }
3556
3557    /// Spawned threads, including test threads, default to 2 MiB stacks, and
3558    /// builds with debug assertions check against that. Setting it here keeps
3559    /// the check independent of RUST_MIN_STACK. Builds without debug
3560    /// assertions force the decoder's inlining, and an unoptimized one needs
3561    /// about 3 MiB, so they get 4 MiB.
3562    fn run_on_bounded_stack(f: impl FnOnce() + Send + 'static) {
3563        let mib = if cfg!(debug_assertions) { 2 } else { 4 };
3564        std::thread::Builder::new()
3565            .stack_size(mib * 1024 * 1024)
3566            .spawn(f)
3567            .unwrap()
3568            .join()
3569            .unwrap();
3570    }
3571
3572    #[test]
3573    fn maximum_depth_fits_bounded_stack() {
3574        run_on_bounded_stack(|| {
3575            let depth = usize::from(super::MAXIMUM_DATA_STRUCTURE_DEPTH);
3576            let arrays = nested_arrays(depth);
3577            let maps = nested_maps(depth, &[0xe0]);
3578            // Ignored values have their own, lower skip limit. Put the deepest
3579            // skip below the deepest typed map.
3580            let mut ignored = vec![0xe1, 0x41, b'x'];
3581            ignored.extend(nested_arrays(usize::from(
3582                super::MAXIMUM_SKIPPED_DATA_STRUCTURE_DEPTH,
3583            )));
3584            let maps_with_ignored = nested_maps(depth, &ignored);
3585            let pointers = nested_pointer_arrays(depth / 2, None);
3586
3587            for buf in [&arrays, &maps, &pointers] {
3588                serde_json::Value::deserialize(&mut Decoder::new(buf, 0)).unwrap();
3589                RawValue::deserialize(&mut Decoder::new(buf, 0)).unwrap();
3590            }
3591            NestedArray::deserialize(&mut Decoder::new(&arrays, 0)).unwrap();
3592            NestedArray::deserialize(&mut Decoder::new(&pointers, 0)).unwrap();
3593            NestedMap::deserialize(&mut Decoder::new(&maps, 0)).unwrap();
3594            NestedMap::deserialize(&mut Decoder::new(&maps_with_ignored, 0)).unwrap();
3595            NestedHashMap::deserialize(&mut Decoder::new(&maps, 0)).unwrap();
3596        });
3597    }
3598
3599    #[test]
3600    fn depth_limit_applies_before_the_stack_runs_out() {
3601        run_on_bounded_stack(|| {
3602            let depth = usize::from(super::MAXIMUM_DATA_STRUCTURE_DEPTH) + 1;
3603            let arrays = nested_arrays(depth);
3604            let maps = nested_maps(depth, &[0xe0]);
3605            // One level past the skip limit, under the deepest allowed map.
3606            let mut ignored = vec![0xe1, 0x41, b'x'];
3607            ignored.extend(nested_arrays(
3608                usize::from(super::MAXIMUM_SKIPPED_DATA_STRUCTURE_DEPTH) + 1,
3609            ));
3610            let maps_with_ignored = nested_maps(depth - 1, &ignored);
3611            // 256 pairs plus one empty array: 513 levels.
3612            let pointers = nested_pointer_arrays(depth / 2, Some(&[0x00, 0x04]));
3613            let errors = [
3614                serde_json::Value::deserialize(&mut Decoder::new(&pointers, 0)).unwrap_err(),
3615                RawValue::deserialize(&mut Decoder::new(&pointers, 0)).unwrap_err(),
3616                NestedArray::deserialize(&mut Decoder::new(&pointers, 0)).unwrap_err(),
3617                serde_json::Value::deserialize(&mut Decoder::new(&arrays, 0)).unwrap_err(),
3618                serde_json::Value::deserialize(&mut Decoder::new(&maps, 0)).unwrap_err(),
3619                RawValue::deserialize(&mut Decoder::new(&arrays, 0)).unwrap_err(),
3620                RawValue::deserialize(&mut Decoder::new(&maps, 0)).unwrap_err(),
3621                NestedArray::deserialize(&mut Decoder::new(&arrays, 0)).unwrap_err(),
3622                NestedMap::deserialize(&mut Decoder::new(&maps, 0)).unwrap_err(),
3623                NestedMap::deserialize(&mut Decoder::new(&maps_with_ignored, 0)).unwrap_err(),
3624                NestedHashMap::deserialize(&mut Decoder::new(&maps, 0)).unwrap_err(),
3625            ];
3626            for error in errors {
3627                assert!(
3628                    error
3629                        .to_string()
3630                        .contains("exceeded maximum data structure depth"),
3631                    "unexpected error: {error}"
3632                );
3633                assert!(matches!(*error, MaxMindDbError::InvalidDatabase { .. }));
3634            }
3635        });
3636    }
3637
3638    #[derive(Debug, Deserialize, PartialEq)]
3639    enum DataEnum {
3640        N(u32),
3641        T(u32, u32),
3642        S { a: u32 },
3643        U,
3644    }
3645
3646    #[derive(Debug, Deserialize, PartialEq)]
3647    struct EnumField {
3648        e: DataEnum,
3649    }
3650
3651    fn decode_enum_at<'de, T: Deserialize<'de>>(
3652        buf: &'de [u8],
3653        start: usize,
3654    ) -> Result<T, super::DecoderError> {
3655        let mut decoder = Decoder::new(buf, start);
3656        T::deserialize(&mut decoder)
3657    }
3658
3659    #[test]
3660    fn enum_unit_variant_decodes_from_string() {
3661        let buf = [0x41, b'U'];
3662        assert_eq!(decode_enum_at::<DataEnum>(&buf, 0).unwrap(), DataEnum::U);
3663    }
3664
3665    #[test]
3666    fn enum_data_variants_decode_from_single_entry_map() {
3667        // {"N": 5}
3668        let buf = [0xe1, 0x41, b'N', 0xc1, 0x05];
3669        assert_eq!(decode_enum_at::<DataEnum>(&buf, 0).unwrap(), DataEnum::N(5));
3670
3671        // {"T": [1, 2]}
3672        let buf = [0xe1, 0x41, b'T', 0x02, 0x04, 0xc1, 0x01, 0xc1, 0x02];
3673        assert_eq!(
3674            decode_enum_at::<DataEnum>(&buf, 0).unwrap(),
3675            DataEnum::T(1, 2)
3676        );
3677
3678        // {"S": {"a": 3}}
3679        let buf = [0xe1, 0x41, b'S', 0xe1, 0x41, b'a', 0xc1, 0x03];
3680        assert_eq!(
3681            decode_enum_at::<DataEnum>(&buf, 0).unwrap(),
3682            DataEnum::S { a: 3 }
3683        );
3684    }
3685
3686    #[test]
3687    fn enum_variants_inside_array_stay_inside_array() {
3688        // [{"N": 5}, "U"] followed by an unrelated uint32 7
3689        let buf = [
3690            0x02, 0x04, 0xe1, 0x41, b'N', 0xc1, 0x05, 0x41, b'U', 0xc1, 0x07,
3691        ];
3692        let mut decoder = Decoder::new(&buf, 0);
3693        let decoded = Vec::<DataEnum>::deserialize(&mut decoder).unwrap();
3694        assert_eq!(decoded, vec![DataEnum::N(5), DataEnum::U]);
3695        assert_eq!(decoder.offset(), buf.len() - 2);
3696    }
3697
3698    #[test]
3699    fn enum_variants_follow_pointers_and_restore_continuation() {
3700        // Offset 0: {"N": 5}. Offset 5: "U".
3701        let mut buf = vec![0xe1, 0x41, b'N', 0xc1, 0x05, 0x41, b'U'];
3702        let start = buf.len();
3703        // [pointer to {"N": 5}, pointer to "U", "U"]
3704        buf.extend_from_slice(&[0x03, 0x04]);
3705        append_pointer(&mut buf, 0);
3706        append_pointer(&mut buf, 5);
3707        buf.extend_from_slice(&[0x41, b'U']);
3708
3709        let decoded = decode_enum_at::<Vec<DataEnum>>(&buf, start).unwrap();
3710        assert_eq!(decoded, vec![DataEnum::N(5), DataEnum::U, DataEnum::U]);
3711    }
3712
3713    #[test]
3714    fn enum_data_variant_from_string_is_rejected() {
3715        // An array with a declared length of 2 holding "N", 5, followed
3716        // outside the array by "N", 7. The payload must not be read from
3717        // the next value in the stream.
3718        let buf = [0x02, 0x04, 0x41, b'N', 0xc1, 0x05, 0x41, b'N', 0xc1, 0x07];
3719        let err = decode_enum_at::<Vec<DataEnum>>(&buf, 0).unwrap_err();
3720        assert!(matches!(*err, MaxMindDbError::Decoding { .. }));
3721        assert!(err
3722            .to_string()
3723            .contains("expected a single-entry map for an enum variant with data"));
3724
3725        // {"e": "N"} followed by an unrelated uint32 9.
3726        let buf = [0xe1, 0x41, b'e', 0x41, b'N', 0xc1, 0x09];
3727        let err = decode_enum_at::<EnumField>(&buf, 0).unwrap_err();
3728        assert!(err
3729            .to_string()
3730            .contains("expected a single-entry map for an enum variant with data"));
3731
3732        for variant in *b"TS" {
3733            let buf = [0x41, variant];
3734            let err = decode_enum_at::<DataEnum>(&buf, 0).unwrap_err();
3735            assert!(err
3736                .to_string()
3737                .contains("expected a single-entry map for an enum variant with data"));
3738        }
3739    }
3740
3741    #[test]
3742    fn enum_unit_variant_decodes_from_index() {
3743        // uint16 3, the index of `U`.
3744        let buf = [0xa1, 0x03];
3745        assert_eq!(decode_enum_at::<DataEnum>(&buf, 0).unwrap(), DataEnum::U);
3746    }
3747
3748    #[test]
3749    fn enum_unit_variant_in_map_form_skips_payload() {
3750        #[derive(Debug, Deserialize, PartialEq)]
3751        enum Kind {
3752            A,
3753            #[serde(other)]
3754            Unknown,
3755        }
3756
3757        // [{"Z": [1, {"x": 2}]}, "A"]: an unknown data variant from a newer
3758        // database falls back to the catch-all, and the payload is skipped.
3759        let buf = [
3760            0x02, 0x04, 0xe1, 0x41, b'Z', 0x02, 0x04, 0xc1, 0x01, 0xe1, 0x41, b'x', 0xc1, 0x02,
3761            0x41, b'A',
3762        ];
3763        let mut decoder = Decoder::new(&buf, 0);
3764        let decoded = Vec::<Kind>::deserialize(&mut decoder).unwrap();
3765        assert_eq!(decoded, vec![Kind::Unknown, Kind::A]);
3766        assert_eq!(decoder.offset(), buf.len());
3767
3768        // {"U": 1}: a known unit variant in map form.
3769        let buf = [0xe1, 0x41, b'U', 0xc1, 0x01];
3770        assert_eq!(decode_enum_at::<DataEnum>(&buf, 0).unwrap(), DataEnum::U);
3771    }
3772
3773    #[test]
3774    fn enum_rejects_other_encodings() {
3775        // {"N": 5, "U": 1}: more than one entry.
3776        let buf = [0xe2, 0x41, b'N', 0xc1, 0x05, 0x41, b'U', 0xc1, 0x01];
3777        let err = decode_enum_at::<DataEnum>(&buf, 0).unwrap_err();
3778        assert!(err.to_string().contains("got a map with 2 entries"));
3779
3780        // {}: no entries.
3781        let buf = [0xe0];
3782        let err = decode_enum_at::<DataEnum>(&buf, 0).unwrap_err();
3783        assert!(err.to_string().contains("got a map with 0 entries"));
3784
3785        // ["U"]: an array is not an enum encoding.
3786        let buf = [0x01, 0x04, 0x41, b'U'];
3787        let err = decode_enum_at::<DataEnum>(&buf, 0).unwrap_err();
3788        assert!(err.to_string().contains("invalid type: sequence"));
3789
3790        // An unknown variant name in either form.
3791        for buf in [&[0x41, b'X'][..], &[0xe1, 0x41, b'X', 0xc1, 0x01][..]] {
3792            let err = decode_enum_at::<DataEnum>(buf, 0).unwrap_err();
3793            assert!(err.to_string().contains("unknown variant"));
3794        }
3795    }
3796
3797    #[test]
3798    fn verification_bounds_overlapping_string_scans() {
3799        // Each header is also valid ASCII inside preceding string payloads.
3800        // Distinct target offsets defeat the exact-target cache.
3801        let size = 65_821 + 65_536;
3802        let mut buf = [0x5f, 0x01, 0x00, 0x00].repeat(64);
3803        buf.resize(buf.len() + size, b'a');
3804        let mut state = VerificationState::new(buf.len());
3805        let allowance = state.work_remaining;
3806        for index in 0..8 {
3807            Decoder::new(&buf, index * 4)
3808                .skip_value_for_verification(&mut state)
3809                .unwrap();
3810        }
3811        assert_eq!(state.work_remaining, allowance - 8 * (size + 1));
3812
3813        let mut decoder = Decoder::new(&buf, 8 * 4);
3814        let err = decoder.skip_value_for_verification(&mut state).unwrap_err();
3815        assert!(matches!(
3816            *err,
3817            MaxMindDbError::ResourceLimit {
3818                offset: Some(36),
3819                ..
3820            }
3821        ));
3822        // The rejected string was neither scanned nor cached; only its visit
3823        // was charged, and its cursor still points to the start of the payload.
3824        assert_eq!(state.work_remaining, allowance - 8 * (size + 1) - 1);
3825        assert_eq!(decoder.offset(), 36);
3826        assert_eq!(state.validated.len(), 8);
3827        assert!(state.active.is_empty());
3828    }
3829
3830    #[test]
3831    fn verification_bounds_repeated_inline_traversal_across_roots() {
3832        let mut buf = [0x01, 0x04].repeat(64); // nested one-element arrays
3833        buf.extend_from_slice(&[0x00, 0x07]); // false
3834        let mut state = VerificationState::new(buf.len());
3835        // Successive roots start inside earlier arrays. Inline children aren't
3836        // cached, so even without string scans their repeated visits need a cap.
3837        let err = (0..64)
3838            .try_for_each(|index| {
3839                Decoder::new(&buf, index * 2).skip_value_for_verification(&mut state)
3840            })
3841            .unwrap_err();
3842        assert!(matches!(*err, MaxMindDbError::ResourceLimit { .. }));
3843        assert_eq!(state.work_remaining, 0);
3844        assert!(state.active.is_empty());
3845    }
3846
3847    #[test]
3848    #[cfg_attr(miri, ignore = "too slow under Miri")]
3849    fn verification_allows_large_nonoverlapping_payloads() {
3850        let size = super::MAXIMUM_DATA_STRUCTURE_BYTES + 1;
3851        let mut buf = vec![0x5f];
3852        buf.extend_from_slice(&((size - 65_821) as u32).to_be_bytes()[1..]);
3853        buf.resize(buf.len() + size, b'a');
3854        let mut state = VerificationState::new(buf.len());
3855        Decoder::new(&buf, 0)
3856            .skip_value_for_verification(&mut state)
3857            .unwrap();
3858    }
3859
3860    #[test]
3861    fn verification_work_allowance_does_not_overflow() {
3862        let mut state = VerificationState::new(usize::MAX);
3863        assert_eq!(state.work_remaining, usize::MAX);
3864        state.charge(usize::MAX, 0).unwrap();
3865        assert!(matches!(
3866            state.charge(1, 0).map_err(|error| *error),
3867            Err(MaxMindDbError::ResourceLimit { .. })
3868        ));
3869        assert_eq!(state.work_remaining, 0);
3870    }
3871
3872    #[test]
3873    fn test_verification_rejects_invalid_bool_size() {
3874        // Extended bool type with an invalid size value of two.
3875        let mut decoder = Decoder::new(&[0x02, 0x07], 0);
3876        let err = decoder
3877            .skip_value_for_verification(&mut VerificationState::new(decoder.limit))
3878            .unwrap_err();
3879
3880        assert!(matches!(*err, MaxMindDbError::InvalidDatabase { .. }));
3881    }
3882
3883    #[test]
3884    fn test_verification_rejects_and_does_not_cache_invalid_utf8() {
3885        let buf = [0x41, 0xff];
3886        let mut state = VerificationState::new(buf.len());
3887
3888        for _ in 0..2 {
3889            let mut decoder = Decoder::new(&buf, 0);
3890            let err = decoder.skip_value_for_verification(&mut state).unwrap_err();
3891
3892            assert!(matches!(*err, MaxMindDbError::InvalidDatabase { .. }));
3893            assert!(err.to_string().contains("invalid UTF-8"));
3894            assert!(state.validated.is_empty());
3895            assert!(state.active.is_empty());
3896        }
3897
3898        #[cfg(not(feature = "unsafe-str-decode"))]
3899        {
3900            let mut decoder = Decoder::new(&buf, 0);
3901            let err = String::deserialize(&mut decoder).unwrap_err();
3902            assert!(err.to_string().contains("invalid UTF-8"));
3903        }
3904    }
3905
3906    fn append_pointer(buf: &mut Vec<u8>, target: usize) {
3907        assert!(target < 2048);
3908        buf.push(0x20 | ((target >> 8) as u8));
3909        buf.push(target as u8);
3910    }
3911
3912    #[test]
3913    fn test_verification_caches_shared_pointer_targets() {
3914        // A false boolean leaf followed by arrays containing two pointers to
3915        // the preceding value. Without caching, verification work doubles at
3916        // every level even though the encoded graph grows only linearly.
3917        let mut buf = vec![0x00, 0x07];
3918        let mut target = 0;
3919        const LEVELS: usize = 20;
3920
3921        for _ in 0..LEVELS {
3922            let array = buf.len();
3923            buf.extend_from_slice(&[0x02, 0x04]);
3924            append_pointer(&mut buf, target);
3925            append_pointer(&mut buf, target);
3926            target = array;
3927        }
3928
3929        let mut decoder = Decoder::new(&buf, target);
3930        let mut state = VerificationState::new(buf.len());
3931        decoder.skip_value_for_verification(&mut state).unwrap();
3932
3933        assert_eq!(state.validated.len(), LEVELS + 1);
3934        assert!(state.active.is_empty());
3935    }
3936
3937    /// Builds one-element arrays that each hold a pointer to the next array,
3938    /// ending in `terminal`. Returns the buffer and each array's offset, first
3939    /// link first. A link adds two skip-depth levels: the array and its pointer.
3940    fn pointer_linked_arrays(links: usize, terminal: &[u8]) -> (Vec<u8>, Vec<usize>) {
3941        let mut buf = terminal.to_vec();
3942        let mut offsets = Vec::with_capacity(links);
3943        let mut target = 0;
3944        for _ in 0..links {
3945            let array = buf.len();
3946            buf.extend_from_slice(&[0x01, 0x04]);
3947            append_pointer(&mut buf, target);
3948            offsets.push(array);
3949            target = array;
3950        }
3951        offsets.reverse();
3952        (buf, offsets)
3953    }
3954
3955    fn verify_roots(buf: &[u8], roots: &[usize]) -> super::DecodeResult<VerificationState> {
3956        let mut state = VerificationState::new(buf.len());
3957        for &root in roots {
3958            Decoder::new(buf, root).skip_value_for_verification(&mut state)?;
3959        }
3960        Ok(state)
3961    }
3962
3963    #[test]
3964    fn verification_allows_cached_targets_that_fit_the_skip_depth() {
3965        // 64 links ending in a scalar are exactly 128 levels deep. The middle
3966        // link is 64 levels deep and sits 64 levels below the first.
3967        let (buf, offsets) = pointer_linked_arrays(64, &[0x00, 0x07]);
3968        let (first, middle) = (offsets[0], offsets[32]);
3969        for roots in [[first, middle], [middle, first]] {
3970            let state = verify_roots(&buf, &roots).unwrap();
3971            assert_eq!(state.validated[&(first as u32)], 128);
3972            assert_eq!(state.validated[&(middle as u32)], 64);
3973            assert!(state.active.is_empty());
3974        }
3975    }
3976
3977    #[test]
3978    #[cfg(target_pointer_width = "64")]
3979    fn verification_rejects_offsets_beyond_32_bits() {
3980        let too_large = usize::try_from(u64::from(u32::MAX) + 1).unwrap();
3981        assert_eq!(VerificationState::key(u32::MAX as usize).unwrap(), u32::MAX);
3982        let err = VerificationState::key(too_large).unwrap_err();
3983        assert!(err.to_string().contains("does not fit in 32 bits"), "{err}");
3984    }
3985
3986    #[test]
3987    fn verification_rechecks_depth_of_cached_pointer_targets() {
3988        // Ending in a one-element array adds one level, for 129 in total. The
3989        // middle link alone is 65 levels deep and valid as a root, but the
3990        // first link reaches it 64 levels down, one level past the limit.
3991        let (buf, offsets) = pointer_linked_arrays(64, &[0x01, 0x04, 0x00, 0x07]);
3992        let (first, middle) = (offsets[0], offsets[32]);
3993        verify_roots(&buf, &[middle]).unwrap();
3994        // Before the depth of cached targets was rechecked, verifying the
3995        // middle first let the first link pass.
3996        for roots in [[first, middle], [middle, first]] {
3997            let err = verify_roots(&buf, &roots).map(|_| ()).unwrap_err();
3998            assert!(err
3999                .to_string()
4000                .contains("exceeded maximum data structure depth"));
4001            if roots[0] == middle {
4002                // A cached target that is too deep is reported at its offset.
4003                assert!(matches!(
4004                    *err,
4005                    MaxMindDbError::InvalidDatabase { offset: Some(offset), .. } if offset == middle
4006                ));
4007            } else {
4008                assert!(matches!(*err, MaxMindDbError::InvalidDatabase { .. }));
4009            }
4010        }
4011    }
4012
4013    fn verify_buffer(buf: &[u8], roots: &[usize]) -> DecodeResult<()> {
4014        let mut state = VerificationState::new(buf.len());
4015        let result = roots
4016            .iter()
4017            .try_for_each(|&root| Decoder::new(buf, root).skip_value_for_verification(&mut state));
4018        // Errors must not leave offsets marked as in progress.
4019        assert!(state.active.is_empty());
4020        result
4021    }
4022
4023    fn assert_invalid_database(result: DecodeResult<()>, message: &str) {
4024        let err = result.unwrap_err();
4025        assert!(
4026            matches!(*err, MaxMindDbError::InvalidDatabase { .. }),
4027            "unexpected error: {err}"
4028        );
4029        assert!(err.to_string().contains(message), "unexpected error: {err}");
4030    }
4031
4032    #[test]
4033    fn test_verification_accepts_root_pointer() {
4034        // A data record may itself be a pointer to a non-pointer value.
4035        let mut buf = vec![0x00, 0x07]; // false
4036        append_pointer(&mut buf, 0);
4037        verify_buffer(&buf, &[2]).unwrap();
4038    }
4039
4040    #[test]
4041    fn test_verification_rejects_pointer_chains() {
4042        // An array whose element points to a pointer to false.
4043        let mut buf = vec![0x00, 0x07];
4044        append_pointer(&mut buf, 0);
4045        buf.extend_from_slice(&[0x01, 0x04]);
4046        append_pointer(&mut buf, 2);
4047        let err = verify_buffer(&buf, &[4]).unwrap_err();
4048        // Reported just past the target pointer's control byte.
4049        assert!(
4050            matches!(
4051                *err,
4052                MaxMindDbError::InvalidDatabase {
4053                    offset: Some(3),
4054                    ..
4055                }
4056            ),
4057            "unexpected error: {err}"
4058        );
4059        assert!(err
4060            .to_string()
4061            .contains("pointer points to another pointer"));
4062
4063        // A root pointer to a pointer.
4064        assert_invalid_database(
4065            verify_buffer(&buf, &[6]),
4066            "pointer points to another pointer",
4067        );
4068    }
4069
4070    #[test]
4071    fn test_verification_rejects_pointer_to_verified_root_pointer() {
4072        // The root pointer at offset 2 is valid by itself. A later pointer to
4073        // it must still fail even though verification already visited it.
4074        let mut buf = vec![0x00, 0x07];
4075        append_pointer(&mut buf, 0);
4076        buf.extend_from_slice(&[0x01, 0x04]);
4077        append_pointer(&mut buf, 2);
4078        assert_invalid_database(
4079            verify_buffer(&buf, &[2, 4]),
4080            "pointer points to another pointer",
4081        );
4082    }
4083
4084    #[test]
4085    fn test_verification_accepts_inline_and_pointer_string_keys() {
4086        // "a", then a map with an inline "b" key and a pointer to "a".
4087        let mut buf = vec![0x41, b'a'];
4088        buf.extend_from_slice(&[0xe2, 0x41, b'b', 0x00, 0x07]);
4089        append_pointer(&mut buf, 0);
4090        buf.extend_from_slice(&[0x00, 0x07]);
4091        verify_buffer(&buf, &[0, 2]).unwrap();
4092        // The key target is checked the first time through the map, too.
4093        verify_buffer(&buf, &[2]).unwrap();
4094    }
4095
4096    #[test]
4097    fn test_verification_rejects_key_pointer_to_invalid_utf8() {
4098        // A string with invalid UTF-8, then a map whose key points to it.
4099        let mut buf = vec![0x41, 0xff, 0xe1];
4100        append_pointer(&mut buf, 0);
4101        buf.extend_from_slice(&[0x00, 0x07]);
4102        let mut state = VerificationState::new(buf.len());
4103        for _ in 0..2 {
4104            let err = Decoder::new(&buf, 2)
4105                .skip_value_for_verification(&mut state)
4106                .unwrap_err();
4107            assert!(
4108                err.to_string().contains("invalid UTF-8"),
4109                "unexpected error: {err}"
4110            );
4111            assert!(state.validated.is_empty());
4112            assert!(state.active.is_empty());
4113        }
4114    }
4115
4116    #[test]
4117    fn test_verification_rejects_non_string_map_keys() {
4118        // A map with an inline uint32 key.
4119        let buf = [0xe1, 0xc1, 0x05, 0x00, 0x07];
4120        assert_invalid_database(
4121            verify_buffer(&buf, &[0]),
4122            "expected string map key, got type 6",
4123        );
4124
4125        // A map with an inline map key.
4126        let buf = [0xe1, 0xe0, 0x00, 0x07];
4127        assert_invalid_database(
4128            verify_buffer(&buf, &[0]),
4129            "expected string map key, got type 7",
4130        );
4131    }
4132
4133    #[test]
4134    fn test_verification_rejects_pointer_to_non_string_map_key() {
4135        // A uint32, then a map whose key points to it. Verifying the uint32
4136        // first must not let the cached target pass as a key.
4137        let mut buf = vec![0xc1, 0x05];
4138        buf.push(0xe1);
4139        append_pointer(&mut buf, 0);
4140        buf.extend_from_slice(&[0x00, 0x07]);
4141        assert_invalid_database(
4142            verify_buffer(&buf, &[0, 2]),
4143            "expected string map key, got type 6",
4144        );
4145        let err = verify_buffer(&buf, &[2]).unwrap_err();
4146        assert!(
4147            matches!(
4148                *err,
4149                MaxMindDbError::InvalidDatabase {
4150                    offset: Some(5),
4151                    ..
4152                }
4153            ),
4154            "unexpected error: {err}"
4155        );
4156        assert!(err
4157            .to_string()
4158            .contains("expected string map key, got type 6"));
4159
4160        // A key pointing to an extended-type value (false).
4161        let mut buf = vec![0x00, 0x07, 0xe1];
4162        append_pointer(&mut buf, 0);
4163        buf.extend_from_slice(&[0x00, 0x07]);
4164        assert_invalid_database(
4165            verify_buffer(&buf, &[2]),
4166            "expected string map key, got type 14",
4167        );
4168    }
4169
4170    #[test]
4171    fn test_verification_reports_unknown_map_key_types() {
4172        // An inline key with extended type 7 + 0xff.
4173        let buf = [0xe1, 0x00, 0xff, 0x00, 0x07];
4174        assert_invalid_database(verify_buffer(&buf, &[0]), "unknown data type: 262");
4175
4176        // A key pointing to an unknown type.
4177        let mut buf = vec![0x00, 0xff, 0xe1];
4178        append_pointer(&mut buf, 0);
4179        buf.extend_from_slice(&[0x00, 0x07]);
4180        assert_invalid_database(verify_buffer(&buf, &[2]), "unknown data type: 262");
4181    }
4182
4183    #[test]
4184    fn test_verification_reports_truncated_map_key_target() {
4185        // A key pointing to an extended control byte at the end of the
4186        // buffer. The bounds error keeps its own offset.
4187        let mut buf = vec![0xe1];
4188        append_pointer(&mut buf, 5);
4189        buf.extend_from_slice(&[0x00, 0x07, 0x00]);
4190        let err = verify_buffer(&buf, &[0]).unwrap_err();
4191        assert!(
4192            matches!(
4193                *err,
4194                MaxMindDbError::InvalidDatabase {
4195                    offset: Some(6),
4196                    ..
4197                }
4198            ),
4199            "unexpected error: {err}"
4200        );
4201        assert!(err.to_string().contains("unexpected end of buffer"));
4202    }
4203
4204    #[test]
4205    fn test_verification_reports_key_type_before_truncated_size() {
4206        // A key pointing to a uint32 whose size byte is missing. The control
4207        // byte already shows that the key is not a string.
4208        let mut buf = vec![0xe1];
4209        append_pointer(&mut buf, 5);
4210        buf.extend_from_slice(&[0x00, 0x07, 0xdd]);
4211        let err = verify_buffer(&buf, &[0]).unwrap_err();
4212        assert!(
4213            matches!(
4214                *err,
4215                MaxMindDbError::InvalidDatabase {
4216                    offset: Some(3),
4217                    ..
4218                }
4219            ),
4220            "unexpected error: {err}"
4221        );
4222        assert!(err
4223            .to_string()
4224            .contains("expected string map key, got type 6"));
4225
4226        // The same truncated uint32 as an inline key.
4227        assert_invalid_database(
4228            verify_buffer(&[0xe1, 0xdd], &[0]),
4229            "expected string map key, got type 6",
4230        );
4231    }
4232
4233    #[test]
4234    fn test_verification_reports_unknown_key_target_at_target() {
4235        fn assert_unknown_type_at(buf: &[u8], offset: usize) {
4236            let err = verify_buffer(buf, &[0]).unwrap_err();
4237            assert!(
4238                matches!(
4239                    *err,
4240                    MaxMindDbError::InvalidDatabase { offset: Some(o), .. } if o == offset
4241                ),
4242                "unexpected error: {err}"
4243            );
4244            assert!(err.to_string().contains("unknown data type: 39"));
4245        }
4246
4247        // Both pointers target extended type 39. The corrupt target is
4248        // reported just past its size bytes, whether it is reached as a key
4249        // or as a value.
4250        for (target, size_len) in [(&[0x00, 0x20][..], 0), (&[0x1d, 0x20, 0x05][..], 1)] {
4251            let mut key = vec![0xe1];
4252            append_pointer(&mut key, 3);
4253            key.extend_from_slice(target);
4254            assert_unknown_type_at(&key, 5 + size_len);
4255
4256            let mut value = vec![0xe1, 0x41, b'a'];
4257            append_pointer(&mut value, 5);
4258            value.extend_from_slice(target);
4259            assert_unknown_type_at(&value, 7 + size_len);
4260        }
4261
4262        // With its size byte missing, the target gives the same bounds error
4263        // either way.
4264        let mut key = vec![0xe1];
4265        append_pointer(&mut key, 3);
4266        key.extend_from_slice(&[0x1d, 0x20]);
4267        let mut value = vec![0xe1, 0x41, b'a'];
4268        append_pointer(&mut value, 5);
4269        value.extend_from_slice(&[0x1d, 0x20]);
4270        let key_err = verify_buffer(&key, &[0]).unwrap_err().to_string();
4271        let value_err = verify_buffer(&value, &[0]).unwrap_err().to_string();
4272        for err in [key_err, value_err] {
4273            assert!(err.ends_with("unexpected end of buffer"), "{err}");
4274        }
4275    }
4276
4277    #[test]
4278    fn test_verification_counts_key_pointers_like_value_pointers() {
4279        // "a", then `nesting` one-element arrays around a map that reaches "a"
4280        // through a pointer, either as its key or as its value. Both pointers
4281        // add one skip-depth level, whether or not "a" is already cached.
4282        fn nested_map(nesting: usize, key_pointer: bool) -> (Vec<u8>, usize) {
4283            let mut buf = vec![0x41, b'a'];
4284            let root = buf.len();
4285            for _ in 0..nesting {
4286                buf.extend_from_slice(&[0x01, 0x04]);
4287            }
4288            buf.push(0xe1);
4289            if key_pointer {
4290                append_pointer(&mut buf, 0);
4291                buf.extend_from_slice(&[0x00, 0x07]);
4292            } else {
4293                buf.extend_from_slice(&[0x41, b'k']);
4294                append_pointer(&mut buf, 0);
4295            }
4296            (buf, root)
4297        }
4298
4299        for key_pointer in [false, true] {
4300            let (buf, root) = nested_map(126, key_pointer);
4301            verify_buffer(&buf, &[root]).unwrap();
4302            verify_buffer(&buf, &[0, root]).unwrap();
4303
4304            let (buf, root) = nested_map(127, key_pointer);
4305            for roots in [&[root][..], &[0, root]] {
4306                assert_depth_limit_error(verify_buffer(&buf, roots));
4307            }
4308        }
4309    }
4310
4311    fn assert_depth_limit_error(result: DecodeResult<()>) {
4312        let err = result.unwrap_err();
4313        assert!(
4314            err.to_string()
4315                .contains("exceeded maximum data structure depth"),
4316            "unexpected error: {err}"
4317        );
4318    }
4319
4320    #[test]
4321    fn test_verification_rejects_map_key_pointer_chain() {
4322        // "a", a pointer to it, then a map whose key points to that pointer.
4323        let mut buf = vec![0x41, b'a'];
4324        append_pointer(&mut buf, 0);
4325        buf.push(0xe1);
4326        append_pointer(&mut buf, 2);
4327        buf.extend_from_slice(&[0x00, 0x07]);
4328        let err = verify_buffer(&buf, &[4]).unwrap_err();
4329        // Reported just past the target pointer's control byte, as for value
4330        // pointers.
4331        assert!(
4332            matches!(
4333                *err,
4334                MaxMindDbError::InvalidDatabase {
4335                    offset: Some(3),
4336                    ..
4337                }
4338            ),
4339            "unexpected error: {err}"
4340        );
4341        assert!(err
4342            .to_string()
4343            .contains("pointer points to another pointer"));
4344    }
4345
4346    #[test]
4347    fn test_verification_rejects_data_pointer_cycles() {
4348        // Two single-element arrays whose values point to each other.
4349        let mut buf = vec![0x01, 0x04];
4350        append_pointer(&mut buf, 4);
4351        buf.extend_from_slice(&[0x01, 0x04]);
4352        append_pointer(&mut buf, 0);
4353
4354        let mut decoder = Decoder::new(&buf, 0);
4355        let err = decoder
4356            .skip_value_for_verification(&mut VerificationState::new(decoder.limit))
4357            .unwrap_err();
4358
4359        assert!(matches!(*err, MaxMindDbError::InvalidDatabase { .. }));
4360        assert!(err.to_string().contains("cyclic data pointer"));
4361    }
4362}