repe 9.0.0

Rust implementation of the REPE RPC protocol (JSON-focused)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
use crate::constants::{BodyFormat, ErrorCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
/// Errors produced while handling struct-backed endpoints.
#[derive(Debug, thiserror::Error)]
pub enum StructError {
    #[error("invalid path `{path}`")]
    InvalidPath { path: String },
    #[error("unexpected additional path segments at `{path}`")]
    InvalidSubpath { path: String },
    #[error("body required for `{path}`")]
    BodyExpected { path: String },
    #[error("body not allowed for `{path}`")]
    BodyUnexpected { path: String },
    #[error("serialization error for `{path}`: {source}")]
    Serialize {
        path: String,
        #[source]
        source: serde_json::Error,
    },
    #[error("deserialization error for `{path}`: {source}")]
    Deserialize {
        path: String,
        #[source]
        source: serde_json::Error,
    },
    #[error("method `{path}` failed: {message}")]
    Execution { path: String, message: String },
}

impl StructError {
    pub fn code(&self) -> ErrorCode {
        match self {
            StructError::InvalidPath { .. } | StructError::InvalidSubpath { .. } => {
                ErrorCode::MethodNotFound
            }
            StructError::BodyExpected { .. } | StructError::BodyUnexpected { .. } => {
                ErrorCode::InvalidBody
            }
            StructError::Serialize { .. } | StructError::Deserialize { .. } => {
                ErrorCode::InvalidBody
            }
            StructError::Execution { .. } => ErrorCode::ParseError,
        }
    }
}

/// Convenience alias for results returned by struct handlers.
pub type StructResult<T> = Result<T, StructError>;

/// Trait implemented by structs that can be exposed directly through the REPE router.
///
/// The implementation should interpret the provided JSON Pointer path segments and
/// either return a JSON value (for reads) or mutate the struct (for writes).
pub trait RepeStruct: Send + Sync {
    /// Handle a read or write against this struct.
    ///
    /// * `segments` – JSON Pointer path split into unescaped segments.
    /// * `body` – `Some(value)` when the request contains a JSON body, `None` for reads.
    ///
    /// Return `Ok(Some(value))` to send a JSON response payload, `Ok(None)` to send `null`.
    fn repe_handle(
        &mut self,
        segments: &[&str],
        body: Option<Value>,
    ) -> StructResult<Option<Value>>;

    /// Encode-in-place counterpart of [`repe_handle`](Self::repe_handle): write the
    /// response body straight into `out` instead of returning an owned
    /// [`serde_json::Value`] for the caller to re-serialize.
    ///
    /// This is the method the router calls. The default implementation delegates
    /// to [`repe_handle`](Self::repe_handle) and encodes whatever it returns, so a
    /// hand-written impl only needs `repe_handle`; `#[derive(RepeStruct)]`
    /// overrides it so a leaf read serializes the live field directly into the
    /// outgoing frame buffer with no intermediate `Value`.
    ///
    /// Writes are unaffected — a request body still arrives as a `Value`.
    ///
    /// [`repe_handle`]: Self::repe_handle
    fn repe_handle_into(
        &mut self,
        segments: &[&str],
        body: Option<Value>,
        out: &mut ResponseBody<'_>,
    ) -> StructResult<()> {
        let value = self.repe_handle(segments, body)?;
        write_optional(out, segments, value)
    }

    /// Serve a **read** through a shared borrow, or decline it.
    ///
    /// A read is a request with no body — REPE separates the two at the frame
    /// level — so there is no `body` parameter here and no state to change. The
    /// router tries this first for every bodiless request against a struct
    /// registered behind a lock that has a shared mode, which is what keeps a
    /// `/version` read from queueing behind a half-second method call on the
    /// same object.
    ///
    /// Return `None` for any path this borrow cannot serve: a write-shaped
    /// endpoint, a `&mut self` method, a nested field whose child declined. The
    /// router then retakes the lock exclusively and dispatches through
    /// [`repe_handle_into`](Self::repe_handle_into), so declining costs
    /// correctness nothing — it is the default, and a hand-written impl that
    /// never overrides this behaves exactly as it did before the path existed.
    ///
    /// Two obligations come with overriding it:
    ///
    /// * **Answer identically.** Whatever this returns for a path is what the
    ///   client sees; the exclusive path is not consulted afterwards. Decline
    ///   rather than approximate.
    /// * **Write nothing when declining.** A `None` return must leave `out` as
    ///   it was found, so the exclusive attempt starts from an empty body.
    ///   [`ObjectBody::entry_try_with`] exists to make that mechanical when the
    ///   decline surfaces partway through an object: it rewinds the whole
    ///   object, so propagating its `None` is all a caller has to do.
    ///
    /// A derived impl serves a listing only when nothing in it has to be
    /// *invoked* — a struct with a field-shaped endpoint declines the whole
    /// listing up front — because a decline discovered later would leave the
    /// entries before it run twice, once here and once on the exclusive retry.
    /// A hand-written impl that invokes anything before it can decide owes the
    /// same care.
    fn repe_read_into(
        &self,
        segments: &[&str],
        out: &mut ResponseBody<'_>,
    ) -> Option<StructResult<()>> {
        let _ = (segments, out);
        None
    }
}

/// Method table for a struct whose methods are declared with `#[repe::methods]`
/// on an inherent `impl` block.
///
/// Generated by the attribute macro, which sees every signature in the block and
/// so cannot fall behind the type the way a hand-maintained
/// `#[repe(methods(..))]` list can. `#[derive(RepeStruct)]` dispatches path
/// segments that match no field through this table when the struct carries the
/// `#[repe(methods)]` marker.
///
/// Implementing this by hand is supported but unusual; the macro exists so the
/// signatures stay derived from the `impl` block.
#[diagnostic::on_unimplemented(
    message = "`{Self}` declares `#[repe(methods)]` but has no `#[repe::methods]` impl block",
    label = "no method table for `{Self}`",
    note = "annotate the inherent `impl {Self}` block with `#[repe::methods]`, or drop `#[repe(methods)]` from the struct"
)]
pub trait RepeMethods: MethodsDeclared {
    /// `(endpoint, signature)` pairs published in the whole-struct listing.
    const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)];

    /// Endpoints in this table that are **field-shaped**: served by a
    /// getter/setter pair (`#[repe(get = "...")]` / `#[repe(set = "...")]`)
    /// rather than by an argument list.
    ///
    /// They are deliberately absent from
    /// [`REPE_METHOD_SIGNATURES`](Self::REPE_METHOD_SIGNATURES), because they
    /// have no signature to publish: a client reads and writes one the way it
    /// reads and writes a field, so the whole-struct listing shows each one's
    /// current value rather than a signature string. The derived listing reads
    /// those values back through [`repe_call`](Self::repe_call), or through
    /// [`repe_call_read_into`](Self::repe_call_read_into) when it is being
    /// served under a shared borrow.
    ///
    /// Defaults to empty, so a hand-written impl need not mention it. One
    /// invariant comes with listing a name here, and the derived listing relies
    /// on it: [`repe_call`](Self::repe_call) must answer
    /// `segments = &[name], body = None` with `Ok(Some(value))`. A name the
    /// table cannot dispatch turns every whole-struct read into that name's
    /// error. `#[repe::methods]` upholds it by construction, because it emits
    /// this list from the getters it generated arms for. The shared-borrow
    /// listing asks the same question of `repe_call_read_into`, where a `None`
    /// is not a failure — it declines the whole listing to the exclusive path.
    const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] = &[];

    /// Invoke the method named by `segments[0]`.
    ///
    /// `segments` is the remaining path relative to the struct root, so error
    /// paths match the ones [`RepeStruct::repe_handle`] produces for fields.
    /// Returns [`StructError::InvalidPath`] when no method matches.
    fn repe_call(&mut self, segments: &[&str], body: Option<Value>) -> StructResult<Option<Value>>;

    /// Encode-in-place counterpart of [`repe_call`](Self::repe_call), mirroring
    /// [`RepeStruct::repe_handle_into`].
    fn repe_call_into(
        &mut self,
        segments: &[&str],
        body: Option<Value>,
        out: &mut ResponseBody<'_>,
    ) -> StructResult<()> {
        let value = self.repe_call(segments, body)?;
        write_optional(out, segments, value)
    }

    /// Shared-borrow counterpart of [`repe_call_into`](Self::repe_call_into),
    /// mirroring [`RepeStruct::repe_read_into`] and carrying the same two
    /// obligations: answer identically, or decline without writing.
    ///
    /// `#[repe::methods]` serves a `&self` method taking no arguments and the
    /// getter half of a `&self` accessor here, and declines everything else.
    fn repe_call_read_into(
        &self,
        segments: &[&str],
        out: &mut ResponseBody<'_>,
    ) -> Option<StructResult<()>> {
        let _ = (segments, out);
        None
    }
}

/// Marker emitted by `#[derive(RepeStruct)]` when the struct carries the
/// `#[repe(methods)]` attribute.
///
/// A derive macro cannot see `impl` blocks, so the two halves of the
/// `#[repe::methods]` surface are tied together by a compile-time handshake.
/// This marker is a supertrait of [`RepeMethods`], so the table the attribute
/// macro generates simply cannot be implemented for a struct that did not
/// declare it — no assertion to emit, and none to forget. Missing either half is
/// a compile error naming the attribute that is absent, rather than a method
/// that quietly never reaches the wire.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has a `#[repe::methods]` impl block but does not declare it",
    label = "`{Self}` is missing `#[repe(methods)]`",
    note = "add `#[repe(methods)]` next to `#[derive(RepeStruct)]` on `{Self}` so the derived router dispatches to the impl block"
)]
pub trait MethodsDeclared {}

/// Build a fully-qualified child path from the current path segments.
pub fn join_path(current: &[&str], segment: &str) -> String {
    if current.is_empty() {
        format!("/{}", segment)
    } else {
        let mut s = String::new();
        for part in current {
            s.push('/');
            s.push_str(part);
        }
        s.push('/');
        s.push_str(segment);
        s
    }
}

/// Build a path string from segments for error messages.
pub fn path_from_segments(segments: &[&str]) -> String {
    if segments.is_empty() {
        String::from("")
    } else {
        let mut s = String::new();
        for segment in segments {
            s.push('/');
            s.push_str(segment);
        }
        s
    }
}

/// Prefix error paths with an additional segment when bubbling errors from nested structs.
pub fn prepend_path(mut err: StructError, prefix: &str) -> StructError {
    let with_prefix = |path: String| {
        if prefix.is_empty() {
            path
        } else if path.is_empty() {
            format!("/{}", prefix)
        } else if path.starts_with('/') {
            format!("/{prefix}{path}")
        } else {
            format!("/{prefix}/{path}")
        }
    };

    match &mut err {
        StructError::InvalidPath { path }
        | StructError::InvalidSubpath { path }
        | StructError::BodyExpected { path }
        | StructError::BodyUnexpected { path }
        | StructError::Serialize { path, .. }
        | StructError::Deserialize { path, .. }
        | StructError::Execution { path, .. } => {
            *path = with_prefix(std::mem::take(path));
        }
    }
    err
}

/// Response body under construction for a [`RepeStruct`] read.
///
/// Handed to [`RepeStruct::repe_handle_into`] so a read serializes the live field
/// straight into the outgoing frame buffer. The alternative — returning a
/// [`serde_json::Value`] that the router then re-serializes — allocates an
/// intermediate tree per read, which is what a client polling a wide object at
/// kilohertz pays for.
///
/// The body starts out empty and [`BodyFormat::Json`]; the write that fills it
/// also settles the format, so a [`write_typed_slice`](Self::write_typed_slice)
/// body reports [`BodyFormat::Beve`]. Exactly one top-level write is expected —
/// a value, a null, or an [`object`](Self::object).
///
/// Any failed write — including one that fails partway through an
/// [`object`](Self::object) — rewinds the buffer to where that write began, so a
/// caller that recovers from a [`StructError`] never ships half-serialized
/// bytes.
pub struct ResponseBody<'a> {
    buf: &'a mut Vec<u8>,
    format: BodyFormat,
    /// True while this body is a value *inside* an enclosing JSON object, where
    /// the frame format is already committed to JSON.
    ///
    /// Reached from generated code by exactly one path: the whole-struct listing
    /// writes each accessor endpoint's value through
    /// [`ObjectBody::entry_with`] or [`ObjectBody::entry_try_with`], so a
    /// `#[repe(typed)]` getter listed inside the object emits a JSON array
    /// rather than switching the enclosing frame to BEVE. (A `#[repe(nested)]`
    /// field also gets a nested body, but its child is always entered with empty
    /// segments and so always takes its own object branch.) The flag also covers
    /// hand-written `repe_handle_into` impls, which can call anything from
    /// anywhere; a JSON-array fallback beats corrupting the frame.
    nested: bool,
}

impl<'a> ResponseBody<'a> {
    /// Wrap an output buffer. `buf` is normally empty; writes append to it.
    pub fn new(buf: &'a mut Vec<u8>) -> Self {
        Self {
            buf,
            format: BodyFormat::Json,
            nested: false,
        }
    }

    /// The body format settled by the write that filled this body.
    pub fn format(&self) -> BodyFormat {
        self.format
    }

    /// Serialize `value` as the whole body, as JSON.
    ///
    /// `path` names the field for the error message and is only read when
    /// serialization fails.
    pub fn write<T>(&mut self, path: &str, value: &T) -> StructResult<()>
    where
        T: Serialize + ?Sized,
    {
        self.write_with_path(|| String::from(path), value)
    }

    /// [`write`](Self::write) with the error path built only if one is needed.
    ///
    /// The derived arms pass a `&'static str` literal and pay nothing either
    /// way, but the [`RepeStruct::repe_handle_into`] default has to *assemble*
    /// its path from the segments — on every successful read, for a string it
    /// then throws away.
    fn write_with_path<T, F>(&mut self, path: F, value: &T) -> StructResult<()>
    where
        T: Serialize + ?Sized,
        F: FnOnce() -> String,
    {
        let start = self.buf.len();
        match serde_json::to_writer(&mut *self.buf, value) {
            Ok(()) => Ok(()),
            Err(source) => {
                self.buf.truncate(start);
                Err(StructError::Serialize {
                    path: path(),
                    source,
                })
            }
        }
    }

    /// Write a JSON `null` body — the response to a write, or to a read that has
    /// nothing to return.
    pub fn write_null(&mut self) {
        self.buf.extend_from_slice(b"null");
    }

    /// Write `slice` as a BEVE typed numeric array and set the body format to
    /// [`BodyFormat::Beve`].
    ///
    /// The bulk encode behind
    /// [`MessageBuilder::body_typed_slice`](crate::message::MessageBuilder::body_typed_slice):
    /// one `copy_nonoverlapping` on little-endian targets rather than a
    /// per-element serde walk, and byte-identical to what Glaze emits for the
    /// same array. This is what `#[repe(typed)]` routes a numeric field to.
    ///
    /// Inside an enclosing object — the whole-struct listing — the frame is
    /// already committed to JSON, so the slice is written as a JSON array
    /// instead. A field only reaches the typed encoding when it is read on its
    /// own.
    pub fn write_typed_slice<T>(&mut self, path: &str, slice: &[T]) -> StructResult<()>
    where
        T: beve::BeveTypedSlice + Serialize,
    {
        if self.nested {
            return self.write(path, slice);
        }
        let encoded_len = beve::typed_slice_size(slice) as usize;
        self.buf.reserve(encoded_len);
        let start = self.buf.len();
        beve::to_writer_typed_slice(&mut *self.buf, slice)
            .expect("writing a typed slice into a Vec is infallible");
        debug_assert_eq!(self.buf.len() - start, encoded_len);
        self.format = BodyFormat::Beve;
        Ok(())
    }

    /// Begin a JSON object body, written key by key.
    ///
    /// Used by the whole-struct listing so a wide object is emitted in one pass
    /// instead of through a [`serde_json::Map`].
    pub fn object(&mut self) -> ObjectBody<'_> {
        let start = self.buf.len();
        self.buf.push(b'{');
        ObjectBody {
            buf: self.buf,
            start,
            first: true,
        }
    }
}

/// A JSON object body being written key by key. Created by
/// [`ResponseBody::object`]; call [`finish`](Self::finish) to close it.
///
/// An entry that fails — or that [`entry_try_with`](Self::entry_try_with)
/// declines — rewinds the buffer past the opening brace, so a partly written
/// object is never left behind for a caller that recovers from it. Dropping
/// without calling [`finish`](Self::finish) is the same situation and leaves
/// nothing behind either, since both ways out without finishing have already
/// rewound.
pub struct ObjectBody<'a> {
    buf: &'a mut Vec<u8>,
    /// Buffer length before the opening brace, to rewind to on failure.
    start: usize,
    first: bool,
}

impl ObjectBody<'_> {
    fn key(&mut self, key: &str) -> StructResult<()> {
        if self.first {
            self.first = false;
        } else {
            self.buf.push(b',');
        }
        serde_json::to_writer(&mut *self.buf, key).map_err(|source| StructError::Serialize {
            path: format!("/{key}"),
            source,
        })?;
        self.buf.push(b':');
        Ok(())
    }

    /// Run one entry, rewinding the whole object if it fails.
    fn entry_with_rewind<F>(&mut self, f: F) -> StructResult<()>
    where
        F: FnOnce(&mut Self) -> StructResult<()>,
    {
        match f(self) {
            Ok(()) => Ok(()),
            Err(err) => {
                self.buf.truncate(self.start);
                Err(err)
            }
        }
    }

    /// Write one `"key": value` entry.
    pub fn entry<T>(&mut self, key: &str, value: &T) -> StructResult<()>
    where
        T: Serialize + ?Sized,
    {
        self.entry_with_rewind(|this| {
            this.key(key)?;
            serde_json::to_writer(&mut *this.buf, value).map_err(|source| StructError::Serialize {
                path: format!("/{key}"),
                source,
            })
        })
    }

    /// Write one `"key": <value>` entry whose value is produced by `f`, for a
    /// nested [`RepeStruct`] that fills the body itself.
    ///
    /// The body handed to `f` is marked as nested: the enclosing frame is
    /// already JSON, so a [`ResponseBody::write_typed_slice`] inside it falls
    /// back to a JSON array rather than switching the frame to BEVE.
    pub fn entry_with<F>(&mut self, key: &str, f: F) -> StructResult<()>
    where
        F: FnOnce(&mut ResponseBody<'_>) -> StructResult<()>,
    {
        self.entry_with_rewind(|this| {
            this.key(key)?;
            let mut body = ResponseBody {
                buf: this.buf,
                format: BodyFormat::Json,
                nested: true,
            };
            f(&mut body)
        })
    }

    /// [`entry_with`](Self::entry_with) for a value the source may decline to
    /// produce, as [`RepeStruct::repe_read_into`] declines a path that needs
    /// exclusive access.
    ///
    /// `None` rewinds the whole object, exactly as an `Err` does, so a caller
    /// that declines in turn leaves the buffer as it found it without a second
    /// step. Dropping the object without calling [`finish`](Self::finish) then
    /// leaves nothing behind, because the only ways out without finishing are
    /// an error and a decline, and both have already rewound.
    pub fn entry_try_with<F>(&mut self, key: &str, f: F) -> Option<StructResult<()>>
    where
        F: FnOnce(&mut ResponseBody<'_>) -> Option<StructResult<()>>,
    {
        let outcome = match self.key(key) {
            Ok(()) => {
                let mut body = ResponseBody {
                    buf: self.buf,
                    format: BodyFormat::Json,
                    nested: true,
                };
                f(&mut body)
            }
            Err(err) => Some(Err(err)),
        };
        if !matches!(outcome, Some(Ok(()))) {
            self.buf.truncate(self.start);
        }
        outcome
    }

    /// Close the object.
    pub fn finish(self) {
        self.buf.push(b'}');
    }
}

/// Write the `Option<Value>` a [`RepeStruct::repe_handle`] returned as the whole
/// body: the payload, or `null` when there is nothing to send.
///
/// Shared by the [`RepeStruct::repe_handle_into`] and
/// [`RepeMethods::repe_call_into`] defaults, which differ only in which method
/// they delegate to.
fn write_optional(
    out: &mut ResponseBody<'_>,
    segments: &[&str],
    value: Option<Value>,
) -> StructResult<()> {
    match value {
        Some(value) => out.write_with_path(|| path_from_segments(segments), &value),
        None => {
            out.write_null();
            Ok(())
        }
    }
}

/// Compile-time check that the three sets of endpoints on one struct do not
/// overlap.
///
/// The two macros cannot see each other's input, so the derive emits a call to
/// this against everything *it* publishes — fields, plus any method named in a
/// struct-level `#[repe(methods(..))]` list — and the two generated
/// [`RepeMethods`] tables. Without it a collision is silent and costly: one
/// declaration wins dispatch, the other becomes permanently unreachable, and
/// the whole-struct listing emits the same key twice. The two listings do not
/// even agree on that last part, since a `serde_json::Map` deduplicates the key
/// and the streaming encoder does not.
///
/// Collisions the macros *can* see on their own — two fields, two listed
/// methods, a field against a listed method, two endpoints in one
/// `#[repe::methods]` block — are rejected at macro time with a message naming
/// the endpoint and pointing at the second declaration.
///
/// The third pairing, methods against accessors, is unreachable from a
/// generated table for the same reason; it is checked because a hand-written
/// [`RepeMethods`] impl can produce it.
pub const fn assert_no_endpoint_collision(
    declared: &[&str],
    methods: &[(&str, &str)],
    accessors: &[&str],
) {
    let mut i = 0;
    while i < methods.len() {
        let mut j = 0;
        while j < declared.len() {
            if const_str_eq(methods[i].0, declared[j]) {
                panic!(
                    "a `#[repe::methods]` method and an endpoint declared on the struct itself \
                     share a name: the struct's declaration wins dispatch and the method could \
                     never be called. Rename one with `#[repe(rename = \"...\")]`."
                );
            }
            j += 1;
        }
        i += 1;
    }

    let mut i = 0;
    while i < accessors.len() {
        let mut j = 0;
        while j < declared.len() {
            if const_str_eq(accessors[i], declared[j]) {
                panic!(
                    "a `#[repe(get = \"...\")]` accessor and an endpoint declared on the struct \
                     itself share a name: the struct's declaration wins dispatch and the accessor \
                     could never be called. Rename the struct's with \
                     `#[repe(rename = \"...\")]`, or give the accessor a different endpoint."
                );
            }
            j += 1;
        }

        let mut j = 0;
        while j < methods.len() {
            if const_str_eq(accessors[i], methods[j].0) {
                panic!(
                    "a `#[repe::methods]` method and a `#[repe(get = \"...\")]` accessor in the \
                     same table share an endpoint name: one of them is unreachable, and the \
                     whole-struct listing would show the endpoint twice."
                );
            }
            j += 1;
        }
        i += 1;
    }
}

/// `str` equality usable in a `const` context, which `PartialEq` is not.
const fn const_str_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

/// Decoder for the body of a struct method taking two or more arguments.
///
/// A single-argument method takes the request body *as* the argument, which is
/// the shape the wire has always had. Beyond one argument the body carries the
/// whole list, in either of two forms:
///
/// * a JSON/BEVE **array** of exactly N values, positionally, or
/// * an **object** keyed by parameter name, where a missing key decodes as
///   `null` (so an `Option<T>` parameter may be omitted).
///
/// Generated by `#[repe::methods]` and by `#[repe(methods(..))]`; public because
/// the generated code names it, not because it is expected to be called by hand.
pub struct MethodArgs<'a> {
    path: &'a str,
    names: &'a [&'a str],
    values: std::vec::IntoIter<Value>,
    index: usize,
}

impl<'a> MethodArgs<'a> {
    /// Split `body` into the argument list for `names`.
    pub fn new(path: &'a str, names: &'a [&'a str], body: Value) -> StructResult<Self> {
        let values = match body {
            Value::Array(items) => {
                if items.len() != names.len() {
                    return Err(arg_error(
                        path,
                        format!("expected {} arguments, got {}", names.len(), items.len()),
                    ));
                }
                items
            }
            Value::Object(mut map) => names
                .iter()
                .map(|name| map.remove(*name).unwrap_or(Value::Null))
                .collect(),
            _ => {
                return Err(arg_error(
                    path,
                    format!(
                        "expected an array of {} arguments or an object with keys [{}]",
                        names.len(),
                        names.join(", ")
                    ),
                ));
            }
        };
        Ok(Self {
            path,
            names,
            values: values.into_iter(),
            index: 0,
        })
    }

    /// Decode the next argument in declaration order.
    pub fn next_arg<T: DeserializeOwned>(&mut self) -> StructResult<T> {
        let name = self.names.get(self.index).copied().unwrap_or("?");
        self.index += 1;
        let value = self.values.next().unwrap_or(Value::Null);
        serde_json::from_value(value).map_err(|source| StructError::Deserialize {
            path: format!("{path}({name})", path = self.path),
            source,
        })
    }
}

/// A `StructError::Deserialize` carrying a message of our own rather than one
/// from serde, so argument-shape complaints read like every other body error.
fn arg_error(path: &str, message: String) -> StructError {
    StructError::Deserialize {
        path: path.to_string(),
        source: <serde_json::Error as serde::de::Error>::custom(message),
    }
}