Skip to main content

serde_unknown/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![doc = include_str!("../README.md")]
3
4extern crate alloc;
5
6use alloc::{string::String, vec::Vec};
7use compact_str::{CompactString, format_compact};
8use core::fmt;
9use derive_more::{Constructor, Deref, DerefMut};
10use pastey::paste;
11use serde::de::{self, DeserializeSeed, EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor};
12use serde::{Deserialize, Deserializer};
13
14/// A path represented by nodes that borrow their parents.
15///
16/// Callbacks receive a temporary path. [`Path::matches`] compares its segments
17/// without allocating. [`Display`](fmt::Display) prints keys separated by dots
18/// and indices in brackets, omitting the root prefix for non-root paths.
19#[derive(Debug)]
20pub enum Path<'p> {
21    /// The root value, displayed as `<root>`.
22    Root,
23    /// A sequence element with its parent path and zero-based index.
24    Index(&'p Path<'p>, usize),
25    /// A map or struct value with its parent path and key.
26    Key(&'p Path<'p>, CompactString),
27}
28
29impl<'p> Path<'p> {
30    /// Matches the entire path against root-to-leaf segments without allocating.
31    ///
32    /// The first segment must be `"<root>"`. `"*"` matches exactly one key or
33    /// sequence index, but cannot replace the root segment. Indices are compared
34    /// as `usize` values. Dots and brackets inside keys are literal; `"*"` has no
35    /// escape syntax. Matching takes linear time and constant auxiliary space.
36    ///
37    /// ```
38    /// use serde_unknown::Path;
39    ///
40    /// let root = Path::Root;
41    /// let items = Path::Key(&root, "items".into());
42    /// let entry = Path::Index(&items, 3);
43    /// let extra = Path::Key(&entry, "extra".into());
44    ///
45    /// assert!(extra.matches(&["<root>", "items", "3", "extra"]));
46    /// assert!(extra.matches(&["<root>", "items", "*", "extra"]));
47    /// assert!(!extra.matches(&["items", "3", "extra"]));
48    /// ```
49    pub fn matches(&self, pattern: &[&str]) -> bool {
50        let mut path = self;
51        let mut segments = pattern.iter().rev();
52        while let Some(&segment) = segments.next() {
53            path = match path {
54                Self::Root => return segment == "<root>" && segments.next().is_none(),
55                Self::Index(parent, index) => {
56                    if segment != "*" && segment.parse::<usize>().ok() != Some(*index) {
57                        return false;
58                    }
59                    parent
60                }
61                Self::Key(parent, key) => {
62                    if segment != "*" && segment != key.as_str() {
63                        return false;
64                    }
65                    parent
66                }
67            };
68        }
69        false
70    }
71}
72
73impl fmt::Display for Path<'_> {
74    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
75        match self {
76            Self::Root => formatter.write_str("<root>"),
77            Self::Index(Self::Root, index) => write!(formatter, "[{index}]"),
78            Self::Index(parent, index) => write!(formatter, "{parent}[{index}]"),
79            Self::Key(Self::Root, key) => formatter.write_str(key),
80            Self::Key(parent, key) => write!(formatter, "{parent}.{key}"),
81        }
82    }
83}
84
85macro_rules! implement {
86    ([$($generic:tt)*] ($($header:tt)*) -> $error:ty; $($body:tt)*) => {
87        #[cfg(feature = "peek")]
88        implement! { #impl [$($generic)*] ($($header)*) where [
89            F: FnMut(&Path<'_>) -> Result<Option<C>, $error>,
90            P: FnMut(&Path<'_>, Option<C>, serde_json::Value) -> Result<(), $error>,
91        ];
92            $($body)*
93        }
94
95        #[cfg(not(feature = "peek"))]
96        implement! { #impl [$($generic)*] ($($header)*) where [
97            F: FnMut(&Path<'_>) -> Result<Option<C>, $error>,
98        ];
99            $($body)*
100        }
101    };
102    (@builder $missing:ident [$($generic:tt)*] ($($header:tt)*) -> $error:ty;
103        $context:ty $(where [$($bound:tt)*])?
104    ) => {
105        implement! { #impl [$($generic)*] ($($header)*) $(where [$($bound)*])?;
106            /// Deserializes `T` using the configured callbacks.
107            ///
108            /// Returns the first callback error unchanged, or the underlying
109            /// deserializer's result when no callback rejects the input.
110            pub fn deserialize<T: Deserialize<'de>>(self) -> Result<T, $error> {
111                Builder {
112                    deserializer: self.deserializer,
113                    filter: implement!(#field $missing self.filter ($context, $error)),
114                    peek: implement!(#field $missing self.peek ($context, $error)),
115                }
116                .deserialize()
117            }
118        }
119    };
120    (#impl [$($generic:tt)*] ($($header:tt)*) $(where [$($bound:tt)*])?; $($body:tt)*) => {
121        impl<$($generic)*> $($header)* $(where $($bound)*)? {
122            $($body)*
123        }
124    };
125    (#field filter $receiver:ident.filter ($context:ty, $error:ty)) => {
126        None::<fn(&Path<'_>) -> Result<Option<$context>, $error>>
127    };
128    (#field peek $receiver:ident.peek ($context:ty, $error:ty)) => {
129        None::<fn(&Path<'_>, Option<$context>, serde_json::Value) -> Result<(), $error>>
130    };
131    (#field $missing:ident $receiver:ident.$field:ident ($context:ty, $error:ty)) => {
132        $receiver.$field
133    };
134}
135
136/// Unknown-field handling for any Serde [`Deserializer`].
137///
138/// Import this trait to call [`.deserialize(callback)`](Self::deserialize) or
139/// [`.track()`](Self::track) on a deserializer. The adapter supports structs that
140/// would otherwise reject unknown fields, including pbjson-generated messages.
141/// Known values retain the target type's deserialization behavior.
142///
143/// Unknown-field tracking does not support `#[serde(flatten)]`. Paths borrow
144/// stack-local nodes and cannot be kept after the callback returns.
145pub trait DeserializerExt<'de>: Deserializer<'de> {
146    /// Deserializes `T`, calling `callback` before each unknown value is consumed.
147    ///
148    /// Return `Ok(())` to continue or `Self::Error` to reject the input. The first
149    /// callback error is returned unchanged even if nested deserialization uses
150    /// a different error type or catches the intermediate error. No further
151    /// callbacks run after rejection. An unknown subtree produces one callback.
152    ///
153    /// ```
154    /// use serde::Deserialize;
155    /// use serde_unknown::DeserializerExt;
156    ///
157    /// #[derive(Deserialize)]
158    /// #[serde(deny_unknown_fields)]
159    /// struct Config { port: u16 }
160    ///
161    /// let mut deserializer = serde_json::Deserializer::from_str(
162    ///     r#"{"port":8080,"future":true}"#,
163    /// );
164    /// let mut count = 0;
165    /// let config: Config = (&mut deserializer).deserialize(|path| {
166    ///     assert!(path.matches(&["<root>", "future"]));
167    ///     count += 1;
168    ///     Ok(())
169    /// })?;
170    /// deserializer.end()?;
171    /// assert_eq!(config.port, 8080);
172    /// assert_eq!(count, 1);
173    /// # Ok::<(), serde_json::Error>(())
174    /// ```
175    fn deserialize<T, F>(self, mut callback: F) -> Result<T, Self::Error>
176    where
177        T: Deserialize<'de>,
178        F: FnMut(&Path<'_>) -> Result<(), Self::Error>,
179    {
180        self.track()
181            .filter(move |path| callback(path).map(|()| None::<()>))
182            .deserialize()
183    }
184
185    /// Creates a [`Builder`] with neither callback configured.
186    ///
187    /// Use [`Builder::filter`] to select unknown values or reject their paths.
188    /// With the `peek` feature, `Builder::peek` can inspect their parsed values.
189    /// With neither callback, unknown values are consumed directly.
190    fn track(self) -> Builder<Self> {
191        Builder {
192            deserializer: self,
193            filter: None,
194            peek: None,
195        }
196    }
197}
198
199impl<'de, D: Deserializer<'de>> DeserializerExt<'de> for D {}
200
201/// Configures optional callbacks before deserializing a value.
202///
203/// Created by [`DeserializerExt::track`]. Callbacks retain their concrete types
204/// and need no boxing. [`filter`](Self::filter) and `peek` (with the `peek`
205/// feature) can be configured in either order. Call `.deserialize()` to execute.
206///
207/// | Callbacks | Behavior |
208/// | --- | --- |
209/// | Neither | Consume unknown values without calling user code. |
210/// | Filter only | Run the filter and consume values directly. |
211/// | Peek only | Inspect every unknown value with context `None::<()>`. |
212/// | Both | Inspect selected values with the filter's `Some(context)`. |
213///
214/// Filter and peek errors reject the input. The first callback error is returned
215/// unchanged, even if nested code catches the intermediate error.
216#[must_use]
217pub struct Builder<D, F = (), P = ()> {
218    deserializer: D,
219    filter: Option<F>,
220    peek: Option<P>,
221}
222
223impl<D, F, P> Builder<D, F, P> {
224    /// Sets a callback that runs before an unknown value is consumed.
225    ///
226    /// Return `Some(context)` to select the value for `peek`, `None` to consume
227    /// it directly, or `D::Error` to reject the input. The context type `C` is
228    /// chosen by the caller; `peek` receives `Some(context)` for selected values.
229    /// Without a peek callback, both successful results consume values directly.
230    /// Calling this method again replaces the previous filter.
231    ///
232    /// ```
233    /// use serde::{Deserialize, de::Error};
234    /// use serde_unknown::DeserializerExt;
235    ///
236    /// #[derive(Deserialize)]
237    /// struct Config { port: u16 }
238    ///
239    /// let mut deserializer = serde_json::Deserializer::from_str(
240    ///     r#"{"port":8080,"forbidden":true}"#,
241    /// );
242    /// let result: Result<Config, _> = (&mut deserializer)
243    ///     .track()
244    ///     .filter(|path| {
245    ///         if path.matches(&["<root>", "forbidden"]) {
246    ///             return Err(Error::custom("forbidden field"));
247    ///         }
248    ///         Ok(None::<()>)
249    ///     })
250    ///     .deserialize();
251    /// assert_eq!(result.err().unwrap().to_string(), "forbidden field");
252    /// ```
253    pub fn filter<'de, C, Filter>(self, filter: Filter) -> Builder<D, Filter, P>
254    where
255        D: Deserializer<'de>,
256        Filter: FnMut(&Path<'_>) -> Result<Option<C>, D::Error>,
257    {
258        Builder {
259            deserializer: self.deserializer,
260            filter: Some(filter),
261            peek: self.peek,
262        }
263    }
264
265    /// Sets a callback that receives an owned JSON value for selected fields.
266    ///
267    /// Requires the `peek` feature. A filter supplies `Some(context)`; returning
268    /// `None` from the filter skips this callback. Without a filter, every unknown
269    /// value is selected and the context is `None` with type `Option<()>`.
270    ///
271    /// The callback runs after the complete subtree is parsed. It is not called
272    /// if parsing fails. Return `Ok(())` to continue or `D::Error` to reject the
273    /// input. Calling this method again replaces the previous peek callback.
274    ///
275    /// Inspection can allocate and requires `deserialize_any` support and values
276    /// representable by [`serde_json::Value`]. Duplicate object keys and some
277    /// format-specific representations are not preserved.
278    ///
279    /// ```
280    /// use serde::Deserialize;
281    /// use serde_unknown::DeserializerExt;
282    ///
283    /// #[derive(Deserialize)]
284    /// struct Config { port: u16 }
285    ///
286    /// let mut deserializer = serde_json::Deserializer::from_str(
287    ///     r#"{"port":8080,"future":{"enabled":true},"other":false}"#,
288    /// );
289    /// let config: Config = (&mut deserializer)
290    ///     .track()
291    ///     .filter(|path| Ok(path.matches(&["<root>", "future"]).then_some("future")))
292    ///     .peek(|_, context, value| {
293    ///         assert_eq!(context, Some("future"));
294    ///         assert_eq!(value, serde_json::json!({"enabled": true}));
295    ///         Ok(())
296    ///     })
297    ///     .deserialize()?;
298    /// deserializer.end()?;
299    /// assert_eq!(config.port, 8080);
300    /// # Ok::<(), serde_json::Error>(())
301    /// ```
302    #[cfg(feature = "peek")]
303    pub fn peek<'de, C, Peek>(self, peek: Peek) -> Builder<D, F, Peek>
304    where
305        D: Deserializer<'de>,
306        Peek: FnMut(&Path<'_>, Option<C>, serde_json::Value) -> Result<(), D::Error>,
307    {
308        Builder {
309            deserializer: self.deserializer,
310            filter: self.filter,
311            peek: Some(peek),
312        }
313    }
314}
315
316implement! { @builder filter ['de, D: Deserializer<'de>] (Builder<D>) -> D::Error; () }
317
318#[cfg(feature = "peek")]
319implement! { @builder peek ['de, D: Deserializer<'de>, F, C] (Builder<D, F>) -> D::Error;
320    C where [F: FnMut(&Path<'_>) -> Result<Option<C>, D::Error>]
321}
322
323#[cfg(feature = "peek")]
324implement! { @builder filter ['de, D: Deserializer<'de>, P] (Builder<D, (), P>) -> D::Error;
325    () where [P: FnMut(&Path<'_>, Option<()>, serde_json::Value) -> Result<(), D::Error>]
326}
327
328implement! { ['de, D: Deserializer<'de>, F, P, C] (Builder<D, F, P>) -> D::Error;
329    /// Deserializes `T` using the configured callbacks.
330    ///
331    /// Returns the first callback error unchanged, or the underlying
332    /// deserializer's result when no callback rejects the input.
333    pub fn deserialize<T: Deserialize<'de>>(self) -> Result<T, D::Error> {
334        let mut state = State {
335            filter: self.filter,
336            peek: self.peek,
337            error: None,
338            key: None,
339            index: 0,
340        };
341        let path = Path::Root;
342        let result = T::deserialize(Tracker::new(self.deserializer, &mut state, &path));
343        state.error.map_or(result, Err)
344    }
345}
346
347struct State<E, F, P> {
348    filter: Option<F>,
349    #[cfg_attr(not(feature = "peek"), allow(dead_code))]
350    peek: Option<P>,
351    error: Option<E>,
352    key: Option<CompactString>,
353    index: usize,
354}
355
356impl<E, F, P> State<E, F, P> {
357    fn check<Error: de::Error, T>(&mut self, result: Result<T, E>) -> Result<T, Error> {
358        result.map_err(|error| {
359            self.error.get_or_insert(error);
360            Error::custom("unknown field rejected")
361        })
362    }
363
364    fn scope<T>(&mut self, visit: impl FnOnce(&mut Self) -> T) -> T {
365        let context = (self.key.take(), self.index);
366        self.index = 0;
367        let result = visit(self);
368        (self.key, self.index) = context;
369        result
370    }
371}
372
373#[derive(Constructor, Deref, DerefMut)]
374#[allow(clippy::redundant_field_names, reason = "rust-lang/rust-clippy#17525")]
375struct Tracker<'s, 'p, T, E, F, P> {
376    inner: T,
377    #[deref(forward)]
378    #[deref_mut(forward)]
379    state: &'s mut State<E, F, P>,
380    path: &'p Path<'p>,
381}
382
383#[derive(Constructor)]
384#[allow(clippy::redundant_field_names, reason = "rust-lang/rust-clippy#17525")]
385struct Struct<T> {
386    inner: T,
387    fields: &'static [&'static str],
388}
389
390#[derive(Constructor)]
391#[allow(clippy::redundant_field_names, reason = "rust-lang/rust-clippy#17525")]
392struct Field<'f, S> {
393    inner: &'f mut Option<S>,
394    fields: &'static [&'static str],
395}
396
397macro_rules! delegate {
398    (@de $($method:ident $(($($argument:ident: $ty:ty),*))?),* $(,)?) => {
399        paste! {$(
400            fn [<deserialize_ $method>]<V: Visitor<'de>>(self, $($($argument: $ty,)*)? visitor: V) -> Result<V::Value, Self::Error> {
401                self.inner.[<deserialize_ $method>]($($($argument,)*)? Tracker::new(visitor, self.state, self.path))
402            }
403        )*}
404    };
405    (@visit $($method:ident $(($($ty:ty)?))?),* $(,)?) => {
406        $( delegate!(#impl visit $method $(($($ty)?))?); )*
407    };
408    (@key $($method:ident $(($ty:ty))?),* $(,)?) => {
409        $( delegate!(#impl key $method $(($ty))?); )*
410    };
411    (#impl $mode:ident $method:ident) => {
412        delegate!(#impl $mode $method ($method));
413    };
414    (#impl visit $method:ident ()) => {
415        paste! {
416            fn [<visit_ $method>]<Error: de::Error>(self) -> Result<Self::Value, Error> {
417                self.inner.[<visit_ $method>]()
418            }
419        }
420    };
421    (#impl visit $method:ident ($ty:ty)) => {
422        paste! {
423            fn [<visit_ $method>]<Error: de::Error>(self, value: $ty) -> Result<Self::Value, Error> {
424                self.inner.[<visit_ $method>](value)
425            }
426        }
427    };
428    (#impl key $method:ident ($ty:ty)) => {
429        paste! {
430            fn [<visit_ $method>]<Error: de::Error>(mut self, value: $ty) -> Result<Self::Value, Error> {
431                if self.key.is_some() {
432                    self.key = Some(format_compact!("{value}"));
433                }
434                self.inner.[<visit_ $method>](value)
435            }
436        }
437    };
438    (@field @$mode:ident $($method:ident ($ty:ty, $deserializer:ident)),* $(,)?) => {
439        paste! {$(
440            fn [<visit_ $method>]<Error: de::Error>(self, value: $ty) -> Result<Self::Value, Error> {
441                delegate!(#impl field @$mode self(value, $deserializer))
442            }
443        )*}
444    };
445    (#impl field @key $receiver:ident ($value:ident, $deserializer:ident)) => {
446        if $receiver.fields.contains(&$value.as_ref()) {
447            delegate!(#impl field @plain $receiver($value, $deserializer))
448        } else {
449            Ok(None)
450        }
451    };
452    (#impl field @plain $receiver:ident ($value:ident, $deserializer:ident)) => {
453        $receiver.inner.take().unwrap()
454            .deserialize(de::value::$deserializer::new($value))
455            .map(Some)
456    };
457    (@plain $(fn $method:ident (&$receiver:ident $(, $argument:ident: $ty:ty)*) -> $result:ty;)+) => {
458        $( delegate!(#impl plain [&] fn $method($receiver $(, $argument: $ty)*) -> $result;); )+
459    };
460    (@plain $(fn $method:ident ($receiver:ident $(, $argument:ident: $ty:ty)*) -> $result:ty;)+) => {
461        $( delegate!(#impl plain [] fn $method($receiver $(, $argument: $ty)*) -> $result;); )+
462    };
463    (#impl plain [$($reference:tt)?] fn $method:ident ($receiver:ident $(, $argument:ident: $ty:ty)*) -> $result:ty;) => {
464        fn $method($($reference)? $receiver $(, $argument: $ty)*) -> $result {
465            $receiver.inner.$method($($argument),*)
466        }
467    };
468    (@$mode:ident $(
469        fn $method:ident <$generic:ident: $bound:ident<'de>> (
470            $receiver:ident,
471            $wrapped:ident: $ty:ty
472        ) -> $result:ty;
473    )+) => {
474        $(fn $method<$generic: $bound<'de>>($receiver, $wrapped: $ty) -> $result {
475            delegate!(#impl $mode $receiver.$method($wrapped))
476        })+
477    };
478    (@$mode:ident $(
479        fn $method:ident <$generic:ident: $bound:ident<'de>> (
480            $receiver:ident,
481            $argument:ident: $ty:ty,
482            $wrapped:ident: $input:ty
483        ) -> $result:ty;
484    )+) => {
485        $(fn $method<$generic: $bound<'de>>($receiver, $argument: $ty, $wrapped: $input) -> $result {
486            delegate!(#impl $mode $receiver.$method($wrapped, $argument))
487        })+
488    };
489    (#impl wrap $receiver:ident.$method:ident ($wrapped:ident $(, $argument:ident)?)) => {
490        $receiver.inner.$method($($argument,)? Tracker::new($wrapped, $receiver.state, $receiver.path))
491    };
492    (#impl scope $receiver:ident.$method:ident ($wrapped:ident $(, $argument:ident)?)) => {
493        $receiver.state.scope(|state| $receiver.inner.$method($($argument,)? Tracker::new($wrapped, state, $receiver.path)))
494    };
495    (#impl plain $receiver:ident.$method:ident ($wrapped:ident $(, $argument:ident)?)) => {
496        $receiver.inner.$method($($argument,)? $wrapped)
497    };
498}
499
500implement! { ['de, 's, 'p, D: Deserializer<'de>, E, F, P, C]
501    (Deserializer<'de> for Tracker<'s, 'p, D, E, F, P>) -> E;
502    type Error = D::Error;
503
504    delegate! { @de
505        any, bool, char, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64,
506        str, string, bytes, byte_buf, option, unit, seq, map, identifier,
507        unit_struct(name: &'static str), newtype_struct(name: &'static str), tuple(len: usize),
508        tuple_struct(name: &'static str, len: usize),
509        enum(name: &'static str, variants: &'static [&'static str])
510    }
511
512    fn deserialize_struct<V: Visitor<'de>>(
513        self,
514        name: &'static str,
515        fields: &'static [&'static str],
516        visitor: V,
517    ) -> Result<V::Value, Self::Error> {
518        self.inner.deserialize_struct(
519            name,
520            fields,
521            Tracker::new(Struct::new(visitor, fields), self.state, self.path),
522        )
523    }
524
525    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
526        if self.state.error.is_some() {
527            return Err(de::Error::custom("unknown field rejected"));
528        }
529        let context = match self.state.filter.as_mut() {
530            Some(filter) => {
531                let result = filter(self.path);
532                match self.state.check(result)? {
533                    Some(context) => Some(context),
534                    None => return self.inner.deserialize_ignored_any(visitor),
535                }
536            }
537            None => None,
538        };
539        #[cfg(feature = "peek")]
540        if let Some(peek) = self.state.peek.as_mut() {
541            let value = <serde_json::Value as Deserialize>::deserialize(self.inner)?;
542            let result = peek(self.path, context, value);
543            self.state.check(result)?;
544            return visitor.visit_unit();
545        }
546        #[cfg(not(feature = "peek"))]
547        let _ = context;
548        self.inner.deserialize_ignored_any(visitor)
549    }
550
551    delegate! { @plain
552        fn is_human_readable(&self) -> bool;
553    }
554}
555
556implement! { ['de, 's, 'p, V: Visitor<'de>, E, F, P, C]
557    (Visitor<'de> for Tracker<'s, 'p, V, E, F, P>) -> E;
558    type Value = V::Value;
559    delegate! { @plain
560        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result;
561    }
562
563    delegate! { @key
564        bool, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64, char,
565        str(&str), borrowed_str(&'de str), string(String),
566    }
567    delegate! { @visit
568        none(), unit(), bytes(&[u8]), borrowed_bytes(&'de [u8]), byte_buf(Vec<u8>),
569    }
570
571    delegate! { @wrap
572        fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error>;
573        fn visit_newtype_struct<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error>;
574    }
575    delegate! { @scope
576        fn visit_seq<A: SeqAccess<'de>>(self, sequence: A) -> Result<Self::Value, A::Error>;
577        fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error>;
578        fn visit_enum<A: EnumAccess<'de>>(self, enumeration: A) -> Result<Self::Value, A::Error>;
579    }
580}
581
582impl<'de, V: Visitor<'de>> Visitor<'de> for Struct<V> {
583    type Value = V::Value;
584
585    delegate! { @plain
586        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result;
587    }
588    delegate! { @visit
589        bool, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64, char,
590        str(&str), borrowed_str(&'de str), string(String),
591        none(), unit(), bytes(&[u8]), borrowed_bytes(&'de [u8]), byte_buf(Vec<u8>),
592    }
593    delegate! { @plain
594        fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error>;
595        fn visit_newtype_struct<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error>;
596        fn visit_seq<A: SeqAccess<'de>>(self, sequence: A) -> Result<Self::Value, A::Error>;
597        fn visit_enum<A: EnumAccess<'de>>(self, enumeration: A) -> Result<Self::Value, A::Error>;
598    }
599
600    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
601        self.inner.visit_map(Struct::new(map, self.fields))
602    }
603}
604
605impl<'de, A: MapAccess<'de>> MapAccess<'de> for Struct<A> {
606    type Error = A::Error;
607
608    fn next_key_seed<K: DeserializeSeed<'de>>(
609        &mut self,
610        seed: K,
611    ) -> Result<Option<K::Value>, A::Error> {
612        let mut seed = Some(seed);
613        loop {
614            match self
615                .inner
616                .next_key_seed(Field::new(&mut seed, self.fields))?
617            {
618                Some(None) => {
619                    self.inner.next_value::<de::IgnoredAny>()?;
620                }
621                key => return Ok(key.flatten()),
622            }
623        }
624    }
625
626    fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, A::Error> {
627        self.inner.next_value_seed(seed)
628    }
629}
630
631impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for Field<'_, S> {
632    type Value = Option<S::Value>;
633
634    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
635        deserializer.deserialize_identifier(self)
636    }
637}
638
639impl<'de, S: DeserializeSeed<'de>> Visitor<'de> for Field<'_, S> {
640    type Value = Option<S::Value>;
641
642    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
643        formatter.write_str("a struct field")
644    }
645
646    delegate! { @field @key
647        str(&str, StrDeserializer),
648        borrowed_str(&'de str, BorrowedStrDeserializer),
649        string(String, StringDeserializer),
650    }
651    delegate! { @field @plain
652        u64(u64, U64Deserializer),
653        bytes(&[u8], BytesDeserializer),
654        borrowed_bytes(&'de [u8], BorrowedBytesDeserializer),
655    }
656}
657
658implement! { ['de, 's, 'p, S: DeserializeSeed<'de>, E, F, P, C]
659    (DeserializeSeed<'de> for Tracker<'s, 'p, S, E, F, P>) -> E;
660    type Value = S::Value;
661    delegate! { @wrap
662        fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error>;
663    }
664}
665
666implement! { ['de, 's, 'p, A: SeqAccess<'de>, E, F, P, C]
667    (SeqAccess<'de> for Tracker<'s, 'p, A, E, F, P>) -> E;
668    type Error = A::Error;
669    fn next_element_seed<S: DeserializeSeed<'de>>(
670        &mut self,
671        seed: S,
672    ) -> Result<Option<S::Value>, A::Error> {
673        let path = Path::Index(self.path, self.index);
674        let result = self
675            .inner
676            .next_element_seed(Tracker::new(seed, self.state, &path));
677        if matches!(result, Ok(Some(_))) {
678            self.index += 1;
679        }
680        result
681    }
682    delegate! { @plain
683        fn size_hint(&self) -> Option<usize>;
684    }
685}
686
687implement! { ['de, 's, 'p, A: MapAccess<'de>, E, F, P, C]
688    (MapAccess<'de> for Tracker<'s, 'p, A, E, F, P>) -> E;
689    type Error = A::Error;
690    fn next_key_seed<K: DeserializeSeed<'de>>(
691        &mut self,
692        seed: K,
693    ) -> Result<Option<K::Value>, A::Error> {
694        self.key = Some(CompactString::const_new("?"));
695        self.inner
696            .next_key_seed(Tracker::new(seed, self.state, self.path))
697    }
698    fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, A::Error> {
699        let key = self
700            .key
701            .take()
702            .unwrap_or_else(|| CompactString::const_new("?"));
703        let path = Path::Key(self.path, key);
704        self.inner
705            .next_value_seed(Tracker::new(seed, self.state, &path))
706    }
707    delegate! { @plain
708        fn size_hint(&self) -> Option<usize>;
709    }
710}
711
712implement! { ['de, 's, 'p, A: EnumAccess<'de>, E, F, P, C]
713    (EnumAccess<'de> for Tracker<'s, 'p, A, E, F, P>) -> E;
714    type Error = A::Error;
715    type Variant = Tracker<'s, 'p, A::Variant, E, F, P>;
716    fn variant_seed<V: DeserializeSeed<'de>>(
717        self,
718        seed: V,
719    ) -> Result<(V::Value, Self::Variant), A::Error> {
720        let (value, access) = self.inner.variant_seed(seed)?;
721        Ok((value, Tracker::new(access, self.state, self.path)))
722    }
723}
724
725implement! { ['de, 's, 'p, A: VariantAccess<'de>, E, F, P, C]
726    (VariantAccess<'de> for Tracker<'s, 'p, A, E, F, P>) -> E;
727    type Error = A::Error;
728    delegate! { @plain
729        fn unit_variant(self) -> Result<(), Self::Error>;
730    }
731    delegate! { @wrap
732        fn newtype_variant_seed<S: DeserializeSeed<'de>>(self, seed: S) -> Result<S::Value, Self::Error>;
733    }
734    delegate! { @wrap
735        fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>;
736        fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error>;
737    }
738}