thruput-sdk 0.58.0

Thruput smart-contract SDK for Rust (rv32 guest runtime and native test harness)
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
//! Making contract calls

use super::contract_result::*;
use super::encode::*;
use super::raw_call_error::*;
use crate::contract::ContractEntrypointID;
use crate::exn::{FaultInfo, FaultString, RawExceptionRef};
use crate::types::transaction::InvocationFrameStatusCode;
use crate::types::{ContractAddress, RuntimeMemoryLength};
use crate::xdr::*;
use crate::{AuthHandleBuf, sys};

/// Typed cross-contract call with caller-supplied exception dispatch.
///
/// `on_exn` receives a parsed exception borrowed from the call scratch and
/// returns the value used in [`RawCallError::Exception`]. Other outcomes do
/// not invoke it. See [`MapExceptions`](crate::MapExceptions) for the callback
/// lifetime and allocation guidance.
#[cfg_attr(not(target_arch = "riscv32"), track_caller)]
pub fn try_call_raw_with<ARGS, RET, X>(
    address: &ContractAddress,
    entrypoint: ContractEntrypointID,
    gas_limit: u64,
    args: &ARGS,
    flags: crate::invoke_config::InvokeFlagSet,
    on_exn: impl for<'s> FnOnce(RawExceptionRef<'s>) -> X,
) -> Result<RET, RawCallError<X>>
where
    ARGS: WriteXDR + crate::CollectAuthHandles,
    RET: ReadXDROwned + crate::ReceiveAuthHandles,
{
    with_call_scratch(|buf, auth_buf| {
        encode_args_into(buf, args).map_err(widen_uninhabited_exn)?;
        args.collect_auth_handles(auth_buf)
            .map_err(RawCallError::EncodingArgs)?;

        let (is_ok, returned_auth_tokens) =
            call_core(address, entrypoint, gas_limit, flags, buf, auth_buf)
                .map_err(widen_uninhabited_exn)?;

        if is_ok {
            contract_call_decode(buf.as_slice(), returned_auth_tokens)
                .map_err(widen_uninhabited_exn)
        } else {
            match RawExceptionRef::parse(buf.as_slice()) {
                Ok(exn) => Err(RawCallError::Exception(on_exn(exn))),
                Err(e) => Err(RawCallError::UnparseableAbort(
                    FaultString::from_display(e),
                )),
            }
        }
    })
}

/// CXS-encode `value` into the (cleared) scratch data buffer.
///
/// Under `alloc` the buffer grows organically to the encoding's size (no
/// fixed cap — protocol calldata is unbounded) and the grown capacity is
/// retained by the scratch for subsequent calls. Without `alloc` the
/// fixed-capacity buffer rejects encodings larger than `SCRATCH_MAX`
/// (4096) bytes.
fn encode_args_into<T: WriteXDR + ?Sized>(
    buf: &mut Buf,
    value: &T,
) -> Result<(), CallFault> {
    crate::internal::encode_scratch(buf, value)
        .map_err(|e| RawCallError::EncodingArgs(FaultString::from_display(e)))
}

/// The whole call orchestration, with no type parameters: invoke the child
/// frame, forwarding the auth tokens in `auth_buf`, and land whatever it
/// produced (return value or abort payload) in `buf`. Reports whether the
/// child returned (`true`) or aborted (`false`), and the ids its returned
/// auth tokens took in this frame.
///
/// `buf` is in-out and holds the encoded calldata on entry: the `Invoke`
/// syscall has already copied the args out by the time the child's payload
/// is fetched, so one scratch buffer serves both directions (which is why
/// this can't take the args as a separate `&[u8]`, as [`contract_call`]
/// does — that would alias the same buffer).
///
/// [`try_call_raw_with`] is generic over `(ARGS, RET, X)` and every generated
/// client instantiates it afresh, so anything left in its body is re-emitted
/// per call form — yet only arg encoding, return decoding, and the caller's
/// `on_exn` genuinely depend on those parameters. `inline(never)` keeps this
/// to one copy.
///
/// On its own that is a *net loss* (measured: +116 bytes across the contract
/// suite) — hoisting the orchestration out of the caller costs more than the
/// sharing saves. It pays (-1452) only together with the single-call-site
/// scratch checkout, which lets what remains of the closure inline into the
/// contract method. Don't judge this function in isolation.
#[inline(never)]
fn call_core(
    address: &ContractAddress,
    entrypoint: ContractEntrypointID,
    gas_limit: u64,
    flags: crate::invoke_config::InvokeFlagSet,
    buf: &mut Buf,
    auth_buf: &AuthHandleBuf,
) -> Result<(bool, core::ops::Range<u32>), CallFault> {
    let (is_ok, outputs) = invoke_frame(
        address,
        entrypoint,
        gas_limit,
        buf.as_slice(),
        auth_buf,
        flags,
    )?;

    buf.clear();

    // No `reserve` here, unlike `contract_call`: `reset_call_scratch` already
    // sized the scratch to `SCRATCH_MAX`, and `checked_returned_len` refuses a
    // payload that does not fit it. `contract_call`'s buffer is
    // caller-supplied and has no such guarantee.
    let returned_auth_tokens = fetch_frame_payload(is_ok, &outputs, buf)?;

    Ok((is_ok, returned_auth_tokens))
}

/// Pull the child frame's payload — returned value or abort bytes — out of
/// the VM into `buf`, sized per the length the `Invoke` syscall reported,
/// and return the ids the child's returned auth tokens took in this frame.
///
/// The one place that reads `CopyableInvokeOutputs`, shared by [`call_core`]
/// and [`contract_call`] (which otherwise cannot share a body: one owns its
/// scratch, the other writes into a caller's buffer). A new output field or
/// validation lands here once, for both.
#[inline]
fn fetch_frame_payload(
    is_ok: bool,
    outputs: &sys::CopyableInvokeOutputs,
    buf: &mut Buf,
) -> Result<core::ops::Range<u32>, CallFault> {
    fill_return_buf(
        outputs.return_buffer_len,
        outputs.returned_auth_token_count,
        buf,
    )
    .map_err(|fault| unparseable(is_ok, fault))
}

/// How a child frame that ran to completion ended. Produced by
/// [`contract_call`]; the payload for both variants lives in the
/// caller-provided return buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallOutcome {
    /// The child returned: `return_buf` holds the returned bytes and the
    /// auth-handle buffer the returned token ids.
    Return,
    /// The child aborted: `return_buf` holds the abort payload.
    Abort,
}

/// Untyped cross-contract call: pass pre-encoded calldata, receive the raw
/// return (or abort) bytes in `return_buf` and the returned auth-token ids
/// in `returned_auth_token_ids`. Both buffers are cleared before the call is
/// attempted, so they are left empty (not stale from a previous call) even
/// if this returns `Err`.
///
/// Prefer [`try_call_raw_with`] (or a generated client) for ordinary typed
/// calls. This entry point exists for forwarders and proxies — e.g. wallet
/// contracts that relay opaque calldata to a target and pass the raw
/// return/abort buffer back verbatim — which cannot name the argument or
/// return types. The payload lands in the caller's buffers rather than
/// being returned by value: the no-alloc buffer is `SCRATCH_MAX` bytes,
/// and a by-value return would copy it once per call layer.
///
/// The error type is `RawCallError<Infallible>`: aborts surface as
/// [`CallOutcome::Abort`] with the payload in `return_buf`, so the
/// `Exception` variant is uninhabited here — which also keeps the `Result`
/// slot small (a `RawException` payload would cost the no-alloc caller
/// a `SCRATCH_MAX`-sized stack slot for a variant this call never builds).
// The two trailing out-params are the point of the API (no by-value buffer
// returns); folding the six real inputs into a struct would be churn, not
// clarity.
#[allow(clippy::too_many_arguments)]
pub fn contract_call<A>(
    address: &ContractAddress,
    entrypoint: ContractEntrypointID,
    gas_limit: u64,
    args: &A,
    auth_token_ids: &crate::collect_auth_handles::AuthHandleBuf,
    flags: crate::invoke_config::InvokeFlagSet,
    return_buf: &mut ReturnBuf,
    returned_auth_token_ids: &mut AuthHandleBuf,
) -> Result<CallOutcome, CallFault>
where
    A: AsRef<[u8]> + ?Sized,
{
    return_buf.clear();
    returned_auth_token_ids.clear();

    let (is_ok, outputs) = invoke_frame(
        address,
        entrypoint,
        gas_limit,
        args.as_ref(),
        auth_token_ids,
        flags,
    )?;

    #[cfg(feature = "alloc")]
    return_buf.reserve(outputs.return_buffer_len as usize);

    // `fill_return_buf` sets `return_buf`'s length before its own trailing
    // auth-token check can fail, and `push_auth_handles` can fail part way.
    // Either would otherwise leave an out-buffer non-empty despite the
    // documented "cleared on Err" contract, so any failure clears both
    // before propagating. The returned ids are listed out because a
    // forwarder hands them on with `Return`, which takes a list.
    if let Err(e) =
        fetch_frame_payload(is_ok, &outputs, return_buf).and_then(|returned| {
            push_auth_handles(returned_auth_token_ids, returned)
        })
    {
        return_buf.clear();
        returned_auth_token_ids.clear();
        return Err(e);
    }

    Ok(if is_ok {
        CallOutcome::Return
    } else {
        CallOutcome::Abort
    })
}

/// Widen a `RawCallError` whose `Exception` variant is uninhabited
/// ([`core::convert::Infallible`]) to any `X`: the `Exception` arm can
/// never actually be constructed, so this just relabels the type.
pub(crate) fn widen_uninhabited_exn<X>(e: CallFault) -> RawCallError<X> {
    match e {
        RawCallError::Invalid => RawCallError::Invalid,
        RawCallError::Reentrance => RawCallError::Reentrance,
        RawCallError::DepthExceeded => RawCallError::DepthExceeded,
        RawCallError::InvokeRejected(c) => RawCallError::InvokeRejected(c),
        RawCallError::Exception(x) => match x {},
        RawCallError::Fault(f) => RawCallError::Fault(f),
        RawCallError::UnparseableReturn(f) => {
            RawCallError::UnparseableReturn(f)
        }
        RawCallError::UnparseableAbort(f) => RawCallError::UnparseableAbort(f),
        RawCallError::UnparseableAuthHandles(f) => {
            RawCallError::UnparseableAuthHandles(f)
        }
        RawCallError::EncodingArgs(f) => RawCallError::EncodingArgs(f),
    }
}

/// Map a returned-data parse fault to the error variant matching the
/// frame's outcome (success vs abort).
fn unparseable(is_ok: bool, fault: FaultString) -> CallFault {
    if is_ok {
        RawCallError::UnparseableReturn(fault)
    } else {
        RawCallError::UnparseableAbort(fault)
    }
}

/// Perform the `Invoke` syscall and interpret the frame status, returning
/// whether the child returned (vs aborted) alongside the syscall outputs
/// (which carry the sizes of the data waiting in the VM's return buffer).
fn invoke_frame(
    address: &ContractAddress,
    entrypoint: ContractEntrypointID,
    gas_limit: u64,
    args: &[u8],
    auth_token_ids: &crate::collect_auth_handles::AuthHandleBuf,
    flags: crate::invoke_config::InvokeFlagSet,
) -> Result<(bool, sys::CopyableInvokeOutputs), CallFault> {
    // Perform the cross-contract call
    let entrypoint = u64::from_be_bytes(entrypoint.into_inner());
    let auth_bytes = auth_handles_as_bytes(auth_token_ids.as_slice());
    let inputs = sys::CopyableInvokeInputs {
        entrypoint_id: entrypoint,
        gas_limit,
        flags,
        reserved: 0,
    };
    let mut outputs = sys::CopyableInvokeOutputs {
        return_buffer_len: 0,
        returned_auth_token_count: 0,
        // Placeholder; overwritten by the syscall whenever a child frame runs
        // (i.e. when `raw_Invoke` returns `Ok`). Never read on the error path.
        frame_status: InvocationFrameStatusCode::Fault,
    };
    let result = {
        // The callee has its own memory on a real guest, so the caller's
        // live guards must not leak into the callee's terminal-return
        // check. Restored when the scope ends, including on unwind.
        let _reset = crate::storage::live_guards::FrameGuardReset::new();
        sys::raw_Invoke(address, args, auth_bytes, &inputs, &mut outputs)
    };

    let is_ok = match result {
        // A child frame ran; its outcome is reported in `frame_status`.
        Ok(()) => {
            let status = outputs.frame_status;
            if status == InvocationFrameStatusCode::Return {
                true
            } else if status == InvocationFrameStatusCode::Abort {
                false
            } else {
                // A child frame ran and produced neither a return nor an
                // abort buffer: it faulted (panic, trap, or out of gas). An
                // out-of-range status would mean the host broke the syscall
                // contract; it lands here too, which is the safe reading —
                // the frame did not return a result either way.
                //
                // Empty because nothing on this path has a message to give:
                // the frame status is all the runtime reports, and the
                // callee's own panic was caught inside the runtime's frame.
                // The harness records a message only for a frame it ran
                // itself — see `into_root_call_result`.
                return Err(RawCallError::Fault(FaultInfo::empty()));
            }
        }
        // The call was rejected before any child frame ran. Each documented
        // rejection keeps its own identity: folding reentrance or the depth
        // bound into a fault would tell the caller its callee misbehaved,
        // when in fact the callee never ran.
        Err(syserr) => return Err(classify_invoke_rejection(syserr)),
    };

    // No cap here: `checked_returned_len` bounds the length against the
    // receiving buffer, and a chain's limit is configuration, not a constant.
    Ok((is_ok, outputs))
}

/// Append the returned auth token ids to the auth-handle list.
fn push_auth_handles(
    buf: &mut AuthHandleBuf,
    ids: core::ops::Range<u32>,
) -> Result<(), CallFault> {
    #[cfg(feature = "alloc")]
    {
        buf.extend(ids);
        Ok(())
    }
    #[cfg(not(feature = "alloc"))]
    {
        for id in ids {
            buf.push(id).map_err(|_| {
                RawCallError::UnparseableAuthHandles(
                    FaultString::from_display(
                        "auth handle buffer capacity exceeded",
                    ),
                )
            })?;
        }
        Ok(())
    }
}

#[cfg(feature = "alloc")]
use crate::cell::{ContractLocalRef, ContractRefCell};

/// The per-instance call scratch: the shared write buffer and the
/// auth-handle list.
struct CallScratch {
    buf: Buf,
    auth: AuthHandleBuf,
}

/// Run `f` with a call scratch (encoded-args / returned-data, and the
/// auth-token-id list).
///
/// The scratch is the SDK's write buffer: cross-contract calls, event
/// emission, storage writes, and terminal returns all encode through it
/// (calldata is the one separate buffer, since decoded args borrow from it for
/// the whole frame). Scratch uses nest — an exception thrown mid-encode
/// re-enters to encode the abort, and the native mock runs child frames
/// in-process — so each use needs its own buffer, not a shared one.
///
/// No-alloc: that buffer is just a local. `Buf` is a `MaybeUninit` array, so
/// constructing one costs a length store and no `memset`; there is nothing to
/// cache and nothing a static would save. Nesting is then correct by
/// construction — no cell, no borrow flag, no re-entrancy fallback.
#[cfg(not(feature = "alloc"))]
fn with_call_scratch<R>(
    f: impl FnOnce(&mut Buf, &mut AuthHandleBuf) -> R,
) -> R {
    let mut scratch = fresh_call_scratch();
    f(&mut scratch.buf, &mut scratch.auth)
}

/// Run `f` with a call scratch. See the no-alloc twin for what the scratch is.
///
/// Under `alloc` a local would mean a fresh `Vec` allocation per use, and the
/// guest bump allocator never frees — so buffers are pooled instead and their
/// capacity reused. A use *takes* its buffer out of the pool for the duration
/// (the pool's `RefCell` is never held while `f` runs), so a nested use simply
/// takes the next one, and the buffers come back on the way out. Moving a
/// `CallScratch` here moves two `Vec` headers, not their contents.
///
/// A `f` that never returns (a terminal return, an abort) drops its buffer
/// rather than returning it to the pool. That is fine: the frame is over.
#[cfg(feature = "alloc")]
fn with_call_scratch<R>(
    f: impl FnOnce(&mut Buf, &mut AuthHandleBuf) -> R,
) -> R {
    let mut scratch = SCRATCH_POOL
        .with_ref(|pool| pool.borrow_mut().pop())
        .unwrap_or_else(fresh_call_scratch);

    reset_call_scratch(&mut scratch);
    let out = f(&mut scratch.buf, &mut scratch.auth);

    SCRATCH_POOL.with_ref(|pool| pool.borrow_mut().push(scratch));
    out
}

#[cfg(feature = "alloc")]
crate::contract_local! {
    static SCRATCH_POOL: ContractRefCell<alloc::vec::Vec<CallScratch>> =
        const { ContractRefCell::new(alloc::vec::Vec::new()) };
}

/// Ready a pooled scratch for a fresh use: cleared, and grown to `SCRATCH_MAX`
/// once so in-bounds payloads never reallocate.
#[cfg(feature = "alloc")]
#[inline]
fn reset_call_scratch(scratch: &mut CallScratch) {
    scratch.buf.clear();
    scratch.auth.clear();
    if scratch.buf.capacity() < crate::internal::SCRATCH_MAX {
        scratch.buf.reserve(crate::internal::SCRATCH_MAX);
    }
}

fn fresh_call_scratch() -> CallScratch {
    CallScratch {
        buf: crate::internal::new_scratch(),
        auth: AuthHandleBuf::new(),
    }
}

/// Run `f` with just the data scratch buffer. For encode-then-syscall sites
/// (events, storage values, terminal returns) that don't touch the auth-handle
/// list.
pub(crate) fn with_scratch<R>(f: impl FnOnce(&mut Buf) -> R) -> R {
    with_call_scratch(|buf, _auth| f(buf))
}

#[cfg(all(test, not(target_arch = "riscv32"), feature = "std"))]
mod scratch_tests {
    use super::*;

    /// A nested scratch use — a throw while the outer scratch is mid-encode,
    /// or the native mock's in-process child frames — must get its *own*
    /// buffer, or the inner encode would scribble over the outer one. Under
    /// `alloc` that means the pool hands out a second buffer rather than
    /// re-lending the first.
    #[test]
    fn nested_scratch_uses_get_distinct_buffers() {
        with_scratch(|outer| {
            outer.clear();
            outer.extend_from_slice(&[0xAA; 8]);
            let outer_ptr = outer.as_slice().as_ptr();

            let inner_ptr = with_scratch(|inner| {
                inner.clear();
                inner.extend_from_slice(&[0xBB; 8]);
                inner.as_slice().as_ptr()
            });

            assert_ne!(
                outer_ptr, inner_ptr,
                "nested scratch use aliased the outer buffer"
            );
            // The outer buffer survived the nested use untouched.
            assert_eq!(outer.as_slice(), &[0xAA; 8]);
        });
    }

    /// Buffers return to the pool, so sequential uses reuse one rather than
    /// allocating per call (the guest bump allocator never frees).
    #[test]
    #[cfg(feature = "alloc")]
    fn sequential_scratch_uses_reuse_one_buffer() {
        let first = with_scratch(|b| {
            b.reserve(crate::internal::SCRATCH_MAX);
            b.as_slice().as_ptr()
        });
        let second = with_scratch(|b| b.as_slice().as_ptr());
        assert_eq!(
            first, second,
            "scratch buffer was not returned to the pool"
        );
    }
}

#[inline]
fn fill_return_buf(
    return_len: u32,
    returned_auth_token_count: u32,
    return_buf: &mut ReturnBuf,
) -> Result<core::ops::Range<u32>, FaultString> {
    let mut written_mu: core::mem::MaybeUninit<RuntimeMemoryLength> =
        core::mem::MaybeUninit::uninit();
    let mut start_mu: core::mem::MaybeUninit<u32> =
        core::mem::MaybeUninit::uninit();
    let mut count_mu: core::mem::MaybeUninit<u32> =
        core::mem::MaybeUninit::uninit();

    sys::uninit_GetReturnedBuffer(
        return_buf.spare_capacity_mut(),
        &mut written_mu,
        &mut start_mu,
        &mut count_mu,
    )
    .map_err(|syserr| FaultString::from_display(format_args!("{syserr:?}")))?;

    let written = unsafe { written_mu.assume_init() };

    let written =
        checked_returned_len(written, return_len, return_buf.capacity())?;

    // Safety: `checked_returned_len` proved `written <= capacity`, so `set_len`
    // stays within the allocation. That the host actually initialized those
    // `written` bytes is trusted from the `GetReturnedBuffer` syscall contract,
    // not proven here; if the host under-fills, bytes in `[actual, written)`
    // would be read as valid data.
    unsafe {
        return_buf.set_len(written);
    }

    returned_auth_token_range(
        unsafe { start_mu.assume_init() },
        unsafe { count_mu.assume_init() },
        returned_auth_token_count,
    )
}

/// Validate the length the host reports for a returned buffer before it is used
/// as the buffer's logical length.
///
/// `GetReturnedBuffer` copies at most `capacity` bytes into the destination
/// span but reports the *full* source length, which can exceed `capacity` when
/// a child returns a buffer larger than this fixed-size [`ReturnBuf`]. Treating
/// that reported length as the number of initialized bytes would push the
/// buffer's logical length past its capacity, so it is rejected as a parse
/// error here before any `set_len`.
fn checked_returned_len(
    written: RuntimeMemoryLength,
    return_len: u32,
    capacity: usize,
) -> Result<usize, FaultString> {
    if written != return_len {
        return Err(FaultString::from_display(format_args!(
            "unexpected return-data length from system call: \
                    written = {written}, \
                    return_len = {return_len}"
        )));
    }

    let written = written as usize;
    if written > capacity {
        return Err(FaultString::from_display(format_args!(
            "return-data length {written} exceeds return buffer \
                    capacity {capacity}"
        )));
    }

    Ok(written)
}

/// The ids the child's returned auth tokens took in this frame: `count`
/// consecutive ids from `start`. The count must match the one `Invoke`
/// reported and the range must fit in a `u32`; otherwise the host broke the
/// syscall contract.
fn returned_auth_token_range(
    start: u32,
    count: u32,
    invoke_count: u32,
) -> Result<core::ops::Range<u32>, FaultString> {
    if count != invoke_count {
        return Err(FaultString::from_display(format_args!(
            "unexpected returned auth token count from system call: \
                    GetReturnedBuffer = {count}, Invoke = {invoke_count}"
        )));
    }
    let end = start.checked_add(count).ok_or_else(|| {
        FaultString::from_display(format_args!(
            "returned auth token ids overflow: start = {start}, \
                    count = {count}"
        ))
    })?;
    Ok(start..end)
}

#[cfg(test)]
mod tests {
    use super::checked_returned_len;

    const CAPACITY: usize = 500;

    #[test]
    fn oversized_return_len_is_rejected() {
        // A child can return up to the protocol's 1024-byte cap. When it returns
        // 600 bytes, both `Invoke` and `GetReturnedBuffer` report 600 even though
        // only `CAPACITY` bytes fit in the destination span. Accepting 600 as the
        // logical length would push `ReturnBuf` past its capacity, so it must be
        // rejected.
        assert!(checked_returned_len(600, 600, CAPACITY).is_err());
    }

    #[test]
    fn return_len_at_capacity_is_accepted() {
        assert_eq!(
            checked_returned_len(CAPACITY as u32, CAPACITY as u32, CAPACITY)
                .unwrap(),
            CAPACITY
        );
    }

    #[test]
    fn return_len_within_capacity_is_accepted() {
        assert_eq!(checked_returned_len(480, 480, CAPACITY).unwrap(), 480);
    }

    #[test]
    fn empty_return_is_accepted() {
        assert_eq!(checked_returned_len(0, 0, CAPACITY).unwrap(), 0);
    }

    #[test]
    fn mismatched_written_and_return_len_is_rejected() {
        assert!(checked_returned_len(400, 500, CAPACITY).is_err());
    }
}