Skip to main content

repe_core/
structs.rs

1use crate::constants::{BodyFormat, ErrorCode};
2use serde::Serialize;
3use serde::de::DeserializeOwned;
4use serde_json::Value;
5/// Errors produced while handling struct-backed endpoints.
6///
7/// Non-exhaustive: match with a wildcard arm, or use [`StructError::code`] to
8/// map any error onto its protocol [`ErrorCode`].
9#[derive(Debug, thiserror::Error)]
10#[non_exhaustive]
11pub enum StructError {
12    #[error("invalid path `{path}`")]
13    InvalidPath { path: String },
14    #[error("unexpected additional path segments at `{path}`")]
15    InvalidSubpath { path: String },
16    #[error("body required for `{path}`")]
17    BodyExpected { path: String },
18    #[error("body not allowed for `{path}`")]
19    BodyUnexpected { path: String },
20    #[error("serialization error for `{path}`: {source}")]
21    Serialize {
22        path: String,
23        #[source]
24        source: serde_json::Error,
25    },
26    #[error("deserialization error for `{path}`: {source}")]
27    Deserialize {
28        path: String,
29        #[source]
30        source: serde_json::Error,
31    },
32    #[error("method `{path}` failed: {message}")]
33    Execution { path: String, message: String },
34}
35
36impl StructError {
37    pub fn code(&self) -> ErrorCode {
38        match self {
39            StructError::InvalidPath { .. } | StructError::InvalidSubpath { .. } => {
40                ErrorCode::MethodNotFound
41            }
42            StructError::BodyExpected { .. } | StructError::BodyUnexpected { .. } => {
43                ErrorCode::InvalidBody
44            }
45            StructError::Serialize { .. } | StructError::Deserialize { .. } => {
46                ErrorCode::InvalidBody
47            }
48            StructError::Execution { .. } => ErrorCode::ParseError,
49        }
50    }
51}
52
53/// Convenience alias for results returned by struct handlers.
54pub type StructResult<T> = Result<T, StructError>;
55
56/// Trait implemented by structs that can be exposed directly through the REPE router.
57///
58/// The implementation should interpret the provided JSON Pointer path segments and
59/// either return a JSON value (for reads) or mutate the struct (for writes).
60#[diagnostic::on_unimplemented(
61    message = "`{Self}` cannot be served over REPE: it does not implement `RepeStruct`",
62    label = "not a REPE-servable type",
63    note = "derive it with `#[derive(RepeStruct)]`, or, for a field of a type you do not own, use `#[repe(nested_serde)]` to route through its `Serialize`/`Deserialize` impls instead of `#[repe(nested)]`",
64    note = "a type in a crate that depends only on `repe-core` can derive this too; `repe` re-exports the same trait"
65)]
66pub trait RepeStruct: Send + Sync {
67    /// Handle a read or write against this struct.
68    ///
69    /// * `segments` – JSON Pointer path split into unescaped segments.
70    /// * `body` – `Some(value)` when the request contains a JSON body, `None` for reads.
71    ///
72    /// Return `Ok(Some(value))` to send a JSON response payload, `Ok(None)` to send `null`.
73    fn repe_handle(
74        &mut self,
75        segments: &[&str],
76        body: Option<Value>,
77    ) -> StructResult<Option<Value>>;
78
79    /// Encode-in-place counterpart of [`repe_handle`](Self::repe_handle): write the
80    /// response body straight into `out` instead of returning an owned
81    /// [`serde_json::Value`] for the caller to re-serialize.
82    ///
83    /// This is the method the router calls. The default implementation delegates
84    /// to [`repe_handle`](Self::repe_handle) and encodes whatever it returns, so a
85    /// hand-written impl only needs `repe_handle`; `#[derive(RepeStruct)]`
86    /// overrides it so a leaf read serializes the live field directly into the
87    /// outgoing frame buffer with no intermediate `Value`.
88    ///
89    /// Writes are unaffected — a request body still arrives as a `Value`.
90    ///
91    /// [`repe_handle`]: Self::repe_handle
92    fn repe_handle_into(
93        &mut self,
94        segments: &[&str],
95        body: Option<Value>,
96        out: &mut ResponseBody<'_>,
97    ) -> StructResult<()> {
98        let value = self.repe_handle(segments, body)?;
99        write_optional(out, segments, value)
100    }
101
102    /// Serve a request through a **shared** borrow, or decline it.
103    ///
104    /// The router tries this first for every request against a struct
105    /// registered behind a lock that has a shared mode, which is what keeps a
106    /// `/version` read from queueing behind a half-second method call on the
107    /// same object.
108    ///
109    /// A body-carrying frame is offered here too, and that is deliberate: REPE
110    /// separates read from write at the *frame* level, but a `&self` method
111    /// taking arguments is a call, not a mutation. Deciding from the frame
112    /// alone put a long-running `&self` call behind the write guard and
113    /// stalled every read of the object for as long as it ran. The receiver is known
114    /// where these arms are generated, so it is the receiver that decides.
115    ///
116    /// Return `None` for any path this borrow cannot serve: a field write, a
117    /// `&mut self` method, a nested field whose child declined. The router then
118    /// retakes the lock exclusively and dispatches through
119    /// [`repe_handle_into`](Self::repe_handle_into), so declining costs
120    /// correctness nothing — it is the default, and a hand-written impl that
121    /// never overrides this behaves exactly as it did before the path existed.
122    ///
123    /// Three obligations come with overriding it:
124    ///
125    /// * **Answer identically.** Whatever this returns for a path is what the
126    ///   client sees; the exclusive path is not consulted afterwards. Decline
127    ///   rather than approximate.
128    /// * **Write nothing when declining.** A `None` return must leave `out` as
129    ///   it was found, so the exclusive attempt starts from an empty body.
130    ///   [`ObjectBody::entry_try_with`] exists to make that mechanical when the
131    ///   decline surfaces partway through an object: it rewinds the whole
132    ///   object, so propagating its `None` is all a caller has to do.
133    /// * **Leave the body alone when declining.** `body` is handed over as
134    ///   `&mut Option<Value>` rather than by value precisely so the exclusive
135    ///   retry can re-dispatch the same request without a clone. Call
136    ///   [`Option::take`] on it only once this borrow has committed to
137    ///   answering — an `Err` counts as an answer — and never on a path that
138    ///   goes on to return `None`. A body taken and then declined reaches the
139    ///   exclusive path as `None`, where it surfaces as a spurious
140    ///   [`BodyExpected`](StructError::BodyExpected).
141    ///
142    /// A derived impl settles the whole-object listing before it writes or
143    /// invokes anything, through
144    /// [`repe_listing_declines`](Self::repe_listing_declines) — because a
145    /// decline discovered later would leave the entries before it run twice,
146    /// once here and once on the exclusive retry, and a rewind cannot undo a
147    /// call. A hand-written impl that invokes anything before it can decide owes
148    /// the same care.
149    fn repe_shared_into(
150        &self,
151        segments: &[&str],
152        body: &mut Option<Value>,
153        out: &mut ResponseBody<'_>,
154    ) -> Option<StructResult<()>> {
155        let _ = (segments, body, out);
156        None
157    }
158
159    /// Whether a shared whole-object listing of this struct declines — asked
160    /// **before** the listing writes or invokes anything.
161    ///
162    /// A listing is the one read that composes many others, so a decline
163    /// discovered partway through is not recoverable: the exclusive retry
164    /// re-runs the entries before it, and an entry that was *invoked* rather
165    /// than serialized runs a second time. Rewinding the response buffer undoes
166    /// the bytes; it cannot undo a call.
167    ///
168    /// So the answer has to be available at the top, and it has to cover the
169    /// whole subtree — a parent's listing composes its children's, so a child
170    /// that declines takes the parent's listing with it. That is why this is on
171    /// [`RepeStruct`] rather than only on
172    /// [`RepeMethods::REPE_LISTING_NEEDS_EXCLUSIVE`], which answers the same
173    /// question about one method table's accessors and nothing beneath them. A
174    /// derived impl returns that const OR'd with every `#[repe(nested)]` child's
175    /// answer, so the whole tree is settled before the first byte is written.
176    ///
177    /// The default is `true`, which is the accurate answer for the default
178    /// [`repe_shared_into`](Self::repe_shared_into): it declines every path,
179    /// listings included. A hand-written impl that overrides `repe_shared_into`
180    /// to serve a listing should override this too, or every derived struct
181    /// nesting it gives up its own shared listing.
182    ///
183    /// **Overriding it is a promise**, and it is the promise the invariant rests
184    /// on: returning `false` asserts that `repe_shared_into(&[], &mut None, ..)`
185    /// answers `Some(..)`. Breaking it still yields a correct response — the listing
186    /// rewinds and the exclusive path retries — but anything the shared attempt
187    /// had already invoked runs twice.
188    fn repe_listing_declines(&self) -> bool {
189        true
190    }
191
192    /// Whether any path can answer a **body-carrying** frame through
193    /// [`repe_shared_into`](Self::repe_shared_into).
194    ///
195    /// The router asks before it takes the read lock. REPE puts a body on a
196    /// write *and* on a call with arguments, so a body alone cannot say which
197    /// one arrived — but a struct whose every write needs `&mut self` knows the
198    /// answer for all of them in advance, and `false` lets the router skip the
199    /// lock, the walk and the certain decline.
200    ///
201    /// This is a hint, and it cannot cost correctness. Everything the shared
202    /// borrow answers with a body, the exclusive path answers identically: a
203    /// `&self` method is callable through either, and every refusal
204    /// ([`BodyUnexpected`](StructError::BodyUnexpected) on a read-only endpoint,
205    /// [`InvalidPath`](StructError::InvalidPath) on an unknown one) is generated
206    /// from the same shape on both sides. `false` on an impl that could have
207    /// served one costs concurrency for that frame and nothing else.
208    ///
209    /// The default is `true`, the accurate answer for a hand-written
210    /// `repe_shared_into` this crate cannot see inside. A derived impl narrows
211    /// it to `false` when nothing it generates can answer a body: no `&self`
212    /// method taking arguments, no read-only endpoint whose refusal is servable
213    /// shared, and no `#[repe(nested)]` child that has either.
214    const REPE_SHARED_SERVES_BODIES: bool = true;
215}
216
217/// A **conditionally-present** child: a component that is not in every build, a
218/// subsystem that is not configured, a resource that failed to open.
219///
220/// `Option` is a foreign type and [`RepeStruct`] is this crate's trait, so a
221/// host cannot write this impl itself — its choices without one are a newtype
222/// per crate or one impl per concrete `Option<Child>`. Carrying it here is what
223/// lets `#[repe(nested)]` be put on an `Option<T>` field directly, which is
224/// where a host reaches for it first.
225///
226/// Present forwards everything to the inner value. Absent answers:
227///
228/// * a **read at the child's own path** with `null`, so a whole-object listing
229///   of the parent shows the key with nothing behind it rather than failing;
230/// * a **write, or any subpath** with [`StructError::InvalidPath`], because a
231///   silent no-op against a live resource is worse than an error — a client
232///   that configured an absent component would otherwise be told it succeeded;
233/// * [`repe_listing_declines`](RepeStruct::repe_listing_declines) with `false`
234///   when absent, since a `null` needs no exclusive borrow, and with the inner
235///   value's own answer when present.
236///
237/// **Presence is the host's, not the client's.** A `null` written at the child's
238/// own path is refused with [`StructError::BodyUnexpected`] whether the child is
239/// there or not, so the one value this path can read back is the one value it
240/// will not take. Removing a child would otherwise be a door that only opens one
241/// way, since creating one is the write an absent child already refuses. A
242/// whole-object write at the *parent* replaces the field, `null` included; that
243/// is a replace of the parent rather than a write to this path.
244///
245/// This matches what Glaze publishes for an unmapped optional member, so a
246/// port's wire shape does not change with the language.
247impl<T: RepeStruct> RepeStruct for Option<T> {
248    fn repe_handle(
249        &mut self,
250        segments: &[&str],
251        body: Option<Value>,
252    ) -> StructResult<Option<Value>> {
253        refuse_presence_write(segments, body.as_ref())?;
254        match self {
255            Some(inner) => inner.repe_handle(segments, body),
256            None => absent_child(segments, body.is_some()).map(|()| None),
257        }
258    }
259
260    fn repe_handle_into(
261        &mut self,
262        segments: &[&str],
263        body: Option<Value>,
264        out: &mut ResponseBody<'_>,
265    ) -> StructResult<()> {
266        refuse_presence_write(segments, body.as_ref())?;
267        match self {
268            Some(inner) => inner.repe_handle_into(segments, body, out),
269            None => {
270                absent_child(segments, body.is_some())?;
271                out.write_null();
272                Ok(())
273            }
274        }
275    }
276
277    fn repe_shared_into(
278        &self,
279        segments: &[&str],
280        body: &mut Option<Value>,
281        out: &mut ResponseBody<'_>,
282    ) -> Option<StructResult<()>> {
283        // Refusing touches nothing, so it needs no exclusive borrow — and it has
284        // to be decided here rather than left to the retry, or a present child
285        // would forward the `null` to its inner value under both guards.
286        if let Err(err) = refuse_presence_write(segments, body.as_ref()) {
287            return Some(Err(err));
288        }
289        match self {
290            Some(inner) => inner.repe_shared_into(segments, body, out),
291            // Absent is a constant: no state to borrow exclusively, so every
292            // answer above is servable here and none of them touches `body`.
293            None => Some(absent_child(segments, body.is_some()).map(|()| out.write_null())),
294        }
295    }
296
297    fn repe_listing_declines(&self) -> bool {
298        match self {
299            Some(inner) => inner.repe_listing_declines(),
300            None => false,
301        }
302    }
303
304    /// A present child answers for itself. An absent one refuses every write
305    /// and every sub-path, and refuses them identically on both borrows, so it
306    /// contributes nothing the exclusive path would not also say.
307    const REPE_SHARED_SERVES_BODIES: bool = T::REPE_SHARED_SERVES_BODIES;
308}
309
310/// Refuse a `null` written at an optional child's **own** path, present or
311/// absent.
312///
313/// `null` is what that path *reads* when the child is absent, so a client will
314/// try writing it back, and without this it lands on whichever branch happens to
315/// be live: a present child forwards it to its inner value and answers with that
316/// type's serde complaint, an absent one answers `InvalidPath`. Neither says
317/// what is actually true, which is that presence is not settable here.
318///
319/// It is refused rather than honoured because honouring it would open a one-way
320/// door: `null` could remove a child, and nothing could put it back — creating
321/// one is the write an absent child already refuses, for the reason that a
322/// client configuring something that is not there must not be told it worked.
323/// Presence belongs to the host on both sides of that. A whole-object write at
324/// the *parent* still replaces the field, `null` included; that is a replace of
325/// the parent, not a write to this path.
326fn refuse_presence_write(segments: &[&str], body: Option<&Value>) -> StructResult<()> {
327    if segments.is_empty() && matches!(body, Some(Value::Null)) {
328        return Err(StructError::BodyUnexpected {
329            path: path_from_segments(segments),
330        });
331    }
332    Ok(())
333}
334
335/// The absent half of [`RepeStruct for Option<T>`](RepeStruct#impl-RepeStruct-for-Option<T>):
336/// `Ok(())` for the one request an absent child can answer, and
337/// [`StructError::InvalidPath`] for the rest.
338///
339/// The path is relative to the child, so a parent's
340/// [`prepend_path`] names the field the client actually asked for.
341fn absent_child(segments: &[&str], has_body: bool) -> StructResult<()> {
342    if segments.is_empty() && !has_body {
343        Ok(())
344    } else {
345        Err(StructError::InvalidPath {
346            path: path_from_segments(segments),
347        })
348    }
349}
350
351/// Method table for a struct whose methods are declared with `#[repe::methods]`
352/// on an inherent `impl` block.
353///
354/// Generated by the attribute macro, which sees every signature in the block and
355/// so cannot fall behind the type the way a hand-maintained
356/// `#[repe(methods(..))]` list can. `#[derive(RepeStruct)]` dispatches path
357/// segments that match no field through this table when the struct carries the
358/// `#[repe(methods)]` marker.
359///
360/// Implementing this by hand is supported but unusual; the macro exists so the
361/// signatures stay derived from the `impl` block.
362#[diagnostic::on_unimplemented(
363    message = "`{Self}` declares `#[repe(methods)]` but its impl block is not annotated",
364    label = "no method table for `{Self}`",
365    note = "annotate the inherent `impl {Self}` block with `#[repe::methods]` (or `#[repe_core::methods]` when only `repe-core` is a dependency), or drop `#[repe(methods)]` from the struct"
366)]
367pub trait RepeMethods: MethodsDeclared {
368    /// `(endpoint, signature)` pairs published in the whole-struct listing.
369    const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)];
370
371    /// Endpoints in this table that are **field-shaped**: served by a
372    /// getter/setter pair (`#[repe(get = "...")]` / `#[repe(set = "...")]`)
373    /// rather than by an argument list.
374    ///
375    /// They are deliberately absent from
376    /// [`REPE_METHOD_SIGNATURES`](Self::REPE_METHOD_SIGNATURES), because they
377    /// have no signature to publish: a client reads and writes one the way it
378    /// reads and writes a field, so the whole-struct listing shows each one's
379    /// current value rather than a signature string. The derived listing reads
380    /// those values back through [`repe_call`](Self::repe_call), or through
381    /// [`repe_call_shared_into`](Self::repe_call_shared_into) when it is being
382    /// served under a shared borrow.
383    ///
384    /// Defaults to empty, so a hand-written impl need not mention it. One
385    /// invariant comes with listing a name here, and the derived listing relies
386    /// on it: [`repe_call`](Self::repe_call) must answer
387    /// `segments = &[name], body = None` with `Ok(Some(value))`. A name the
388    /// table cannot dispatch turns every whole-struct read into that name's
389    /// error. `#[repe::methods]` upholds it by construction, because it emits
390    /// this list from the getters it generated arms for. The shared-borrow
391    /// listing asks the same question of `repe_call_shared_into`, where a `None`
392    /// is not a failure — it declines the whole listing to the exclusive path.
393    const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] = &[];
394
395    /// `true` only on the placeholder table `#[repe::methods]` emits when the
396    /// block itself failed to parse.
397    ///
398    /// That table publishes nothing, so every compile-time check against it
399    /// would fire and bury the real error under a second, misleading one. This
400    /// says "these tables are not the truth" so those checks can stand down —
401    /// which emptiness alone cannot say, because a block that compiles and
402    /// publishes nothing is empty too, and its checks must still run.
403    #[doc(hidden)]
404    const REPE_TABLE_RECOVERED: bool = false;
405
406    /// Whether the whole-struct listing must be served exclusively because some
407    /// entry in it can only be read through `&mut self`.
408    ///
409    /// This is the one question the shared listing has to settle **before** it
410    /// runs anything, and it is why it is a `const` rather than a check per
411    /// entry. A listing is the one read that composes many others; a decline
412    /// discovered partway through leaves the entries before it already invoked,
413    /// and the exclusive retry invokes them again. A `&self` getter over a read
414    /// counter would report the second call.
415    ///
416    /// Only the getter half of a field-shaped endpoint can force it. Fields
417    /// serialize, published signatures are string literals, and a nested child
418    /// declines before writing anything of its own — none of those is a *call*.
419    /// So this is `true` exactly when some accessor's getter takes `&mut self`.
420    ///
421    /// The default is the conservative one: any accessor at all forces the
422    /// exclusive path, which is what a hand-written table gets for free and what
423    /// this crate did for every table before the receiver was carried here.
424    /// `#[repe::methods]` overrides it with the answer it computed from the
425    /// receivers it has already seen, so a struct whose computed values are pure
426    /// reads keeps its shared listing — and so does every ancestor that nests
427    /// it, since a child's decline propagates.
428    ///
429    /// **Overriding it is a promise.** Setting it to `false` asserts that
430    /// [`repe_call_shared_into`](Self::repe_call_shared_into) answers
431    /// `segments = &[name], body = None` with `Some(..)` for every name in
432    /// [`REPE_ACCESSOR_ENDPOINTS`](Self::REPE_ACCESSOR_ENDPOINTS). A table that
433    /// breaks that promise still produces a correct response — the listing
434    /// rewinds and retries exclusively — but the getters that ran before the
435    /// decline run a second time, which is the double invocation this const
436    /// exists to rule out.
437    const REPE_LISTING_NEEDS_EXCLUSIVE: bool = !Self::REPE_ACCESSOR_ENDPOINTS.is_empty();
438
439    /// Whether any endpoint in this table can answer a body-carrying frame
440    /// through [`repe_call_shared_into`](Self::repe_call_shared_into).
441    ///
442    /// The table half of
443    /// [`RepeStruct::REPE_SHARED_SERVES_BODIES`], which ORs this with what the
444    /// struct's own fields and children say. Three shapes here can answer one: a
445    /// `&self` method that takes arguments, a `&self` setter, and a read-only
446    /// accessor, whose refusal needs no exclusive borrow to give.
447    ///
448    /// The default is `true`, which is never wrong — only, for a table that
449    /// serves no body, slower than it needs to be.
450    const REPE_SHARED_SERVES_BODIES: bool = true;
451
452    /// Invoke the method named by `segments[0]`.
453    ///
454    /// `segments` is the remaining path relative to the struct root, so error
455    /// paths match the ones [`RepeStruct::repe_handle`] produces for fields.
456    /// Returns [`StructError::InvalidPath`] when no method matches.
457    fn repe_call(&mut self, segments: &[&str], body: Option<Value>) -> StructResult<Option<Value>>;
458
459    /// Encode-in-place counterpart of [`repe_call`](Self::repe_call), mirroring
460    /// [`RepeStruct::repe_handle_into`].
461    fn repe_call_into(
462        &mut self,
463        segments: &[&str],
464        body: Option<Value>,
465        out: &mut ResponseBody<'_>,
466    ) -> StructResult<()> {
467        let value = self.repe_call(segments, body)?;
468        write_optional(out, segments, value)
469    }
470
471    /// Shared-borrow counterpart of [`repe_call_into`](Self::repe_call_into),
472    /// mirroring [`RepeStruct::repe_shared_into`] and carrying the same three
473    /// obligations: answer identically, decline without writing, and leave
474    /// `body` in place when declining.
475    ///
476    /// `#[repe::methods]` serves every `&self` method here — including one
477    /// taking arguments, which is a call rather than a mutation however the
478    /// frame is shaped — along with the getter half of a `&self` accessor, and
479    /// declines everything else.
480    fn repe_call_shared_into(
481        &self,
482        segments: &[&str],
483        body: &mut Option<Value>,
484        out: &mut ResponseBody<'_>,
485    ) -> Option<StructResult<()>> {
486        let _ = (segments, body, out);
487        None
488    }
489}
490
491/// Marker emitted by `#[derive(RepeStruct)]` when the struct carries the
492/// `#[repe(methods)]` attribute.
493///
494/// A derive macro cannot see `impl` blocks, so the two halves of the
495/// `#[repe::methods]` surface are tied together by a compile-time handshake.
496/// This marker is a supertrait of [`RepeMethods`], so the table the attribute
497/// macro generates simply cannot be implemented for a struct that did not
498/// declare it — no assertion to emit, and none to forget. Missing either half is
499/// a compile error naming the attribute that is absent, rather than a method
500/// that quietly never reaches the wire.
501#[diagnostic::on_unimplemented(
502    message = "`{Self}` has an annotated `methods` impl block but does not declare it",
503    label = "`{Self}` is missing `#[repe(methods)]`",
504    note = "add `#[repe(methods)]` next to `#[derive(RepeStruct)]` on `{Self}` so the derived router dispatches to the impl block"
505)]
506pub trait MethodsDeclared {}
507
508/// Build a path string from segments for error messages.
509pub fn path_from_segments(segments: &[&str]) -> String {
510    if segments.is_empty() {
511        String::from("")
512    } else {
513        let mut s = String::new();
514        for segment in segments {
515            s.push('/');
516            s.push_str(segment);
517        }
518        s
519    }
520}
521
522/// Prefix error paths with an additional segment when bubbling errors from nested structs.
523pub fn prepend_path(mut err: StructError, prefix: &str) -> StructError {
524    let with_prefix = |path: String| {
525        if prefix.is_empty() {
526            path
527        } else if path.is_empty() {
528            format!("/{}", prefix)
529        } else if path.starts_with('/') {
530            format!("/{prefix}{path}")
531        } else {
532            format!("/{prefix}/{path}")
533        }
534    };
535
536    match &mut err {
537        StructError::InvalidPath { path }
538        | StructError::InvalidSubpath { path }
539        | StructError::BodyExpected { path }
540        | StructError::BodyUnexpected { path }
541        | StructError::Serialize { path, .. }
542        | StructError::Deserialize { path, .. }
543        | StructError::Execution { path, .. } => {
544            *path = with_prefix(std::mem::take(path));
545        }
546    }
547    err
548}
549
550/// The bound on [`ResponseBody::write_typed_slice`] without the `typed`
551/// feature. Deliberately unimplementable — it is sealed, so no type satisfies
552/// it *and none can be made to* — which makes the method uncallable and a
553/// `#[repe(typed)]` field an error against a named feature rather than against
554/// a method that does not exist.
555///
556/// It exists **only** in that configuration. With the feature on, the method
557/// takes `beve::BeveTypedSlice + Serialize` directly and this trait is not
558/// there at all — a diagnostic device has no business being public API of the
559/// build everyone ships, and, since every type BEVE accepts would satisfy it
560/// through a blanket impl, nothing would ever name it there anyway.
561/// Seals [`TypedSliceElement`] so that "no type implements it" is a fact this
562/// crate enforces rather than one it merely asserts. Without this a downstream
563/// crate could write `impl TypedSliceElement for T {}` — the trait is public and
564/// has no members, so nothing stops it — and reach a `write_typed_slice` whose
565/// body is an `unreachable!`.
566#[cfg(not(feature = "typed"))]
567mod sealed {
568    pub trait Sealed {}
569}
570
571#[cfg(not(feature = "typed"))]
572#[diagnostic::on_unimplemented(
573    message = "`#[repe(typed)]` needs the `typed` feature of `repe-core`",
574    label = "no BEVE typed-array encoding is compiled in",
575    note = "enable it with `repe-core = {{ version = \"2\", features = [\"typed\"] }}`, or drop \
576            `#[repe(typed)]` from the field to serve it as a JSON array",
577    note = "crates that depend on `repe` rather than `repe-core` already have it on"
578)]
579pub trait TypedSliceElement: sealed::Sealed {}
580
581/// Response body under construction for a [`RepeStruct`] read.
582///
583/// Handed to [`RepeStruct::repe_handle_into`] so a read serializes the live field
584/// straight into the outgoing frame buffer. The alternative — returning a
585/// [`serde_json::Value`] that the router then re-serializes — allocates an
586/// intermediate tree per read, which is what a client polling a wide object at
587/// kilohertz pays for.
588///
589/// The body starts out empty and [`BodyFormat::Json`]; the write that fills it
590/// also settles the format, so a [`write_typed_slice`](Self::write_typed_slice)
591/// body reports [`BodyFormat::Beve`]. Exactly one top-level write is expected —
592/// a value, a null, or an [`object`](Self::object).
593///
594/// Any failed write — including one that fails partway through an
595/// [`object`](Self::object) — rewinds the buffer to where that write began, so a
596/// caller that recovers from a [`StructError`] never ships half-serialized
597/// bytes.
598pub struct ResponseBody<'a> {
599    buf: &'a mut Vec<u8>,
600    format: BodyFormat,
601    /// True while this body is a value *inside* an enclosing JSON object, where
602    /// the frame format is already committed to JSON.
603    ///
604    /// Reached from generated code by exactly one path: the whole-struct listing
605    /// writes each accessor endpoint's value through
606    /// [`ObjectBody::entry_with`] or [`ObjectBody::entry_try_with`], so a
607    /// `#[repe(typed)]` getter listed inside the object emits a JSON array
608    /// rather than switching the enclosing frame to BEVE. (A `#[repe(nested)]`
609    /// field also gets a nested body, but its child is always entered with empty
610    /// segments and so always takes its own object branch.) The flag also covers
611    /// hand-written `repe_handle_into` impls, which can call anything from
612    /// anywhere; a JSON-array fallback beats corrupting the frame.
613    ///
614    /// [`write_typed_slice`](Self::write_typed_slice) is the only reader, and
615    /// without the `typed` feature there is no typed encoding to divert — the
616    /// flag is still set where an object is entered, so that turning the
617    /// feature on needs no other change.
618    ///
619    /// `expect` rather than `allow`: if this ever gains a second reader that is
620    /// not feature-gated, the attribute becomes wrong and says so.
621    #[cfg_attr(not(feature = "typed"), expect(dead_code))]
622    nested: bool,
623}
624
625impl<'a> ResponseBody<'a> {
626    /// Wrap an output buffer. `buf` is normally empty; writes append to it.
627    pub fn new(buf: &'a mut Vec<u8>) -> Self {
628        Self {
629            buf,
630            format: BodyFormat::Json,
631            nested: false,
632        }
633    }
634
635    /// The body format settled by the write that filled this body.
636    pub fn format(&self) -> BodyFormat {
637        self.format
638    }
639
640    /// Serialize `value` as the whole body, as JSON.
641    ///
642    /// `path` names the field for the error message and is only read when
643    /// serialization fails.
644    pub fn write<T>(&mut self, path: &str, value: &T) -> StructResult<()>
645    where
646        T: Serialize + ?Sized,
647    {
648        self.write_with_path(|| String::from(path), value)
649    }
650
651    /// [`write`](Self::write) with the error path built only if one is needed.
652    ///
653    /// The derived arms pass a `&'static str` literal and pay nothing either
654    /// way, but the [`RepeStruct::repe_handle_into`] default has to *assemble*
655    /// its path from the segments — on every successful read, for a string it
656    /// then throws away.
657    fn write_with_path<T, F>(&mut self, path: F, value: &T) -> StructResult<()>
658    where
659        T: Serialize + ?Sized,
660        F: FnOnce() -> String,
661    {
662        let start = self.buf.len();
663        match serde_json::to_writer(&mut *self.buf, value) {
664            Ok(()) => Ok(()),
665            Err(source) => {
666                self.buf.truncate(start);
667                Err(StructError::Serialize {
668                    path: path(),
669                    source,
670                })
671            }
672        }
673    }
674
675    /// Write a JSON `null` body — the response to a write, or to a read that has
676    /// nothing to return.
677    pub fn write_null(&mut self) {
678        self.buf.extend_from_slice(b"null");
679    }
680
681    /// Write `slice` as a BEVE typed numeric array and set the body format to
682    /// [`BodyFormat::Beve`].
683    ///
684    /// The same bulk encode `repe::message::MessageBuilder::body_typed_slice`
685    /// produces — one `copy_nonoverlapping` on little-endian targets rather than
686    /// a per-element serde walk, and byte-identical to what Glaze emits for the
687    /// same array. This is what `#[repe(typed)]` routes a numeric field to.
688    /// (Named rather than linked: the builder lives in `repe`, which this crate
689    /// deliberately does not depend on.)
690    ///
691    /// Inside an enclosing object — the whole-struct listing — the frame is
692    /// already committed to JSON, so the slice is written as a JSON array
693    /// instead. A field only reaches the typed encoding when it is read on its
694    /// own.
695    ///
696    /// Requires the `typed` feature, which is what carries `beve`. It is on
697    /// through `repe` and off for a direct `repe-core` dependency, where this
698    /// signature is replaced by one whose bound no type satisfies, so that
699    /// calling it is a compile error naming the feature.
700    #[cfg(feature = "typed")]
701    pub fn write_typed_slice<T>(&mut self, path: &str, slice: &[T]) -> StructResult<()>
702    where
703        T: beve::BeveTypedSlice + Serialize,
704    {
705        if self.nested {
706            return self.write(path, slice);
707        }
708        let encoded_len = beve::typed_slice_size(slice) as usize;
709        self.buf.reserve(encoded_len);
710        let start = self.buf.len();
711        beve::to_writer_typed_slice(&mut *self.buf, slice)
712            .expect("writing a typed slice into a Vec is infallible");
713        debug_assert_eq!(self.buf.len() - start, encoded_len);
714        self.format = BodyFormat::Beve;
715        Ok(())
716    }
717
718    /// The `typed`-less stand-in for [`write_typed_slice`], kept so a
719    /// `#[repe(typed)]` field reports a missing *feature* rather than a missing
720    /// *method*.
721    ///
722    /// No type implements [`TypedSliceElement`] without the feature, so this is
723    /// uncallable and the diagnostic on that trait is what a caller actually
724    /// reads.
725    ///
726    /// **The `E0277` this produces is the deliverable, not a side effect.**
727    /// `#[cfg]`-ing this method away instead is the obvious simplification and
728    /// silently degrades it to `E0599`, "no method named `write_typed_slice`",
729    /// pointing at a derive rather than at a feature — and nothing in CI would
730    /// notice. Falling back to the JSON array here would be worse still: it
731    /// compiles and changes the wire.
732    ///
733    /// [`write_typed_slice`]: ResponseBody::write_typed_slice
734    #[cfg(not(feature = "typed"))]
735    pub fn write_typed_slice<T>(&mut self, path: &str, slice: &[T]) -> StructResult<()>
736    where
737        T: TypedSliceElement,
738    {
739        let _ = (path, slice);
740        unreachable!("`TypedSliceElement` is sealed and implemented by nothing")
741    }
742
743    /// Begin a JSON object body, written key by key.
744    ///
745    /// Used by the whole-struct listing so a wide object is emitted in one pass
746    /// instead of through a [`serde_json::Map`].
747    pub fn object(&mut self) -> ObjectBody<'_> {
748        let start = self.buf.len();
749        self.buf.push(b'{');
750        ObjectBody {
751            buf: self.buf,
752            start,
753            first: true,
754        }
755    }
756}
757
758/// A JSON object body being written key by key. Created by
759/// [`ResponseBody::object`]; call [`finish`](Self::finish) to close it.
760///
761/// An entry that fails — or that [`entry_try_with`](Self::entry_try_with)
762/// declines — rewinds the buffer past the opening brace, so a partly written
763/// object is never left behind for a caller that recovers from it. Dropping
764/// without calling [`finish`](Self::finish) is the same situation and leaves
765/// nothing behind either, since both ways out without finishing have already
766/// rewound.
767pub struct ObjectBody<'a> {
768    buf: &'a mut Vec<u8>,
769    /// Buffer length before the opening brace, to rewind to on failure.
770    start: usize,
771    first: bool,
772}
773
774impl ObjectBody<'_> {
775    fn key(&mut self, key: &str) -> StructResult<()> {
776        if self.first {
777            self.first = false;
778        } else {
779            self.buf.push(b',');
780        }
781        serde_json::to_writer(&mut *self.buf, key).map_err(|source| StructError::Serialize {
782            path: format!("/{key}"),
783            source,
784        })?;
785        self.buf.push(b':');
786        Ok(())
787    }
788
789    /// Run one entry, rewinding the whole object if it fails.
790    fn entry_with_rewind<F>(&mut self, f: F) -> StructResult<()>
791    where
792        F: FnOnce(&mut Self) -> StructResult<()>,
793    {
794        match f(self) {
795            Ok(()) => Ok(()),
796            Err(err) => {
797                self.buf.truncate(self.start);
798                Err(err)
799            }
800        }
801    }
802
803    /// Write one `"key": value` entry.
804    pub fn entry<T>(&mut self, key: &str, value: &T) -> StructResult<()>
805    where
806        T: Serialize + ?Sized,
807    {
808        self.entry_with_rewind(|this| {
809            this.key(key)?;
810            serde_json::to_writer(&mut *this.buf, value).map_err(|source| StructError::Serialize {
811                path: format!("/{key}"),
812                source,
813            })
814        })
815    }
816
817    /// Write one `"key": <value>` entry whose value is produced by `f`, for a
818    /// nested [`RepeStruct`] that fills the body itself.
819    ///
820    /// The body handed to `f` is marked as nested: the enclosing frame is
821    /// already JSON, so a [`ResponseBody::write_typed_slice`] inside it falls
822    /// back to a JSON array rather than switching the frame to BEVE.
823    pub fn entry_with<F>(&mut self, key: &str, f: F) -> StructResult<()>
824    where
825        F: FnOnce(&mut ResponseBody<'_>) -> StructResult<()>,
826    {
827        self.entry_with_rewind(|this| {
828            this.key(key)?;
829            let mut body = ResponseBody {
830                buf: this.buf,
831                format: BodyFormat::Json,
832                nested: true,
833            };
834            f(&mut body)
835        })
836    }
837
838    /// [`entry_with`](Self::entry_with) for a value the source may decline to
839    /// produce, as [`RepeStruct::repe_shared_into`] declines a path that needs
840    /// exclusive access.
841    ///
842    /// `None` rewinds the whole object, exactly as an `Err` does, so a caller
843    /// that declines in turn leaves the buffer as it found it without a second
844    /// step. Dropping the object without calling [`finish`](Self::finish) then
845    /// leaves nothing behind, because the only ways out without finishing are
846    /// an error and a decline, and both have already rewound.
847    pub fn entry_try_with<F>(&mut self, key: &str, f: F) -> Option<StructResult<()>>
848    where
849        F: FnOnce(&mut ResponseBody<'_>) -> Option<StructResult<()>>,
850    {
851        let outcome = match self.key(key) {
852            Ok(()) => {
853                let mut body = ResponseBody {
854                    buf: self.buf,
855                    format: BodyFormat::Json,
856                    nested: true,
857                };
858                f(&mut body)
859            }
860            Err(err) => Some(Err(err)),
861        };
862        if !matches!(outcome, Some(Ok(()))) {
863            self.buf.truncate(self.start);
864        }
865        outcome
866    }
867
868    /// Close the object.
869    pub fn finish(self) {
870        self.buf.push(b'}');
871    }
872}
873
874/// Write the `Option<Value>` a [`RepeStruct::repe_handle`] returned as the whole
875/// body: the payload, or `null` when there is nothing to send.
876///
877/// Shared by the [`RepeStruct::repe_handle_into`] and
878/// [`RepeMethods::repe_call_into`] defaults, which differ only in which method
879/// they delegate to.
880fn write_optional(
881    out: &mut ResponseBody<'_>,
882    segments: &[&str],
883    value: Option<Value>,
884) -> StructResult<()> {
885    match value {
886        Some(value) => out.write_with_path(|| path_from_segments(segments), &value),
887        None => {
888            out.write_null();
889            Ok(())
890        }
891    }
892}
893
894/// Compile-time check that the three sets of endpoints on one struct do not
895/// overlap.
896///
897/// The two macros cannot see each other's input, so the derive emits a call to
898/// this against everything *it* publishes — fields, plus any method named in a
899/// struct-level `#[repe(methods(..))]` list — and the two generated
900/// [`RepeMethods`] tables. Without it a collision is silent and costly: one
901/// declaration wins dispatch, the other becomes permanently unreachable, and
902/// the whole-struct listing emits the same key twice. The two listings do not
903/// even agree on that last part, since a `serde_json::Map` deduplicates the key
904/// and the streaming encoder does not.
905///
906/// Collisions the macros *can* see on their own — two fields, two listed
907/// methods, a field against a listed method, two endpoints in one
908/// `#[repe::methods]` block — are rejected at macro time with a message naming
909/// the endpoint and pointing at the second declaration.
910///
911/// The third pairing, methods against accessors, is unreachable from a
912/// generated table for the same reason; it is checked because a hand-written
913/// [`RepeMethods`] impl can produce it.
914#[doc(hidden)]
915pub const fn assert_no_endpoint_collision(
916    declared: &[&str],
917    methods: &[(&str, &str)],
918    accessors: &[&str],
919) {
920    let mut i = 0;
921    while i < methods.len() {
922        if const_contains(declared, methods[i].0) {
923            panic!(
924                "a published method and an endpoint declared on the struct itself \
925                 share a name: the struct's declaration wins dispatch and the method could \
926                 never be called. Rename one with `#[repe(rename = \"...\")]`."
927            );
928        }
929        i += 1;
930    }
931
932    let mut i = 0;
933    while i < accessors.len() {
934        if const_contains(declared, accessors[i]) {
935            panic!(
936                "a `#[repe(get = \"...\")]` accessor and an endpoint declared on the struct \
937                 itself share a name: the struct's declaration wins dispatch and the accessor \
938                 could never be called. Rename the struct's with \
939                 `#[repe(rename = \"...\")]`, or give the accessor a different endpoint."
940            );
941        }
942
943        if listed_signature(methods, accessors[i]).is_some() {
944            panic!(
945                "a published method and a `#[repe(get = \"...\")]` accessor in the \
946                 same table share an endpoint name: one of them is unreachable, and the \
947                 whole-struct listing would show the endpoint twice."
948            );
949        }
950        i += 1;
951    }
952}
953
954/// Compile-time check that a `#[repe(listing_order(..))]` list names exactly the
955/// endpoints the struct publishes.
956///
957/// The derive validates the half it can see on its own — fields and struct-level
958/// `#[repe(methods(..))]` entries — with an error that names the offending key.
959/// It cannot see the `#[repe::methods]` impl block, so the other half is checked
960/// here, where both generated tables are in scope. A `const` panic cannot name
961/// the key, which is why the derive keeps everything it can reach at macro time.
962///
963/// Both directions matter. An order naming an endpoint that does not exist would
964/// emit a key whose value came from a failed dispatch; an order omitting one
965/// would silently drop it from every whole-object read, which is the harder bug
966/// to see because the endpoint still answers on its own path.
967#[doc(hidden)]
968pub const fn assert_listing_order(
969    order: &[&str],
970    declared: &[&str],
971    methods: &[(&str, &str)],
972    accessors: &[&str],
973    recovering: bool,
974) {
975    // `recovering` is [`RepeMethods::REPE_TABLE_RECOVERED`]: the block failed to
976    // parse, so the tables describe nothing and every key here would look
977    // unknown. This assertion would then be exactly the extra error that
978    // recovery exists to prevent. It must come from the marker rather than from
979    // the tables being empty — a block that compiles and publishes nothing is
980    // also empty, and an unknown key in *that* struct's order has to be caught
981    // here, because the derive skips its own check whenever an impl block is in
982    // play.
983    let mut i = 0;
984    while i < order.len() {
985        let known = const_contains(declared, order[i])
986            || const_contains(accessors, order[i])
987            || listed_signature(methods, order[i]).is_some();
988        if !known && !recovering {
989            panic!(
990                "`#[repe(listing_order(..))]` names a key that is not an endpoint on this \
991                 struct. It lists the whole-object listing's keys, so every name in it has to \
992                 be a field, a listed method, or an endpoint of the annotated `methods` impl block."
993            );
994        }
995        i += 1;
996    }
997
998    let mut j = 0;
999    while j < methods.len() {
1000        if !const_contains(order, methods[j].0) {
1001            panic!(
1002                "a method on the annotated `methods` impl block is missing from `#[repe(listing_order(..))]`, \
1003                 which names the whole-object listing's keys in full. An omitted endpoint \
1004                 would disappear from every whole-object read while still answering on its \
1005                 own path."
1006            );
1007        }
1008        j += 1;
1009    }
1010
1011    let mut j = 0;
1012    while j < accessors.len() {
1013        if !const_contains(order, accessors[j]) {
1014            panic!(
1015                "a `#[repe(get = \"...\")]` accessor is missing from \
1016                 `#[repe(listing_order(..))]`, which names the whole-object listing's keys in \
1017                 full. An omitted endpoint would disappear from every whole-object read while \
1018                 still answering on its own path."
1019            );
1020        }
1021        j += 1;
1022    }
1023}
1024
1025/// The published signature for `name`, or `None` when the name belongs to a
1026/// field-shaped accessor instead.
1027///
1028/// Called from a `const` block in the ordered listing a
1029/// `#[repe(listing_order(..))]` produces: the derive cannot see the
1030/// `#[repe::methods]` block, so it does not know which of the two tables an
1031/// ordered key came from, but the tables themselves are constants and the
1032/// question folds away before run time.
1033#[doc(hidden)]
1034pub const fn listed_signature<'a>(methods: &[(&'a str, &'a str)], name: &str) -> Option<&'a str> {
1035    let mut i = 0;
1036    while i < methods.len() {
1037        if const_str_eq(methods[i].0, name) {
1038            return Some(methods[i].1);
1039        }
1040        i += 1;
1041    }
1042    None
1043}
1044
1045/// `slice.contains(&name)` usable in a `const` context.
1046const fn const_contains(list: &[&str], name: &str) -> bool {
1047    let mut i = 0;
1048    while i < list.len() {
1049        if const_str_eq(list[i], name) {
1050            return true;
1051        }
1052        i += 1;
1053    }
1054    false
1055}
1056
1057/// Resolve path `segments` against a [`serde_json::Value`], for a
1058/// `#[repe(nested_serde)]` field.
1059///
1060/// Objects are indexed by key and arrays by decimal position, matching RFC 6901
1061/// evaluation; this takes already-split segments because the struct router has
1062/// them in that form and the pointer string does not exist.
1063///
1064/// `None` means the path does not resolve, which the caller reports as
1065/// [`StructError::InvalidPath`].
1066pub fn serde_pointer<'a>(value: &'a Value, segments: &[&str]) -> Option<&'a Value> {
1067    let mut cursor = value;
1068    for segment in segments {
1069        cursor = match cursor {
1070            Value::Object(map) => map.get(*segment)?,
1071            Value::Array(items) => items.get(segment.parse::<usize>().ok()?)?,
1072            _ => return None,
1073        };
1074    }
1075    Some(cursor)
1076}
1077
1078/// The mutable counterpart of [`serde_pointer`], for a write below a
1079/// `#[repe(nested_serde)]` field.
1080///
1081/// `segments` must be non-empty: replacing the whole value is the caller's own
1082/// assignment, not a walk. Every segment, the last included, has to name
1083/// something that is **already there** — a key an object does not have is
1084/// rejected rather than inserted, because the value is about to be deserialized
1085/// back into a typed field where an invented key is either dropped or an error,
1086/// and a client that misspelled one deserves to hear about it here.
1087///
1088/// Contrast [`crate::structs`]' sibling in `repe`'s registry, `set_pointer`,
1089/// which deliberately *inserts* a missing object key: that one is building a
1090/// free-form document, this one is editing a value with a type. Do not unify
1091/// them.
1092pub fn serde_pointer_set(value: &mut Value, segments: &[&str], new: Value) -> Option<()> {
1093    if segments.is_empty() {
1094        return None;
1095    }
1096    let mut cursor = value;
1097    for segment in segments {
1098        cursor = match cursor {
1099            Value::Object(map) => map.get_mut(*segment)?,
1100            Value::Array(items) => items.get_mut(segment.parse::<usize>().ok()?)?,
1101            _ => return None,
1102        };
1103    }
1104    *cursor = new;
1105    Some(())
1106}
1107
1108/// `str` equality usable in a `const` context, which `PartialEq` is not.
1109const fn const_str_eq(a: &str, b: &str) -> bool {
1110    let (a, b) = (a.as_bytes(), b.as_bytes());
1111    if a.len() != b.len() {
1112        return false;
1113    }
1114    let mut i = 0;
1115    while i < a.len() {
1116        if a[i] != b[i] {
1117            return false;
1118        }
1119        i += 1;
1120    }
1121    true
1122}
1123
1124/// Decoder for the body of a struct method taking two or more arguments.
1125///
1126/// A single-argument method takes the request body *as* the argument, which is
1127/// the shape the wire has always had. Beyond one argument the body carries the
1128/// whole list, in either of two forms:
1129///
1130/// * a JSON/BEVE **array** of exactly N values, positionally, or
1131/// * an **object** keyed by parameter name, where a missing key decodes as
1132///   `null` (so an `Option<T>` parameter may be omitted).
1133///
1134/// Generated code names this, and a hand-written [`RepeMethods`] impl that
1135/// publishes a multi-argument method should too: it is what makes such a table
1136/// accept the same two body shapes a derived one does, instead of inventing a
1137/// third that no client of a derived struct would speak. That is why it is
1138/// public and documented rather than hidden — it carries a wire contract, not
1139/// an implementation detail.
1140pub struct MethodArgs<'a> {
1141    path: &'a str,
1142    names: &'a [&'a str],
1143    values: std::vec::IntoIter<Value>,
1144    index: usize,
1145}
1146
1147impl<'a> MethodArgs<'a> {
1148    /// Split `body` into the argument list for `names`.
1149    pub fn new(path: &'a str, names: &'a [&'a str], body: Value) -> StructResult<Self> {
1150        let values = match body {
1151            Value::Array(items) => {
1152                if items.len() != names.len() {
1153                    return Err(arg_error(
1154                        path,
1155                        format!("expected {} arguments, got {}", names.len(), items.len()),
1156                    ));
1157                }
1158                items
1159            }
1160            Value::Object(mut map) => names
1161                .iter()
1162                .map(|name| map.remove(*name).unwrap_or(Value::Null))
1163                .collect(),
1164            _ => {
1165                return Err(arg_error(
1166                    path,
1167                    format!(
1168                        "expected an array of {} arguments or an object with keys [{}]",
1169                        names.len(),
1170                        names.join(", ")
1171                    ),
1172                ));
1173            }
1174        };
1175        Ok(Self {
1176            path,
1177            names,
1178            values: values.into_iter(),
1179            index: 0,
1180        })
1181    }
1182
1183    /// Decode the next argument in declaration order.
1184    pub fn next_arg<T: DeserializeOwned>(&mut self) -> StructResult<T> {
1185        let name = self.names.get(self.index).copied().unwrap_or("?");
1186        self.index += 1;
1187        let value = self.values.next().unwrap_or(Value::Null);
1188        serde_json::from_value(value).map_err(|source| StructError::Deserialize {
1189            path: format!("{path}({name})", path = self.path),
1190            source,
1191        })
1192    }
1193}
1194
1195/// A `StructError::Deserialize` carrying a message of our own rather than one
1196/// from serde, so argument-shape complaints read like every other body error.
1197fn arg_error(path: &str, message: String) -> StructError {
1198    StructError::Deserialize {
1199        path: path.to_string(),
1200        source: <serde_json::Error as serde::de::Error>::custom(message),
1201    }
1202}