Skip to main content

strede/
borrow.rs

1use core::future::Future;
2use core::mem;
3use core::pin::Pin;
4use core::task::{Context, Poll};
5
6use crate::map_arm::{
7    ArmState, ConcatDispatchProj, ConcatDispatchState, ConcatRaceState, DetectDuplicatesOwned,
8    MapArmBase, MapArmSlot, NextKey, SlotDispatchProj, SlotDispatchState, SlotRaceState,
9    StackConcat, TagDispatchProj, TagDispatchState, TagInjectingStackOwned, TagRaceState,
10    VirtualArmSlot, WrapperDispatchProj, WrapperDispatchState, WrapperRaceState, poll_key_slot,
11};
12use crate::{Chunk, DeserializeError, Probe};
13
14// ---------------------------------------------------------------------------
15// Deserialize - the "what"  (mirrors serde::Deserialize)
16// ---------------------------------------------------------------------------
17
18/// Types that can deserialize themselves from a [`Deserializer`] stream.
19///
20/// Implement this to make a type readable by any format that implements
21/// [`Deserializer`].  The method drives the deserializer forward and returns
22/// the fully constructed value, or a fatal format error.
23///
24/// The `Extra` type parameter is side-channel context passed into
25/// [`Entry::deserialize_value`], [`SeqEntry::get`], [`MapKeyProbe::deserialize_key`], and
26/// [`MapValueProbe::deserialize_value`] at the call site.  Defaults to `()` for types that
27/// need no extra context.
28pub trait Deserialize<'de, Extra = ()>: Sized {
29    /// Deserialize `Self` from `d`, with caller-supplied side-channel `extra`.
30    ///
31    /// - `Ok(Probe::Hit((claim, value)))` - succeeded; thread `claim` back to the caller.
32    /// - `Ok(Probe::Miss)` - token type didn't match; stream not advanced.
33    /// - `Err(e)` - fatal format error (malformed data, I/O failure).
34    async fn deserialize<D: Deserializer<'de>>(
35        d: D,
36        extra: Extra,
37    ) -> Result<Probe<(D::Claim, Self)>, D::Error>;
38}
39
40// ---------------------------------------------------------------------------
41// Deserializer - stream handle
42// ---------------------------------------------------------------------------
43
44/// A stream of tokens that can be decoded into Rust values.
45///
46/// The deserializer owns the stream and is the sole means of advancing it -
47/// all advancement goes through [`Deserializer::entry`].  Type probing is done
48/// through [`Entry`] handles handed to the closure.
49pub trait Deserializer<'de>: Sized {
50    /// Fatal error type produced by this format.
51    type Error: DeserializeError;
52
53    /// Proof-of-consumption token returned from [`Deserializer::entry`].
54    type Claim: 'de;
55
56    /// The claim type produced by entry handles ([`Entry::Claim`]).
57    /// Distinct from `Claim` to allow implementations to use different claim
58    /// types at the deserializer level vs the entry level (e.g. flatten facades).
59    type EntryClaim: 'de;
60
61    /// Owned handle for one item slot.  See [`Entry`].
62    type Entry: Entry<'de, Claim = Self::EntryClaim, Error = Self::Error>;
63
64    /// Advance to the next item in the stream.
65    ///
66    /// Passes `N` owned [`Entry`] handles to `f`.  When a probe inside `f`
67    /// resolves `Ok(Probe::Hit((claim, r)))`, the winning arm returns it;
68    /// `entry` verifies the claim and returns `Ok(Probe::Hit((claim, r)))`.
69    /// Returns `Err(e)` if a fatal error occurs before or during `f`.
70    /// `Ok(Probe::Miss)` propagates upward if no probe matched.
71    /// `Pending` until a token is available.
72    ///
73    /// Use `N > 1` to race multiple probe arms via [`select_probe!`](crate::select_probe) without
74    /// borrow conflicts.  Handles dropped without resolving do not advance
75    /// the stream.
76    async fn entry<const N: usize, F, Fut, R>(
77        self,
78        f: F,
79    ) -> Result<Probe<(Self::Claim, R)>, Self::Error>
80    where
81        F: FnMut([Self::Entry; N]) -> Fut,
82        Fut: Future<Output = Result<Probe<(Self::EntryClaim, R)>, Self::Error>>;
83}
84
85// ---------------------------------------------------------------------------
86// Entry - type-probing handle for one item slot
87// ---------------------------------------------------------------------------
88
89/// Owned handle for one item slot, passed into the closure of [`Deserializer::entry`].
90///
91/// Each probe consumes `self` and resolves to `Ok(Probe::Hit((Claim, T)))` when
92/// the current token is of type `T`, `Ok(Probe::Miss)` if the type doesn't
93/// match or the token is a different kind, or `Err(e)` on a fatal format error.
94/// The `Claim` must be returned from the closure so `next` can advance the stream.
95///
96/// # For implementors
97///
98/// Type mismatches **must** return `Ok(Probe::Miss)` - never `Err`.  `Err` is
99/// reserved for fatal format errors (malformed data, I/O failure).
100///
101/// Use `N > 1` in `entry` to race arms via [`select_probe!`](crate::select_probe):
102///
103/// ```rust,ignore
104/// let value = d.entry(|[e1, e2, e3, e4]| async {
105///     select_probe! {
106///         e1.deserialize_bool(),
107///         e2.deserialize_i64(),
108///         async move {
109///             let (c, v) = hit!(e3.deserialize_str().await);
110///             Ok(Probe::Hit((c, Value::Str(v))))
111///         },
112///         async move {
113///             let mut m = hit!(e4.deserialize_map().await);
114///             let (c, v) = collect_map(m).await?;
115///             Ok(Probe::Hit((c, Value::Map(v))))
116///         },
117///     }
118/// }).await?;
119/// ```
120pub trait Entry<'de>: Sized {
121    /// Fatal error type; must match the parent [`Deserializer::Error`].
122    type Error: DeserializeError;
123
124    /// Proof-of-consumption token.  Must be returned from the `next` closure
125    /// alongside the caller's value so the deserializer can advance the stream.
126    type Claim: 'de;
127
128    type StrChunks: StrAccess<Claim = Self::Claim, Error = Self::Error>;
129    type BytesChunks: BytesAccess<Claim = Self::Claim, Error = Self::Error>;
130    type Map: MapAccess<'de, MapClaim = Self::Claim, Error = Self::Error>;
131    type Seq: SeqAccess<'de, SeqClaim = Self::Claim, Error = Self::Error>;
132
133    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
134    async fn deserialize_bool(self) -> Result<Probe<(Self::Claim, bool)>, Self::Error>;
135    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
136    async fn deserialize_u8(self) -> Result<Probe<(Self::Claim, u8)>, Self::Error>;
137    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
138    async fn deserialize_u16(self) -> Result<Probe<(Self::Claim, u16)>, Self::Error>;
139    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
140    async fn deserialize_u32(self) -> Result<Probe<(Self::Claim, u32)>, Self::Error>;
141    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
142    async fn deserialize_u64(self) -> Result<Probe<(Self::Claim, u64)>, Self::Error>;
143    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
144    async fn deserialize_u128(self) -> Result<Probe<(Self::Claim, u128)>, Self::Error>;
145    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
146    async fn deserialize_i8(self) -> Result<Probe<(Self::Claim, i8)>, Self::Error>;
147    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
148    async fn deserialize_i16(self) -> Result<Probe<(Self::Claim, i16)>, Self::Error>;
149    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
150    async fn deserialize_i32(self) -> Result<Probe<(Self::Claim, i32)>, Self::Error>;
151    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
152    async fn deserialize_i64(self) -> Result<Probe<(Self::Claim, i64)>, Self::Error>;
153    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
154    async fn deserialize_i128(self) -> Result<Probe<(Self::Claim, i128)>, Self::Error>;
155    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
156    async fn deserialize_f32(self) -> Result<Probe<(Self::Claim, f32)>, Self::Error>;
157    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
158    async fn deserialize_f64(self) -> Result<Probe<(Self::Claim, f64)>, Self::Error>;
159    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
160    async fn deserialize_char(self) -> Result<Probe<(Self::Claim, char)>, Self::Error>;
161    /// Attempt a **zero-copy** string borrow.
162    ///
163    /// Hits only when the format can return the entire string as a single
164    /// contiguous `&'de str` slice - i.e. with no escape sequences or
165    /// transcoding.  Returns `Ok(Probe::Miss)` when the token is a string
166    /// but cannot be represented that way (e.g. JSON `"\n"`), so that a
167    /// concurrent [`Entry::deserialize_str_chunks`] arm can take over via
168    /// `select_probe!`.  This makes `Cow<str>` callers easy to write: race
169    /// the two methods and borrow when free, allocate only when necessary.
170    ///
171    /// `Ok(Probe::Miss)` on type mismatch *or* when zero-copy is unavailable;
172    /// `Err` on fatal format error only.
173    async fn deserialize_str(self) -> Result<Probe<(Self::Claim, &'de str)>, Self::Error>;
174    /// Begin streaming a string chunk-by-chunk.  The [`Entry::Claim`] is
175    /// returned by [`StrAccess::next_str`] when the string is exhausted.
176    /// Handles all strings including those with escape sequences.
177    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
178    async fn deserialize_str_chunks(self) -> Result<Probe<Self::StrChunks>, Self::Error>;
179    /// Attempt a **zero-copy** bytes borrow.  Same Miss semantics as
180    /// [`Entry::deserialize_str`]: hits only when the entire value is
181    /// available as a contiguous `&'de [u8]` slice; returns `Miss` otherwise
182    /// so a [`Entry::deserialize_bytes_chunks`] arm can handle the rest.
183    /// `Ok(Probe::Miss)` on type mismatch *or* when zero-copy is unavailable;
184    /// `Err` on fatal format error only.
185    async fn deserialize_bytes(self) -> Result<Probe<(Self::Claim, &'de [u8])>, Self::Error>;
186    /// Begin streaming a byte string chunk-by-chunk.  The [`Entry::Claim`] is
187    /// returned by [`BytesAccess::next_bytes`] when the byte string is exhausted.
188    /// Handles all byte strings including those requiring transcoding.
189    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
190    async fn deserialize_bytes_chunks(self) -> Result<Probe<Self::BytesChunks>, Self::Error>;
191    /// Begin reading a map.  The [`Entry::Claim`] is returned by
192    /// [`MapAccess::iterate`] when the map is exhausted.
193    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
194    async fn deserialize_map(self) -> Result<Probe<Self::Map>, Self::Error>;
195    /// Begin reading a sequence.  The [`Entry::Claim`] is returned by
196    /// [`SeqAccess::next`] when the sequence is exhausted.
197    /// `Ok(Probe::Miss)` on type mismatch; `Err` on fatal format error only.
198    async fn deserialize_seq(self) -> Result<Probe<Self::Seq>, Self::Error>;
199
200    /// Deserialize an optional value.
201    ///
202    /// - Null token → `Ok(Probe::Hit((claim, None)))`
203    /// - Token matching `T::deserialize` → `Ok(Probe::Hit((claim, Some(v))))`
204    /// - Token matching neither → `Ok(Probe::Miss)`
205    /// - Fatal format error → `Err(e)`
206    async fn deserialize_option<T: Deserialize<'de, Extra>, Extra>(
207        self,
208        extra: Extra,
209    ) -> Result<Probe<(Self::Claim, Option<T>)>, Self::Error>;
210
211    /// Probe for a null token.
212    ///
213    /// - `Ok(Probe::Hit(claim))` - null token consumed.
214    /// - `Ok(Probe::Miss)` - token is not null.
215    /// - `Err(e)` - fatal format error.
216    async fn deserialize_null(self) -> Result<Probe<Self::Claim>, Self::Error>;
217
218    /// Delegate to `T::deserialize` from this entry handle, forwarding `extra`.
219    ///
220    /// Creates a sub-deserializer with the current token pre-loaded and
221    /// calls `T::deserialize`.  Returns `Hit` if `T` matched, `Miss` if
222    /// `T::deserialize` returned `Miss`.
223    async fn deserialize_value<T: Deserialize<'de, Extra>, Extra>(
224        self,
225        extra: Extra,
226    ) -> Result<Probe<(Self::Claim, T)>, Self::Error>;
227
228    /// Fork a sibling entry handle for the same item slot.
229    ///
230    /// Both `self` and the returned handle refer to the same slot.
231    /// Whichever resolves a probe first claims the slot; the other
232    /// becomes inert and may be dropped without advancing the stream.
233    fn fork(&mut self) -> Self;
234
235    /// Consume and discard the current token regardless of its type
236    /// (scalar, string, map, or sequence).
237    ///
238    /// Always succeeds on well-formed input.  Returns the [`Claim`](Entry::Claim)
239    /// so the stream can advance.  `Err` only on malformed data.
240    async fn skip(self) -> Result<Self::Claim, Self::Error>;
241}
242
243// ---------------------------------------------------------------------------
244// StrAccess
245// ---------------------------------------------------------------------------
246
247/// Streams a string in zero-copy chunks.  Obtained from [`Entry::deserialize_str_chunks`].
248///
249/// Strings are primitives - the type is already known, so no probing or
250/// racing is needed.  This adapter exists solely for formats that cannot
251/// deliver the value as a single contiguous slice (e.g. escape-sequence
252/// synthesis in JSON).
253///
254/// ```rust,ignore
255/// let mut chunks = hit!(e.deserialize_str_chunks().await);
256/// let mut out = String::new();
257/// let claim = loop {
258///     match chunks.next_str(|s| out.push_str(s)).await? {
259///         Chunk::Data((new, ())) => chunks = new,
260///         Chunk::Done(claim) => break claim,
261///     }
262/// };
263/// ```
264pub trait StrAccess: Sized {
265    /// Proof-of-consumption token, returned when the string is exhausted.
266    /// Must match the enclosing [`Entry::Claim`].
267    type Claim;
268    /// Fatal error type; must match the parent [`Deserializer::Error`].
269    type Error: DeserializeError;
270
271    /// Fork a sibling accessor at the same read position.
272    ///
273    /// Both `self` and the returned accessor are independent: advancing one
274    /// does not affect the other.  Both start from the current chunk
275    /// position and must each be driven to `Done` independently.
276    fn fork(&mut self) -> Self;
277
278    /// Advance to the next chunk, passing it to `f`.
279    ///
280    /// - `Ok(Chunk::Data((self, r)))` - next chunk processed; accessor returned for the next call.
281    /// - `Ok(Chunk::Done(claim))` - string exhausted; claim is now valid.
282    /// - `Err(e)` - fatal format error.
283    /// - `Pending` - no data yet.
284    async fn next_str<R>(
285        self,
286        f: impl FnOnce(&str) -> R,
287    ) -> Result<Chunk<(Self, R), Self::Claim>, Self::Error>;
288}
289
290// ---------------------------------------------------------------------------
291// BytesAccess
292// ---------------------------------------------------------------------------
293
294/// Streams a byte string in zero-copy chunks.  Obtained from [`Entry::deserialize_bytes_chunks`].
295///
296/// Byte strings are primitives - the type is already known, so no probing or
297/// racing is needed.  This adapter exists solely for formats that cannot
298/// deliver the value as a single contiguous slice.
299///
300/// ```rust,ignore
301/// let mut chunks = hit!(e.deserialize_bytes_chunks().await);
302/// let mut out = Vec::new();
303/// let claim = loop {
304///     match chunks.next_bytes(|b| out.extend_from_slice(b)).await? {
305///         Chunk::Data((new, ())) => chunks = new,
306///         Chunk::Done(claim) => break claim,
307///     }
308/// };
309/// ```
310pub trait BytesAccess: Sized {
311    /// Proof-of-consumption token, returned when the byte string is exhausted.
312    /// Must match the enclosing [`Entry::Claim`].
313    type Claim;
314    /// Fatal error type; must match the parent [`Deserializer::Error`].
315    type Error: DeserializeError;
316
317    /// Fork a sibling accessor at the same read position.
318    ///
319    /// See [`StrAccess::fork`] for full semantics.
320    fn fork(&mut self) -> Self;
321
322    /// Advance to the next chunk, passing it to `f`.
323    ///
324    /// - `Ok(Chunk::Data((self, r)))` - next chunk processed; accessor returned for the next call.
325    /// - `Ok(Chunk::Done(claim))` - byte string exhausted; claim is now valid.
326    /// - `Err(e)` - fatal format error.
327    /// - `Pending` - no data yet.
328    async fn next_bytes<R>(
329        self,
330        f: impl FnOnce(&[u8]) -> R,
331    ) -> Result<Chunk<(Self, R), Self::Claim>, Self::Error>;
332}
333
334// ---------------------------------------------------------------------------
335// Map access - new design
336// ---------------------------------------------------------------------------
337
338/// A key probe for a single map key in the borrow family. Forkable for racing multiple arms.
339pub trait MapKeyProbe<'de>: Sized {
340    type Error: DeserializeError;
341    type KeyClaim: MapKeyClaim<'de, Error = Self::Error>;
342
343    fn fork(&mut self) -> Self;
344
345    async fn deserialize_key<K: Deserialize<'de, Extra>, Extra>(
346        self,
347        extra: Extra,
348    ) -> Result<Probe<(Self::KeyClaim, K)>, Self::Error>;
349}
350
351/// Proof that a key was consumed. Converts into a value probe.
352pub trait MapKeyClaim<'de>: Sized {
353    type Error: DeserializeError;
354    type MapClaim: 'de;
355    type ValueProbe: MapValueProbe<'de, MapClaim = Self::MapClaim, Error = Self::Error>;
356
357    /// Consume this key claim and produce a value probe for the corresponding
358    /// map value. Format-specific (e.g. JSON reads `:` and the value start token).
359    async fn into_value_probe(self) -> Result<Self::ValueProbe, Self::Error>;
360}
361
362/// A value probe that can deserialize a value or skip it (borrow family).
363pub trait MapValueProbe<'de>: Sized {
364    type Error: DeserializeError;
365    type MapClaim: 'de;
366    type ValueClaim: MapValueClaim<'de, MapClaim = Self::MapClaim, Error = Self::Error>;
367
368    fn fork(&mut self) -> Self;
369
370    async fn deserialize_value<V: Deserialize<'de, Extra>, Extra>(
371        self,
372        extra: Extra,
373    ) -> Result<Probe<(Self::ValueClaim, V)>, Self::Error>;
374
375    async fn skip(self) -> Result<Self::ValueClaim, Self::Error>;
376}
377
378/// Proof that a value was consumed. Advances to the next key or ends the map (borrow family).
379pub trait MapValueClaim<'de>: Sized {
380    type Error: DeserializeError;
381    type KeyProbe: MapKeyProbe<'de, Error = Self::Error>;
382    type MapClaim: 'de;
383
384    async fn next_key(
385        self,
386        unsatisfied: usize,
387        open: usize,
388    ) -> Result<NextKey<Self::KeyProbe, Self::MapClaim>, Self::Error>;
389}
390
391// ---------------------------------------------------------------------------
392// MapAccess - iterates key-value pairs via arm stacks
393// ---------------------------------------------------------------------------
394
395/// Iterates the key-value pairs of a map.  Obtained from [`Entry::deserialize_map`].
396pub trait MapAccess<'de>: Sized {
397    /// Fatal error type; must match the parent [`Deserializer::Error`].
398    type Error: DeserializeError;
399
400    /// Proof-of-consumption token returned on map exhaustion; must match
401    /// the enclosing [`Entry::Claim`].
402    type MapClaim: 'de;
403
404    type KeyProbe: MapKeyProbe<'de, Error = Self::Error>;
405
406    fn fork(&mut self) -> Self;
407
408    /// Drive the map iteration with the given arm stack.
409    ///
410    /// Returns `Hit((MapClaim, Outputs))` on success, `Miss` if a value
411    /// type mismatched or a required field was missing, `Err` on format errors.
412    async fn iterate<S: MapArmStack<'de, Self::KeyProbe>>(
413        self,
414        arms: S,
415    ) -> Result<Probe<(Self::MapClaim, S::Outputs)>, Self::Error>;
416}
417
418// ---------------------------------------------------------------------------
419// Type aliases for borrow map access
420// ---------------------------------------------------------------------------
421
422/// Shorthand for the key probe type reachable from a `Deserializer`.
423pub type KP<'de, D> =
424    <<<D as Deserializer<'de>>::Entry as Entry<'de>>::Map as MapAccess<'de>>::KeyProbe;
425
426/// Shorthand for the value claim type reachable from a borrow key probe type.
427pub type VC<'de, KP> =
428    <<<KP as MapKeyProbe<'de>>::KeyClaim as MapKeyClaim<'de>>::ValueProbe as MapValueProbe<'de>>::ValueClaim;
429
430/// Shorthand for the value probe type reachable from a borrow key probe type.
431pub type VP<'de, KP> = <<KP as MapKeyProbe<'de>>::KeyClaim as MapKeyClaim<'de>>::ValueProbe;
432
433/// Shorthand for the value probe type reachable directly from a `Deserializer`.
434pub type VP2<'de, D> = <<KP<'de, D> as MapKeyProbe<'de>>::KeyClaim as MapKeyClaim<'de>>::ValueProbe;
435
436// ---------------------------------------------------------------------------
437// MapArmStack<'de, KP> - borrow-family arm stack
438// ---------------------------------------------------------------------------
439
440/// Borrow-family counterpart to [`crate::MapArmStackOwned`].
441///
442/// A left-nested tuple stack of [`MapArmSlot`]s parameterized by `'de`.
443/// The map impl drives the iteration loop using this trait's `init_race` /
444/// `poll_race_one` / `init_dispatch` / `poll_dispatch` methods.
445pub trait MapArmStack<'de, KP: MapKeyProbe<'de>>: Sized {
446    const SIZE: usize;
447
448    /// Left-nested tuple of `Option<(K, V)>` for each arm.
449    type Outputs;
450
451    /// Number of arms that still require a value (required fields not yet matched).
452    /// Virtual arms are excluded.
453    fn unsatisfied_count(&self) -> usize;
454
455    /// Number of arms still willing to run, including virtual arms.
456    fn open_count(&self) -> usize;
457
458    type RaceState;
459
460    fn init_race(&mut self, kp: KP) -> Self::RaceState;
461    #[allow(clippy::type_complexity)]
462    fn poll_race_one(
463        &mut self,
464        state: Pin<&mut Self::RaceState>,
465        arm_index: usize,
466        cx: &mut Context<'_>,
467    ) -> Poll<Result<Probe<(usize, KP::KeyClaim)>, KP::Error>>;
468
469    type DispatchState;
470
471    fn init_dispatch(&mut self, arm_index: usize, vp: VP<'de, KP>) -> Self::DispatchState;
472    #[allow(clippy::type_complexity)]
473    fn poll_dispatch(
474        &mut self,
475        state: Pin<&mut Self::DispatchState>,
476        cx: &mut Context<'_>,
477    ) -> Poll<Result<Probe<(VC<'de, KP>, ())>, KP::Error>>;
478
479    /// Race all unsatisfied arms' key callbacks against the given key probe.
480    async fn race_keys(&mut self, kp: KP) -> Result<Probe<(usize, KP::KeyClaim)>, KP::Error> {
481        if Self::SIZE == 0 {
482            return Ok(Probe::Miss);
483        }
484        let mut race_state = core::pin::pin!(self.init_race(kp));
485        core::future::poll_fn(|cx| {
486            let mut all_miss = true;
487            for i in 0..Self::SIZE {
488                match self.poll_race_one(race_state.as_mut(), i, cx) {
489                    Poll::Ready(Ok(Probe::Hit(v))) => return Poll::Ready(Ok(Probe::Hit(v))),
490                    Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
491                    Poll::Ready(Ok(Probe::Miss)) => {}
492                    Poll::Pending => {
493                        all_miss = false;
494                    }
495                }
496            }
497            if all_miss {
498                return Poll::Ready(Ok(Probe::Miss));
499            }
500            Poll::Pending
501        })
502        .await
503    }
504
505    /// Dispatch the value probe to the arm at `arm_index`.
506    async fn dispatch_value(
507        &mut self,
508        arm_index: usize,
509        vp: VP<'de, KP>,
510    ) -> Result<Probe<(VC<'de, KP>, ())>, KP::Error> {
511        let dispatch_state = self.init_dispatch(arm_index, vp);
512        let mut dispatch_state = core::pin::pin!(dispatch_state);
513        core::future::poll_fn(|cx| self.poll_dispatch(dispatch_state.as_mut(), cx)).await
514    }
515
516    fn take_outputs(&mut self) -> Self::Outputs;
517}
518
519// --- MapArmBase impl ---
520
521impl<'de, KP: MapKeyProbe<'de>> MapArmStack<'de, KP> for MapArmBase {
522    const SIZE: usize = 0;
523    type Outputs = ();
524
525    #[inline(always)]
526    fn unsatisfied_count(&self) -> usize {
527        0
528    }
529    #[inline(always)]
530    fn open_count(&self) -> usize {
531        0
532    }
533
534    type RaceState = ();
535
536    #[inline(always)]
537    fn init_race(&mut self, _kp: KP) {}
538    #[inline(always)]
539    fn poll_race_one(
540        &mut self,
541        _state: Pin<&mut ()>,
542        _arm_index: usize,
543        _cx: &mut Context<'_>,
544    ) -> Poll<Result<Probe<(usize, KP::KeyClaim)>, KP::Error>> {
545        unreachable!("poll_race_one called on MapArmBase (SIZE=0)")
546    }
547
548    type DispatchState = core::convert::Infallible;
549
550    #[inline(always)]
551    fn init_dispatch(&mut self, _arm_index: usize, _vp: VP<'de, KP>) -> Self::DispatchState {
552        unreachable!("init_dispatch called on MapArmBase")
553    }
554    #[inline(always)]
555    fn poll_dispatch(
556        &mut self,
557        _state: Pin<&mut Self::DispatchState>,
558        _cx: &mut Context<'_>,
559    ) -> Poll<Result<Probe<(VC<'de, KP>, ())>, KP::Error>> {
560        unreachable!("poll_dispatch called on MapArmBase")
561    }
562
563    #[inline(always)]
564    fn take_outputs(&mut self) {}
565}
566
567// --- Recursive (Rest, Slot) impl ---
568
569impl<'de, KP, Rest, K, V, KeyFn, KeyFut, ValFn, ValFut> MapArmStack<'de, KP>
570    for (Rest, MapArmSlot<K, V, KeyFn, ValFn>)
571where
572    KP: MapKeyProbe<'de>,
573    Rest: MapArmStack<'de, KP>,
574    KeyFn: FnMut(KP) -> KeyFut,
575    KeyFut: Future<Output = Result<Probe<(KP::KeyClaim, K)>, KP::Error>>,
576    ValFn: FnMut(VP<'de, KP>, K) -> ValFut,
577    ValFut: Future<Output = Result<Probe<(VC<'de, KP>, (K, V))>, KP::Error>>,
578{
579    const SIZE: usize = Rest::SIZE + 1;
580    type Outputs = (Rest::Outputs, Option<(K, V)>);
581
582    #[inline(always)]
583    fn unsatisfied_count(&self) -> usize {
584        self.0.unsatisfied_count() + if self.1.state.is_done() { 0 } else { 1 }
585    }
586    #[inline(always)]
587    fn open_count(&self) -> usize {
588        self.0.open_count() + if self.1.state.is_done() { 0 } else { 1 }
589    }
590
591    type RaceState = SlotRaceState<Rest::RaceState, KeyFut>;
592
593    #[inline(always)]
594    fn init_race(&mut self, mut kp: KP) -> Self::RaceState {
595        let rest_kp = kp.fork();
596        let this_fut = if self.1.state.is_done() {
597            None
598        } else {
599            Some((self.1.key_fn)(kp))
600        };
601        SlotRaceState {
602            rest: self.0.init_race(rest_kp),
603            this: this_fut,
604        }
605    }
606
607    #[inline(always)]
608    fn poll_race_one(
609        &mut self,
610        state: Pin<&mut Self::RaceState>,
611        arm_index: usize,
612        cx: &mut Context<'_>,
613    ) -> Poll<Result<Probe<(usize, KP::KeyClaim)>, KP::Error>> {
614        let projected = state.project();
615        if arm_index == Self::SIZE - 1 {
616            match poll_key_slot(projected.this, cx) {
617                Poll::Ready(Ok(Probe::Hit((kc, k)))) => {
618                    self.1.state = ArmState::Key(k);
619                    Poll::Ready(Ok(Probe::Hit((Self::SIZE - 1, kc))))
620                }
621                Poll::Ready(Ok(Probe::Miss)) => Poll::Ready(Ok(Probe::Miss)),
622                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
623                Poll::Pending => Poll::Pending,
624            }
625        } else {
626            self.0.poll_race_one(projected.rest, arm_index, cx)
627        }
628    }
629
630    type DispatchState = SlotDispatchState<Rest::DispatchState, ValFut>;
631
632    #[inline(always)]
633    fn init_dispatch(&mut self, arm_index: usize, vp: VP<'de, KP>) -> Self::DispatchState {
634        if arm_index == Self::SIZE - 1 {
635            let k = match core::mem::replace(&mut self.1.state, ArmState::Empty) {
636                ArmState::Key(k) => k,
637                _ => unreachable!("init_dispatch called but arm not in Key state"),
638            };
639            SlotDispatchState::ThisArm((self.1.val_fn)(vp, k))
640        } else {
641            SlotDispatchState::Delegated(self.0.init_dispatch(arm_index, vp))
642        }
643    }
644
645    #[inline(always)]
646    fn poll_dispatch(
647        &mut self,
648        state: Pin<&mut Self::DispatchState>,
649        cx: &mut Context<'_>,
650    ) -> Poll<Result<Probe<(VC<'de, KP>, ())>, KP::Error>> {
651        match state.project() {
652            SlotDispatchProj::ThisArm(fut) => fut.poll(cx).map(|r| {
653                r.map(|probe| match probe {
654                    Probe::Hit((vc, (k, v))) => {
655                        self.1.state = ArmState::Done(k, v);
656                        Probe::Hit((vc, ()))
657                    }
658                    Probe::Miss => Probe::Miss,
659                })
660            }),
661            SlotDispatchProj::Delegated(rest_state) => self.0.poll_dispatch(rest_state, cx),
662        }
663    }
664
665    #[inline(always)]
666    fn take_outputs(&mut self) -> Self::Outputs {
667        let out = match mem::replace(&mut self.1.state, ArmState::Empty) {
668            ArmState::Done(k, v) => Some((k, v)),
669            _ => None,
670        };
671        (self.0.take_outputs(), out)
672    }
673}
674
675// --- (Rest, VirtualArmSlot) impl ---
676
677impl<'de, KP, Rest, K, KeyFn, KeyFut, ValFn, ValFut> MapArmStack<'de, KP>
678    for (Rest, VirtualArmSlot<K, KeyFn, ValFn>)
679where
680    KP: MapKeyProbe<'de>,
681    Rest: MapArmStack<'de, KP>,
682    KeyFn: FnMut(KP) -> KeyFut,
683    KeyFut: Future<Output = Result<Probe<(KP::KeyClaim, K)>, KP::Error>>,
684    ValFn: FnMut(VP<'de, KP>, K) -> ValFut,
685    ValFut: Future<Output = Result<Probe<(VC<'de, KP>, ())>, KP::Error>>,
686{
687    const SIZE: usize = Rest::SIZE + 1;
688    type Outputs = Rest::Outputs;
689
690    #[inline(always)]
691    fn unsatisfied_count(&self) -> usize {
692        self.0.unsatisfied_count()
693    }
694    #[inline(always)]
695    fn open_count(&self) -> usize {
696        self.0.open_count() + 1
697    }
698
699    type RaceState = SlotRaceState<Rest::RaceState, KeyFut>;
700
701    #[inline(always)]
702    fn init_race(&mut self, mut kp: KP) -> Self::RaceState {
703        let rest_kp = kp.fork();
704        let this_fut = (self.1.key_fn)(kp);
705        SlotRaceState {
706            rest: self.0.init_race(rest_kp),
707            this: Some(this_fut),
708        }
709    }
710
711    #[inline(always)]
712    fn poll_race_one(
713        &mut self,
714        state: Pin<&mut Self::RaceState>,
715        arm_index: usize,
716        cx: &mut Context<'_>,
717    ) -> Poll<Result<Probe<(usize, KP::KeyClaim)>, KP::Error>> {
718        let projected = state.project();
719        if arm_index == Self::SIZE - 1 {
720            match poll_key_slot(projected.this, cx) {
721                Poll::Ready(Ok(Probe::Hit((kc, k)))) => {
722                    self.1.pending_key = Some(k);
723                    Poll::Ready(Ok(Probe::Hit((Self::SIZE - 1, kc))))
724                }
725                Poll::Ready(Ok(Probe::Miss)) => Poll::Ready(Ok(Probe::Miss)),
726                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
727                Poll::Pending => Poll::Pending,
728            }
729        } else {
730            self.0.poll_race_one(projected.rest, arm_index, cx)
731        }
732    }
733
734    type DispatchState = SlotDispatchState<Rest::DispatchState, ValFut>;
735
736    #[inline(always)]
737    fn init_dispatch(&mut self, arm_index: usize, vp: VP<'de, KP>) -> Self::DispatchState {
738        if arm_index == Self::SIZE - 1 {
739            let k = self
740                .1
741                .pending_key
742                .take()
743                .expect("init_dispatch on virtual arm without pending key");
744            SlotDispatchState::ThisArm((self.1.val_fn)(vp, k))
745        } else {
746            SlotDispatchState::Delegated(self.0.init_dispatch(arm_index, vp))
747        }
748    }
749
750    #[inline(always)]
751    fn poll_dispatch(
752        &mut self,
753        state: Pin<&mut Self::DispatchState>,
754        cx: &mut Context<'_>,
755    ) -> Poll<Result<Probe<(VC<'de, KP>, ())>, KP::Error>> {
756        match state.project() {
757            SlotDispatchProj::ThisArm(fut) => fut.poll(cx),
758            SlotDispatchProj::Delegated(rest_state) => self.0.poll_dispatch(rest_state, cx),
759        }
760    }
761
762    #[inline(always)]
763    fn take_outputs(&mut self) -> Self::Outputs {
764        self.0.take_outputs()
765    }
766}
767
768// --- DetectDuplicatesOwned impl ---
769
770impl<'de, KP, S, const M: usize, KeyFn, KeyFut, SkipFn, SkipFut> MapArmStack<'de, KP>
771    for DetectDuplicatesOwned<S, M, KeyFn, SkipFn>
772where
773    KP: MapKeyProbe<'de>,
774    S: MapArmStack<'de, KP>,
775    KeyFn: FnMut(KP) -> KeyFut,
776    KeyFut: Future<Output = Result<Probe<(KP::KeyClaim, crate::MatchVals<usize>)>, KP::Error>>,
777    SkipFn: FnMut(VP<'de, KP>) -> SkipFut,
778    SkipFut: Future<Output = Result<VC<'de, KP>, KP::Error>>,
779{
780    const SIZE: usize = S::SIZE + 1;
781    type Outputs = S::Outputs;
782
783    #[inline(always)]
784    fn unsatisfied_count(&self) -> usize {
785        self.inner.unsatisfied_count()
786    }
787    #[inline(always)]
788    fn open_count(&self) -> usize {
789        self.inner.open_count() + 1
790    }
791
792    type RaceState = WrapperRaceState<S::RaceState, KeyFut>;
793
794    #[inline(always)]
795    fn init_race(&mut self, mut kp: KP) -> Self::RaceState {
796        let dup_kp = kp.fork();
797        let dup_fut = (self.key_fn)(dup_kp);
798        WrapperRaceState {
799            inner: self.inner.init_race(kp),
800            virtual_arm: Some(dup_fut),
801        }
802    }
803
804    #[inline(always)]
805    fn poll_race_one(
806        &mut self,
807        state: Pin<&mut Self::RaceState>,
808        arm_index: usize,
809        cx: &mut Context<'_>,
810    ) -> Poll<Result<Probe<(usize, KP::KeyClaim)>, KP::Error>> {
811        let projected = state.project();
812        if arm_index == Self::SIZE - 1 {
813            match poll_key_slot(projected.virtual_arm, cx) {
814                Poll::Ready(Ok(Probe::Hit((kc, matched)))) => {
815                    self.dup = self.wire_names[matched.0].0;
816                    Poll::Ready(Ok(Probe::Hit((Self::SIZE - 1, kc))))
817                }
818                Poll::Ready(Ok(Probe::Miss)) => Poll::Ready(Ok(Probe::Miss)),
819                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
820                Poll::Pending => Poll::Pending,
821            }
822        } else {
823            self.inner.poll_race_one(projected.inner, arm_index, cx)
824        }
825    }
826
827    type DispatchState = WrapperDispatchState<S::DispatchState, SkipFut>;
828
829    #[inline(always)]
830    fn init_dispatch(&mut self, arm_index: usize, vp: VP<'de, KP>) -> Self::DispatchState {
831        if arm_index == Self::SIZE - 1 {
832            WrapperDispatchState::Virtual((self.skip_fn)(vp))
833        } else {
834            WrapperDispatchState::Inner(self.inner.init_dispatch(arm_index, vp))
835        }
836    }
837
838    #[inline(always)]
839    fn poll_dispatch(
840        &mut self,
841        state: Pin<&mut Self::DispatchState>,
842        cx: &mut Context<'_>,
843    ) -> Poll<Result<Probe<(VC<'de, KP>, ())>, KP::Error>> {
844        match state.project() {
845            WrapperDispatchProj::Virtual(fut) => fut.poll(cx).map(|r| match r {
846                Ok(_vc) => Err(<KP::Error as crate::DeserializeError>::duplicate_field(
847                    self.dup,
848                )),
849                Err(e) => Err(e),
850            }),
851            WrapperDispatchProj::Inner(inner_state) => self.inner.poll_dispatch(inner_state, cx),
852        }
853    }
854
855    #[inline(always)]
856    fn take_outputs(&mut self) -> Self::Outputs {
857        self.inner.take_outputs()
858    }
859}
860
861// --- TagInjectingStackOwned impl ---
862
863impl<'de, 'v, KP, S, const N: usize, TagKeyFn, TagKeyFut, TagValFn, TagValFut> MapArmStack<'de, KP>
864    for TagInjectingStackOwned<'v, S, N, TagKeyFn, TagValFn>
865where
866    KP: MapKeyProbe<'de>,
867    S: MapArmStack<'de, KP>,
868    TagKeyFn: FnMut(KP) -> TagKeyFut,
869    TagKeyFut: Future<Output = Result<Probe<(KP::KeyClaim, crate::Match)>, KP::Error>>,
870    TagValFn: FnMut(VP<'de, KP>) -> TagValFut,
871    TagValFut: Future<Output = Result<Probe<(VC<'de, KP>, crate::MatchVals<usize>)>, KP::Error>>,
872{
873    const SIZE: usize = S::SIZE + 1;
874    type Outputs = S::Outputs;
875
876    #[inline(always)]
877    fn unsatisfied_count(&self) -> usize {
878        self.inner.unsatisfied_count()
879    }
880    #[inline(always)]
881    fn open_count(&self) -> usize {
882        self.inner.open_count() + 1
883    }
884
885    type RaceState = TagRaceState<TagKeyFut, S::RaceState>;
886
887    #[inline(always)]
888    fn init_race(&mut self, mut kp: KP) -> Self::RaceState {
889        let inner_kp = kp.fork();
890        let tag_fut = (self.tag_key_fn)(kp);
891        TagRaceState {
892            tag_fut: Some(tag_fut),
893            inner: self.inner.init_race(inner_kp),
894        }
895    }
896
897    #[inline(always)]
898    fn poll_race_one(
899        &mut self,
900        state: Pin<&mut Self::RaceState>,
901        arm_index: usize,
902        cx: &mut Context<'_>,
903    ) -> Poll<Result<Probe<(usize, KP::KeyClaim)>, KP::Error>> {
904        let projected = state.project();
905        if arm_index == 0 {
906            match poll_key_slot(projected.tag_fut, cx) {
907                Poll::Ready(Ok(Probe::Hit((kc, _match)))) => Poll::Ready(Ok(Probe::Hit((0, kc)))),
908                Poll::Ready(Ok(Probe::Miss)) => Poll::Ready(Ok(Probe::Miss)),
909                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
910                Poll::Pending => Poll::Pending,
911            }
912        } else {
913            match self.inner.poll_race_one(projected.inner, arm_index - 1, cx) {
914                Poll::Ready(Ok(Probe::Hit((idx, kc)))) => {
915                    Poll::Ready(Ok(Probe::Hit((idx + 1, kc))))
916                }
917                other => other,
918            }
919        }
920    }
921
922    type DispatchState = TagDispatchState<TagValFut, S::DispatchState>;
923
924    #[inline(always)]
925    fn init_dispatch(&mut self, arm_index: usize, vp: VP<'de, KP>) -> Self::DispatchState {
926        if arm_index == 0 {
927            TagDispatchState::Tag((self.tag_val_fn)(vp))
928        } else {
929            TagDispatchState::Inner(self.inner.init_dispatch(arm_index - 1, vp))
930        }
931    }
932
933    #[inline(always)]
934    fn poll_dispatch(
935        &mut self,
936        state: Pin<&mut Self::DispatchState>,
937        cx: &mut Context<'_>,
938    ) -> Poll<Result<Probe<(VC<'de, KP>, ())>, KP::Error>> {
939        match state.project() {
940            TagDispatchProj::Tag(fut) => fut.poll(cx).map(|r| {
941                r.map(|probe| match probe {
942                    Probe::Hit((vc, crate::MatchVals(idx))) => {
943                        self.tag_value.set(Some(idx));
944                        Probe::Hit((vc, ()))
945                    }
946                    Probe::Miss => Probe::Miss,
947                })
948            }),
949            TagDispatchProj::Inner(inner_state) => self.inner.poll_dispatch(inner_state, cx),
950        }
951    }
952
953    #[inline(always)]
954    fn take_outputs(&mut self) -> Self::Outputs {
955        self.inner.take_outputs()
956    }
957}
958
959// --- StackConcat impl ---
960
961impl<'de, KP, A, B> MapArmStack<'de, KP> for StackConcat<A, B>
962where
963    KP: MapKeyProbe<'de>,
964    A: MapArmStack<'de, KP>,
965    B: MapArmStack<'de, KP>,
966{
967    const SIZE: usize = A::SIZE + B::SIZE;
968    type Outputs = (A::Outputs, B::Outputs);
969
970    #[inline(always)]
971    fn unsatisfied_count(&self) -> usize {
972        self.0.unsatisfied_count() + self.1.unsatisfied_count()
973    }
974    #[inline(always)]
975    fn open_count(&self) -> usize {
976        self.0.open_count() + self.1.open_count()
977    }
978
979    type RaceState = ConcatRaceState<A::RaceState, B::RaceState>;
980
981    #[inline(always)]
982    fn init_race(&mut self, mut kp: KP) -> Self::RaceState {
983        let b_kp = kp.fork();
984        ConcatRaceState {
985            a: self.0.init_race(kp),
986            b: self.1.init_race(b_kp),
987        }
988    }
989
990    #[inline(always)]
991    fn poll_race_one(
992        &mut self,
993        state: Pin<&mut Self::RaceState>,
994        arm_index: usize,
995        cx: &mut Context<'_>,
996    ) -> Poll<Result<Probe<(usize, KP::KeyClaim)>, KP::Error>> {
997        let projected = state.project();
998        if arm_index < A::SIZE {
999            self.0.poll_race_one(projected.a, arm_index, cx)
1000        } else {
1001            match self.1.poll_race_one(projected.b, arm_index - A::SIZE, cx) {
1002                Poll::Ready(Ok(Probe::Hit((idx, kc)))) => {
1003                    Poll::Ready(Ok(Probe::Hit((A::SIZE + idx, kc))))
1004                }
1005                other => other,
1006            }
1007        }
1008    }
1009
1010    type DispatchState = ConcatDispatchState<A::DispatchState, B::DispatchState>;
1011
1012    #[inline(always)]
1013    fn init_dispatch(&mut self, arm_index: usize, vp: VP<'de, KP>) -> Self::DispatchState {
1014        if arm_index < A::SIZE {
1015            ConcatDispatchState::InA(self.0.init_dispatch(arm_index, vp))
1016        } else {
1017            ConcatDispatchState::InB(self.1.init_dispatch(arm_index - A::SIZE, vp))
1018        }
1019    }
1020
1021    #[inline(always)]
1022    fn poll_dispatch(
1023        &mut self,
1024        state: Pin<&mut Self::DispatchState>,
1025        cx: &mut Context<'_>,
1026    ) -> Poll<Result<Probe<(VC<'de, KP>, ())>, KP::Error>> {
1027        match state.project() {
1028            ConcatDispatchProj::InA(a_state) => self.0.poll_dispatch(a_state, cx),
1029            ConcatDispatchProj::InB(b_state) => self.1.poll_dispatch(b_state, cx),
1030        }
1031    }
1032
1033    #[inline(always)]
1034    fn take_outputs(&mut self) -> Self::Outputs {
1035        (self.0.take_outputs(), self.1.take_outputs())
1036    }
1037}
1038
1039// ---------------------------------------------------------------------------
1040// Flatten infrastructure - borrow family
1041// ---------------------------------------------------------------------------
1042
1043// Parallel to FlattenContOwned / FlattenDeserializerOwned / FlattenEntryOwned / FlattenMapAccessOwned
1044// in the owned family, but parameterized over MapAccess<'de> and using
1045// MapArmStack<'de, KP> instead of MapArmStackOwned<KP>.
1046
1047/// Continuation for [`FlattenMapAccess`]. Determines what happens after
1048/// the outer and inner arm stacks are combined via [`StackConcat`].
1049///
1050/// Terminal case: [`FlattenTerminal`] calls `map.iterate(SkipUnknown!(arms))`.
1051/// Intermediate case: generated by the derive macro - calls the next flatten
1052/// field's `Deserialize::deserialize` with a new [`FlattenDeserializer`].
1053#[allow(async_fn_in_trait)]
1054pub trait FlattenCont<'de, M: MapAccess<'de>> {
1055    /// Extra result produced by the continuation (e.g., values from subsequent
1056    /// flatten fields). `()` for the terminal case.
1057    type Extra;
1058
1059    /// Drive the combined arm stack to completion.
1060    ///
1061    /// `arms` is `StackConcat(outer_arms, inner_arms)`.
1062    async fn finish<Arms: MapArmStack<'de, M::KeyProbe>>(
1063        self,
1064        map: M,
1065        arms: Arms,
1066    ) -> Result<Probe<(M::MapClaim, Arms::Outputs, Self::Extra)>, M::Error>;
1067}
1068
1069impl<'de, M: MapAccess<'de>> FlattenCont<'de, M> for crate::FlattenTerminal {
1070    type Extra = ();
1071
1072    async fn finish<Arms: MapArmStack<'de, M::KeyProbe>>(
1073        self,
1074        map: M,
1075        arms: Arms,
1076    ) -> Result<Probe<(M::MapClaim, Arms::Outputs, ())>, M::Error> {
1077        let wrapped = crate::SkipUnknown!(arms, M::KeyProbe, VP<'de, M::KeyProbe>);
1078        let (claim, out) = crate::hit!(map.iterate(wrapped).await);
1079        Ok(Probe::Hit((claim, out, ())))
1080    }
1081}
1082
1083#[cfg(feature = "alloc")]
1084impl<'de, M: MapAccess<'de>> FlattenCont<'de, M> for crate::FlattenTerminalBoxed {
1085    type Extra = ();
1086
1087    async fn finish<Arms: MapArmStack<'de, M::KeyProbe>>(
1088        self,
1089        map: M,
1090        arms: Arms,
1091    ) -> Result<Probe<(M::MapClaim, Arms::Outputs, ())>, M::Error> {
1092        let wrapped = crate::SkipUnknown!(arms, M::KeyProbe, VP<'de, M::KeyProbe>);
1093        #[allow(clippy::type_complexity)]
1094        let r: Result<Probe<(M::MapClaim, Arms::Outputs)>, M::Error> =
1095            alloc::boxed::Box::pin(map.iterate(wrapped)).await;
1096        let (claim, out) = crate::hit!(r);
1097        Ok(Probe::Hit((claim, out, ())))
1098    }
1099}
1100
1101/// Facade [`Deserializer<'de>`] used to implement `#[strede(flatten)]` for the borrow family.
1102///
1103/// Pass this as the deserializer to a flattened field's [`Deserialize`] impl. It
1104/// intercepts `deserialize_map` → `iterate(inner_arms)`, prepends the outer
1105/// struct's arms via [`StackConcat`], and delegates to the [`FlattenCont`]
1106/// continuation. For the terminal case ([`FlattenTerminal`]) this drives the
1107/// real map's `iterate`; for intermediate cases it chains to the next flatten field.
1108pub struct FlattenDeserializer<'a, 'de, M, OuterArms, Cont>
1109where
1110    M: MapAccess<'de>,
1111    OuterArms: MapArmStack<'de, M::KeyProbe>,
1112    Cont: FlattenCont<'de, M>,
1113{
1114    pub map: M,
1115    pub outer_arms: &'a core::cell::Cell<Option<OuterArms>>,
1116    pub outer_outputs: &'a core::cell::Cell<Option<OuterArms::Outputs>>,
1117    pub cont: Cont,
1118    pub extra: &'a core::cell::Cell<Option<Cont::Extra>>,
1119    pub _de: core::marker::PhantomData<&'de ()>,
1120}
1121
1122impl<'a, 'de, M, OuterArms, Cont> FlattenDeserializer<'a, 'de, M, OuterArms, Cont>
1123where
1124    M: MapAccess<'de>,
1125    OuterArms: MapArmStack<'de, M::KeyProbe>,
1126    Cont: FlattenCont<'de, M>,
1127{
1128    pub fn new(
1129        map: M,
1130        outer_arms: &'a core::cell::Cell<Option<OuterArms>>,
1131        outer_outputs: &'a core::cell::Cell<Option<OuterArms::Outputs>>,
1132        cont: Cont,
1133        extra: &'a core::cell::Cell<Option<Cont::Extra>>,
1134    ) -> Self {
1135        Self {
1136            map,
1137            outer_arms,
1138            outer_outputs,
1139            cont,
1140            extra,
1141            _de: core::marker::PhantomData,
1142        }
1143    }
1144}
1145
1146impl<'a, 'de, M, OuterArms, Cont> Deserializer<'de>
1147    for FlattenDeserializer<'a, 'de, M, OuterArms, Cont>
1148where
1149    M: MapAccess<'de>,
1150    OuterArms: MapArmStack<'de, M::KeyProbe>,
1151    Cont: FlattenCont<'de, M>,
1152{
1153    type Error = M::Error;
1154    type Claim = M::MapClaim;
1155    type EntryClaim = M::MapClaim;
1156    type Entry = FlattenEntry<'a, 'de, M, OuterArms, Cont>;
1157
1158    async fn entry<const N: usize, F, Fut, R>(
1159        self,
1160        mut f: F,
1161    ) -> Result<Probe<(Self::Claim, R)>, Self::Error>
1162    where
1163        F: FnMut([Self::Entry; N]) -> Fut,
1164        Fut: core::future::Future<Output = Result<Probe<(Self::EntryClaim, R)>, Self::Error>>,
1165    {
1166        assert!(N == 1, "FlattenDeserializer only supports entry<1, ...>");
1167        let entry = FlattenEntry {
1168            map: self.map,
1169            outer_arms: self.outer_arms,
1170            outer_outputs: self.outer_outputs,
1171            cont: self.cont,
1172            extra: self.extra,
1173            _de: core::marker::PhantomData,
1174        };
1175        let mut slot = Some(entry);
1176        let entries: [Self::Entry; N] = core::array::from_fn(|_| slot.take().unwrap());
1177        f(entries).await
1178    }
1179}
1180
1181/// Entry handle produced by [`FlattenDeserializer`].
1182pub struct FlattenEntry<'a, 'de, M, OuterArms, Cont>
1183where
1184    M: MapAccess<'de>,
1185    OuterArms: MapArmStack<'de, M::KeyProbe>,
1186    Cont: FlattenCont<'de, M>,
1187{
1188    pub map: M,
1189    pub outer_arms: &'a core::cell::Cell<Option<OuterArms>>,
1190    pub outer_outputs: &'a core::cell::Cell<Option<OuterArms::Outputs>>,
1191    pub cont: Cont,
1192    pub extra: &'a core::cell::Cell<Option<Cont::Extra>>,
1193    pub _de: core::marker::PhantomData<&'de ()>,
1194}
1195
1196impl<'a, 'de, M, OuterArms, Cont> Entry<'de> for FlattenEntry<'a, 'de, M, OuterArms, Cont>
1197where
1198    M: MapAccess<'de>,
1199    OuterArms: MapArmStack<'de, M::KeyProbe>,
1200    Cont: FlattenCont<'de, M>,
1201{
1202    type Error = M::Error;
1203    type Claim = M::MapClaim;
1204    type StrChunks = crate::Never<'static, M::MapClaim, M::Error>;
1205    type BytesChunks = crate::Never<'static, M::MapClaim, M::Error>;
1206    type Map = FlattenMapAccess<'a, 'de, M, OuterArms, Cont>;
1207    type Seq = crate::Never<'static, M::MapClaim, M::Error>;
1208
1209    async fn deserialize_map(self) -> Result<Probe<Self::Map>, Self::Error> {
1210        Ok(Probe::Hit(FlattenMapAccess {
1211            map: self.map,
1212            outer_arms: self.outer_arms,
1213            outer_outputs: self.outer_outputs,
1214            cont: self.cont,
1215            extra: self.extra,
1216            _de: core::marker::PhantomData,
1217        }))
1218    }
1219
1220    // All other entry methods return Miss - flatten only supports map-shaped types.
1221    async fn deserialize_bool(self) -> Result<Probe<(Self::Claim, bool)>, Self::Error> {
1222        Ok(Probe::Miss)
1223    }
1224    async fn deserialize_u8(self) -> Result<Probe<(Self::Claim, u8)>, Self::Error> {
1225        Ok(Probe::Miss)
1226    }
1227    async fn deserialize_u16(self) -> Result<Probe<(Self::Claim, u16)>, Self::Error> {
1228        Ok(Probe::Miss)
1229    }
1230    async fn deserialize_u32(self) -> Result<Probe<(Self::Claim, u32)>, Self::Error> {
1231        Ok(Probe::Miss)
1232    }
1233    async fn deserialize_u64(self) -> Result<Probe<(Self::Claim, u64)>, Self::Error> {
1234        Ok(Probe::Miss)
1235    }
1236    async fn deserialize_u128(self) -> Result<Probe<(Self::Claim, u128)>, Self::Error> {
1237        Ok(Probe::Miss)
1238    }
1239    async fn deserialize_i8(self) -> Result<Probe<(Self::Claim, i8)>, Self::Error> {
1240        Ok(Probe::Miss)
1241    }
1242    async fn deserialize_i16(self) -> Result<Probe<(Self::Claim, i16)>, Self::Error> {
1243        Ok(Probe::Miss)
1244    }
1245    async fn deserialize_i32(self) -> Result<Probe<(Self::Claim, i32)>, Self::Error> {
1246        Ok(Probe::Miss)
1247    }
1248    async fn deserialize_i64(self) -> Result<Probe<(Self::Claim, i64)>, Self::Error> {
1249        Ok(Probe::Miss)
1250    }
1251    async fn deserialize_i128(self) -> Result<Probe<(Self::Claim, i128)>, Self::Error> {
1252        Ok(Probe::Miss)
1253    }
1254    async fn deserialize_f32(self) -> Result<Probe<(Self::Claim, f32)>, Self::Error> {
1255        Ok(Probe::Miss)
1256    }
1257    async fn deserialize_f64(self) -> Result<Probe<(Self::Claim, f64)>, Self::Error> {
1258        Ok(Probe::Miss)
1259    }
1260    async fn deserialize_char(self) -> Result<Probe<(Self::Claim, char)>, Self::Error> {
1261        Ok(Probe::Miss)
1262    }
1263    async fn deserialize_str(self) -> Result<Probe<(Self::Claim, &'de str)>, Self::Error> {
1264        Ok(Probe::Miss)
1265    }
1266    async fn deserialize_str_chunks(self) -> Result<Probe<Self::StrChunks>, Self::Error> {
1267        Ok(Probe::Miss)
1268    }
1269    async fn deserialize_bytes(self) -> Result<Probe<(Self::Claim, &'de [u8])>, Self::Error> {
1270        Ok(Probe::Miss)
1271    }
1272    async fn deserialize_bytes_chunks(self) -> Result<Probe<Self::BytesChunks>, Self::Error> {
1273        Ok(Probe::Miss)
1274    }
1275    async fn deserialize_seq(self) -> Result<Probe<Self::Seq>, Self::Error> {
1276        Ok(Probe::Miss)
1277    }
1278    async fn deserialize_null(self) -> Result<Probe<Self::Claim>, Self::Error> {
1279        Ok(Probe::Miss)
1280    }
1281    async fn deserialize_option<T: Deserialize<'de, Extra>, Extra>(
1282        self,
1283        _extra: Extra,
1284    ) -> Result<Probe<(Self::Claim, Option<T>)>, Self::Error> {
1285        Ok(Probe::Miss)
1286    }
1287    async fn deserialize_value<T: Deserialize<'de, Extra>, Extra>(
1288        self,
1289        _extra: Extra,
1290    ) -> Result<Probe<(Self::Claim, T)>, Self::Error> {
1291        Ok(Probe::Miss)
1292    }
1293    fn fork(&mut self) -> Self {
1294        panic!("FlattenEntry::fork called; flatten only supports N=1 entry")
1295    }
1296    async fn skip(self) -> Result<Self::Claim, Self::Error> {
1297        panic!("FlattenEntry::skip called on flatten entry")
1298    }
1299}
1300
1301/// [`MapAccess<'de>`] produced by [`FlattenEntry`].
1302///
1303/// When `iterate(inner_arms)` is called, it takes the outer arms from the
1304/// `Cell`, builds `StackConcat(outer_arms, inner_arms)`, and delegates to
1305/// `cont.finish(map, combined)`. The continuation either drives the real map
1306/// (terminal) or chains to the next flatten field (intermediate).
1307pub struct FlattenMapAccess<'a, 'de, M, OuterArms, Cont>
1308where
1309    M: MapAccess<'de>,
1310    OuterArms: MapArmStack<'de, M::KeyProbe>,
1311    Cont: FlattenCont<'de, M>,
1312{
1313    pub map: M,
1314    pub outer_arms: &'a core::cell::Cell<Option<OuterArms>>,
1315    pub outer_outputs: &'a core::cell::Cell<Option<OuterArms::Outputs>>,
1316    pub cont: Cont,
1317    pub extra: &'a core::cell::Cell<Option<Cont::Extra>>,
1318    pub _de: core::marker::PhantomData<&'de ()>,
1319}
1320
1321impl<'a, 'de, M, OuterArms, Cont> MapAccess<'de> for FlattenMapAccess<'a, 'de, M, OuterArms, Cont>
1322where
1323    M: MapAccess<'de>,
1324    OuterArms: MapArmStack<'de, M::KeyProbe>,
1325    Cont: FlattenCont<'de, M>,
1326{
1327    type Error = M::Error;
1328    type MapClaim = M::MapClaim;
1329    type KeyProbe = M::KeyProbe;
1330
1331    fn fork(&mut self) -> Self {
1332        panic!("FlattenMapAccess::fork not supported")
1333    }
1334
1335    async fn iterate<S: MapArmStack<'de, Self::KeyProbe>>(
1336        self,
1337        inner_arms: S,
1338    ) -> Result<Probe<(Self::MapClaim, S::Outputs)>, Self::Error> {
1339        let outer_arms = self
1340            .outer_arms
1341            .take()
1342            .expect("FlattenMapAccess::iterate called without outer arms");
1343        let combined = StackConcat(outer_arms, inner_arms);
1344        let (claim, (outer_out, inner_out), extra) =
1345            crate::hit!(self.cont.finish(self.map, combined).await);
1346        self.outer_outputs.set(Some(outer_out));
1347        self.extra.set(Some(extra));
1348        Ok(Probe::Hit((claim, inner_out)))
1349    }
1350}
1351
1352// ---------------------------------------------------------------------------
1353// Macros for borrow family
1354// ---------------------------------------------------------------------------
1355
1356/// Wraps a [`MapArmStack`] so that unknown map keys are silently consumed (borrow family).
1357#[macro_export]
1358macro_rules! SkipUnknown {
1359    ($inner:expr, $kp:ty, $vp:ty) => {{
1360        use $crate::MapKeyProbe as _;
1361        (
1362            $inner,
1363            $crate::VirtualArmSlot::new(
1364                |kp: $kp| kp.deserialize_key::<$crate::Skip, _>(()),
1365                |vp: $vp, _k: $crate::Skip| async move {
1366                    use $crate::MapValueProbe as _;
1367                    let vc = vp.skip().await?;
1368                    ::core::result::Result::Ok($crate::Probe::Hit((vc, ())))
1369                },
1370            ),
1371        )
1372    }};
1373    ($inner:expr) => {{
1374        use $crate::MapKeyProbe as _;
1375        (
1376            $inner,
1377            $crate::VirtualArmSlot::new(
1378                |kp| kp.deserialize_key::<$crate::Skip, _>(()),
1379                |vp, _k: $crate::Skip| async move {
1380                    use $crate::MapValueProbe as _;
1381                    let vc = vp.skip().await?;
1382                    ::core::result::Result::Ok($crate::Probe::Hit((vc, ())))
1383                },
1384            ),
1385        )
1386    }};
1387}
1388
1389/// Wraps a [`MapArmStack`] to return a duplicate-field error (borrow family).
1390#[macro_export]
1391macro_rules! DetectDuplicates {
1392    ($inner:expr, $wire_names:expr, $kp:ty, $vp:ty) => {{
1393        use $crate::MapKeyProbe as _;
1394        let __wn = $wire_names;
1395        $crate::DetectDuplicatesOwned::new(
1396            $inner,
1397            __wn,
1398            move |kp: $kp| kp.deserialize_key::<$crate::MatchVals<usize>, _>(__wn),
1399            |vp: $vp| vp.skip(),
1400        )
1401    }};
1402}
1403
1404/// Wraps a [`MapArmStack`] to intercept a tag field (borrow family).
1405#[macro_export]
1406macro_rules! TagInjectingStack {
1407    ($inner:expr, $tag_field:expr, $tag_candidates:expr, $tag_value:expr, $kp:ty, $vp:ty) => {{
1408        use $crate::MapKeyProbe as _;
1409        use $crate::MapValueProbe as _;
1410        let __tf = $tag_field;
1411        let __tc = $tag_candidates;
1412        $crate::TagInjectingStackOwned::new(
1413            $inner,
1414            __tf,
1415            __tc,
1416            $tag_value,
1417            move |kp: $kp| kp.deserialize_key::<$crate::Match, &str>(__tf),
1418            move |vp: $vp| vp.deserialize_value::<$crate::MatchVals<usize>, _>(__tc),
1419        )
1420    }};
1421}
1422
1423// ---------------------------------------------------------------------------
1424// SeqAccess
1425// ---------------------------------------------------------------------------
1426
1427/// Iterates the elements of a sequence.  Obtained from [`Entry::deserialize_seq`].
1428///
1429/// ```rust,ignore
1430/// let mut out = Vec::new();
1431/// loop {
1432///     match hit!(seq.next(|[e]| async {
1433///         let (claim, v) = hit!(e.get::<u32, ()>(()).await);
1434///         Ok(Probe::Hit((claim, v)))
1435///     }).await) {
1436///         Chunk::Data((n_seq, v)) => {
1437///             out.push(v)
1438///             seq = n_seq;
1439///         },
1440///         Chunk::Done(claim) => return Ok(Probe::Hit((claim, out))),
1441///     }
1442/// }
1443/// ```
1444pub trait SeqAccess<'de>: Sized {
1445    /// Fatal error type; must match the parent [`Deserializer::Error`].
1446    type Error: DeserializeError;
1447
1448    /// Proof-of-consumption token returned on sequence exhaustion; must match
1449    /// the enclosing [`Entry::Claim`].
1450    type SeqClaim: 'de;
1451
1452    /// Proof-of-consumption token produced by [`SeqEntry`] probes; threaded
1453    /// back through the closure return value to advance the sequence.
1454    type ElemClaim: 'de;
1455
1456    /// Owned handle for one sequence element.  See [`SeqEntry`].
1457    type Elem: SeqEntry<'de, Claim = Self::ElemClaim, Error = Self::Error>;
1458
1459    /// Fork a sibling accessor at the same sequence position.
1460    ///
1461    /// See [`MapAccess::fork`] for full semantics.
1462    fn fork(&mut self) -> Self;
1463
1464    /// Advance to the next element, passing `N` owned [`SeqEntry`] handles to `f`.
1465    ///
1466    /// Returns:
1467    /// - `Ok(Probe::Hit(Chunk::Data(r)))` - an element was consumed.
1468    /// - `Ok(Probe::Hit(Chunk::Done(claim)))` - sequence exhausted.
1469    /// - `Ok(Probe::Miss)` - closure returned Miss.
1470    /// - `Err(e)` - fatal format error.
1471    /// - `Pending` - no data yet.
1472    async fn next<const N: usize, F, Fut, R>(
1473        self,
1474        f: F,
1475    ) -> Result<Probe<Chunk<(Self, R), Self::SeqClaim>>, Self::Error>
1476    where
1477        F: FnMut([Self::Elem; N]) -> Fut,
1478        Fut: Future<Output = Result<Probe<(Self::ElemClaim, R)>, Self::Error>>;
1479}
1480
1481/// Owned handle for one element in a sequence.
1482pub trait SeqEntry<'de> {
1483    /// Fatal error type; must match the parent [`Deserializer::Error`].
1484    type Error: DeserializeError;
1485    /// Proof-of-consumption token; must match the enclosing [`SeqAccess::Claim`].
1486    type Claim: 'de;
1487
1488    /// Deserialize the element as `T`, forwarding `extra` into `T::deserialize`.
1489    /// Returns `Ok(Probe::Hit((claim, value)))`; the claim must be returned from
1490    /// the closure passed to [`SeqAccess::next`] to advance the stream.
1491    /// `Ok(Probe::Miss)` if `T::deserialize` misses; `Err` on fatal format error only.
1492    async fn get<T: Deserialize<'de, Extra>, Extra>(
1493        self,
1494        extra: Extra,
1495    ) -> Result<Probe<(Self::Claim, T)>, Self::Error>;
1496
1497    /// Fork a sibling element handle for the same sequence slot.
1498    ///
1499    /// Both handles refer to the same element; whichever resolves `get`
1500    /// first claims it.
1501    fn fork(&mut self) -> Self
1502    where
1503        Self: Sized;
1504
1505    /// Consume and discard the element without deserializing it.
1506    /// Returns the [`Claim`](SeqEntry::Claim) so the stream can advance.
1507    async fn skip(self) -> Result<Self::Claim, Self::Error>;
1508}
1509
1510// ---------------------------------------------------------------------------
1511// Never impls - borrow family
1512// ---------------------------------------------------------------------------
1513
1514impl<'n, C, E: DeserializeError> StrAccess for crate::Never<'n, C, E> {
1515    type Claim = C;
1516    type Error = E;
1517    fn fork(&mut self) -> Self {
1518        match self.0 {}
1519    }
1520    async fn next_str<R>(
1521        self,
1522        _f: impl FnOnce(&str) -> R,
1523    ) -> Result<Chunk<(Self, R), Self::Claim>, Self::Error> {
1524        match self.0 {}
1525    }
1526}
1527
1528impl<'n, C, E: DeserializeError> BytesAccess for crate::Never<'n, C, E> {
1529    type Claim = C;
1530    type Error = E;
1531    fn fork(&mut self) -> Self {
1532        match self.0 {}
1533    }
1534    async fn next_bytes<R>(
1535        self,
1536        _f: impl FnOnce(&[u8]) -> R,
1537    ) -> Result<Chunk<(Self, R), Self::Claim>, Self::Error> {
1538        match self.0 {}
1539    }
1540}
1541
1542impl<'n, 'de, C: 'de, E: DeserializeError> SeqAccess<'de> for crate::Never<'n, C, E> {
1543    type Error = E;
1544    type SeqClaim = C;
1545    type ElemClaim = C;
1546    type Elem = crate::Never<'n, C, E>;
1547
1548    fn fork(&mut self) -> Self {
1549        match self.0 {}
1550    }
1551    async fn next<const N: usize, F, Fut, R>(
1552        self,
1553        _f: F,
1554    ) -> Result<Probe<Chunk<(Self, R), Self::SeqClaim>>, Self::Error>
1555    where
1556        F: FnMut([Self::Elem; N]) -> Fut,
1557        Fut: core::future::Future<Output = Result<Probe<(Self::ElemClaim, R)>, Self::Error>>,
1558    {
1559        match self.0 {}
1560    }
1561}
1562
1563impl<'n, 'de, C: 'de, E: DeserializeError> SeqEntry<'de> for crate::Never<'n, C, E> {
1564    type Error = E;
1565    type Claim = C;
1566    fn fork(&mut self) -> Self {
1567        match self.0 {}
1568    }
1569    async fn get<T: Deserialize<'de, Extra>, Extra>(
1570        self,
1571        _extra: Extra,
1572    ) -> Result<Probe<(Self::Claim, T)>, Self::Error> {
1573        match self.0 {}
1574    }
1575    async fn skip(self) -> Result<Self::Claim, Self::Error> {
1576        match self.0 {}
1577    }
1578}
1579
1580impl<'n, 'de, C: 'de, E: DeserializeError> MapAccess<'de> for crate::Never<'n, C, E> {
1581    type Error = E;
1582    type MapClaim = C;
1583    type KeyProbe = crate::Never<'n, C, E>;
1584
1585    fn fork(&mut self) -> Self {
1586        match self.0 {}
1587    }
1588
1589    async fn iterate<S: MapArmStack<'de, Self::KeyProbe>>(
1590        self,
1591        _arms: S,
1592    ) -> Result<Probe<(Self::MapClaim, S::Outputs)>, Self::Error> {
1593        match self.0 {}
1594    }
1595}
1596
1597impl<'n, 'de, C: 'de, E: DeserializeError> MapKeyProbe<'de> for crate::Never<'n, C, E> {
1598    type Error = E;
1599    type KeyClaim = crate::Never<'n, C, E>;
1600    fn fork(&mut self) -> Self {
1601        match self.0 {}
1602    }
1603    async fn deserialize_key<K: Deserialize<'de, Extra>, Extra>(
1604        self,
1605        _extra: Extra,
1606    ) -> Result<Probe<(Self::KeyClaim, K)>, Self::Error> {
1607        match self.0 {}
1608    }
1609}
1610
1611impl<'n, 'de, C: 'de, E: DeserializeError> MapKeyClaim<'de> for crate::Never<'n, C, E> {
1612    type Error = E;
1613    type MapClaim = C;
1614    type ValueProbe = crate::Never<'n, C, E>;
1615    async fn into_value_probe(self) -> Result<Self::ValueProbe, Self::Error> {
1616        match self.0 {}
1617    }
1618}
1619
1620impl<'n, 'de, C: 'de, E: DeserializeError> MapValueProbe<'de> for crate::Never<'n, C, E> {
1621    type Error = E;
1622    type MapClaim = C;
1623    type ValueClaim = crate::Never<'n, C, E>;
1624    fn fork(&mut self) -> Self {
1625        match self.0 {}
1626    }
1627    async fn deserialize_value<V: Deserialize<'de, Extra>, Extra>(
1628        self,
1629        _extra: Extra,
1630    ) -> Result<Probe<(Self::ValueClaim, V)>, Self::Error> {
1631        match self.0 {}
1632    }
1633    async fn skip(self) -> Result<Self::ValueClaim, Self::Error> {
1634        match self.0 {}
1635    }
1636}
1637
1638impl<'n, 'de, C: 'de, E: DeserializeError> MapValueClaim<'de> for crate::Never<'n, C, E> {
1639    type Error = E;
1640    type KeyProbe = crate::Never<'n, C, E>;
1641    type MapClaim = C;
1642    async fn next_key(
1643        self,
1644        _unsatisfied: usize,
1645        _open: usize,
1646    ) -> Result<NextKey<Self::KeyProbe, Self::MapClaim>, Self::Error> {
1647        match self.0 {}
1648    }
1649}
1650
1651// ---------------------------------------------------------------------------
1652// Deserialize impls for primitives
1653// ---------------------------------------------------------------------------
1654
1655macro_rules! impl_deserialize_primitive {
1656    ($ty:ty, $method:ident) => {
1657        impl<'de> Deserialize<'de> for $ty {
1658            async fn deserialize<D: Deserializer<'de>>(
1659                d: D,
1660                _extra: (),
1661            ) -> Result<Probe<(D::Claim, Self)>, D::Error> {
1662                d.entry(|[e]| async { e.$method().await }).await
1663            }
1664        }
1665    };
1666}
1667
1668impl_deserialize_primitive!(bool, deserialize_bool);
1669impl_deserialize_primitive!(u8, deserialize_u8);
1670impl_deserialize_primitive!(u16, deserialize_u16);
1671impl_deserialize_primitive!(u32, deserialize_u32);
1672impl_deserialize_primitive!(u64, deserialize_u64);
1673impl_deserialize_primitive!(u128, deserialize_u128);
1674impl_deserialize_primitive!(i8, deserialize_i8);
1675impl_deserialize_primitive!(i16, deserialize_i16);
1676impl_deserialize_primitive!(i32, deserialize_i32);
1677impl_deserialize_primitive!(i64, deserialize_i64);
1678impl_deserialize_primitive!(i128, deserialize_i128);
1679impl_deserialize_primitive!(f32, deserialize_f32);
1680impl_deserialize_primitive!(f64, deserialize_f64);
1681impl_deserialize_primitive!(char, deserialize_char);
1682
1683impl<'de: 'a, 'a> Deserialize<'de> for &'a str {
1684    async fn deserialize<D: Deserializer<'de>>(
1685        d: D,
1686        _extra: (),
1687    ) -> Result<Probe<(D::Claim, Self)>, D::Error> {
1688        d.entry(|[e]| e.deserialize_str()).await
1689    }
1690}
1691
1692impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] {
1693    async fn deserialize<D: Deserializer<'de>>(
1694        d: D,
1695        _extra: (),
1696    ) -> Result<Probe<(D::Claim, Self)>, D::Error> {
1697        d.entry(|[e]| e.deserialize_bytes()).await
1698    }
1699}
1700
1701impl<'de, Extra: Copy, T: Deserialize<'de, Extra>> Deserialize<'de, Extra> for Option<T> {
1702    async fn deserialize<D: Deserializer<'de>>(
1703        d: D,
1704        extra: Extra,
1705    ) -> Result<Probe<(D::Claim, Self)>, D::Error> {
1706        d.entry(|[e]| e.deserialize_option::<T, Extra>(extra)).await
1707    }
1708}