Skip to main content

ic_wire/
evolution.rs

1//! Sparse extension fields, open variants and bounded message projections.
2//!
3//! The sparse `Wire` projection stages and projects typed extension records and
4//! tuples through supported containers. Applications can also project open
5//! cases and recovery envelopes explicitly. Projected calls share Wire's
6//! admission across the complete Serde value and typed envelope contents.
7
8mod declaration;
9#[doc(hidden)]
10pub use declaration::__private;
11mod method;
12#[cfg(feature = "derive")]
13pub use declaration::Evolve;
14#[cfg(feature = "typescript")]
15pub use declaration::{ExtensionLayout, OpenLayout, SchemaFields};
16pub use declaration::{ExtensionSlot, OpenSlot, RecoverSlot};
17pub use method::{Evolving, Method, decode, encode, encode_into, encode_to_slice};
18#[doc(hidden)]
19pub mod inline;
20#[cfg(feature = "derive")]
21#[doc(hidden)]
22pub use serde as __serde;
23
24use crate::{
25    Encoding, Error, LimitKind, Limits, decode as reader, encode as writer, framing::HEADER_BYTES,
26    meter::Budget,
27};
28use alloc::vec::Vec;
29use core::fmt;
30use serde::{
31    Deserialize, Deserializer, Serialize, Serializer,
32    de::{self, SeqAccess, Visitor},
33    ser::SerializeTuple,
34};
35use serde_bytes::Bytes;
36
37mod recovery;
38pub use recovery::{Recoverable, RecoveryContext};
39
40/// A manually projected message with a positional core and a sparse root block.
41pub struct Projected<'a, T> {
42    /// Positional fields in their declared order.
43    pub core: T,
44    /// Staged sparse fields at the root of the message.
45    pub extensions: Extensions<'a>,
46}
47
48impl<'a, T> Projected<'a, T> {
49    /// Assemble a message with its staged root fields.
50    pub const fn new(core: T, extensions: Extensions<'a>) -> Self {
51        Self { core, extensions }
52    }
53
54    /// Assemble a message whose writer supplies no root extensions.
55    pub const fn empty(core: T) -> Self {
56        Self::new(core, Extensions::empty())
57    }
58}
59
60impl<T: Serialize> Serialize for Projected<'_, T> {
61    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
62        (&self.core, self.extensions).serialize(serializer)
63    }
64}
65
66impl<'de: 'a, 'a, T: Deserialize<'de>> Deserialize<'de> for Projected<'a, T> {
67    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
68        let (core, extensions) = <(T, Extensions<'a>)>::deserialize(deserializer)?;
69        Ok(Self::new(core, extensions))
70    }
71}
72
73/// Decode the outer Serde DTO and project its envelopes under one budget.
74///
75/// The application owns the projection, including required-field checks and
76/// visiting the root extension block and any nested envelopes. Keep custom
77/// Serde and application work bounded independently.
78///
79/// # Errors
80/// Returns an error from frame admission, DTO decoding, projection, or any
81/// refused operation even if the application ignores that refusal.
82pub fn decode_projected<'de, T: Deserialize<'de>, R>(
83    input: &'de [u8],
84    encoding: Encoding,
85    limits: Limits,
86    project: impl FnOnce(Projected<'de, T>, &ReadContext<'_>) -> Result<R, Error>,
87) -> Result<R, Error> {
88    decode_value(input, encoding, limits, project)
89}
90
91pub(crate) fn decode_value<'de, T: Deserialize<'de>, R>(
92    input: &'de [u8],
93    encoding: Encoding,
94    limits: Limits,
95    project: impl FnOnce(T, &ReadContext<'_>) -> Result<R, Error>,
96) -> Result<R, Error> {
97    let (payload, limits) = reader::admit_input(input, encoding, limits)?;
98    let budget = Budget::new(limits);
99    let dto = reader::decode_payload(payload, &budget, 1);
100    budget.check()?;
101    let result = project(
102        dto?,
103        &ReadContext {
104            budget: &budget,
105            depth: 1,
106        },
107    );
108    budget.check()?;
109    result
110}
111
112/// Prepare envelopes in caller-owned scratch space and encode the resulting DTO.
113///
114/// Envelope preparation, DTO sizing and DTO writing each debit the same meter.
115/// Returns the final slice in reusable output storage.
116///
117/// # Errors
118/// Clears the output on any failure. A failed preparation may modify its own
119/// scratch storage. Custom serializers must agree on their size across passes.
120pub fn encode_projected_into<'out, 'value, T: Serialize>(
121    output: &'out mut Vec<u8>,
122    encoding: Encoding,
123    limits: Limits,
124    prepare: impl FnOnce(&WriteContext<'_>) -> Result<Projected<'value, T>, Error>,
125) -> Result<&'out [u8], Error> {
126    encode_value_into(output, encoding, limits, prepare)
127}
128
129pub(crate) fn encode_value_into<T: Serialize>(
130    output: &mut Vec<u8>,
131    encoding: Encoding,
132    limits: Limits,
133    prepare: impl FnOnce(&WriteContext<'_>) -> Result<T, Error>,
134) -> Result<&[u8], Error> {
135    encode_value_into_with(output, encoding, limits, |output, header, context| {
136        let value = prepare(context);
137        context.budget.check()?;
138        write_value_into(output, header, context, &value?)
139    })
140}
141
142fn encode_value_into_with(
143    output: &mut Vec<u8>,
144    encoding: Encoding,
145    limits: Limits,
146    write: impl FnOnce(&mut Vec<u8>, Option<[u8; HEADER_BYTES]>, &WriteContext<'_>) -> Result<(), Error>,
147) -> Result<&[u8], Error> {
148    output.clear();
149    let header = writer::frame_header(encoding);
150    let prefix = if header.is_some() { HEADER_BYTES } else { 0 };
151    let limits = limits.without_prefix(prefix)?;
152    let budget = Budget::new(limits);
153    budget.check()?;
154    let context = WriteContext {
155        budget: &budget,
156        depth: 1,
157        byte_limit: limits.bytes,
158    };
159    let result = write(output, header, &context);
160    if let Err(error) = budget.check().and(result) {
161        output.clear();
162        return Err(error);
163    }
164    Ok(output)
165}
166
167fn write_value_into<T: Serialize>(
168    output: &mut Vec<u8>,
169    header: Option<[u8; HEADER_BYTES]>,
170    context: &WriteContext<'_>,
171    value: &T,
172) -> Result<(), Error> {
173    writer::write_projected_vec(value, context.budget, header, context.byte_limit, output)
174}
175
176/// Measure an already projected message, including its root block and any frame header.
177/// Preparation of the projected fields uses the caller's staging allowance.
178///
179/// # Errors
180/// Returns a sizing, serialization or allowance error.
181pub fn projected_len<T: Serialize>(
182    value: &Projected<'_, T>,
183    encoding: Encoding,
184    limits: Limits,
185) -> Result<usize, Error> {
186    writer::encoded_len(value, encoding, limits)
187}
188
189/// Prepare envelopes and encode the DTO once into caller-owned output.
190///
191/// The destination is already allocated. Envelope preparation and DTO
192/// serialization share one resource meter. Only the successful returned
193/// prefix contains a complete encoding.
194///
195/// # Errors
196/// Returns a preparation, serialization or allowance error. A short
197/// destination returns `Limit(Output)`. A failed operation may modify the
198/// caller's output and scratch.
199pub fn encode_projected_to_slice<'out, 'value, T: Serialize>(
200    output: &'out mut [u8],
201    encoding: Encoding,
202    limits: Limits,
203    prepare: impl FnOnce(&WriteContext<'_>) -> Result<Projected<'value, T>, Error>,
204) -> Result<&'out [u8], Error> {
205    encode_value_to_slice(output, encoding, limits, prepare)
206}
207
208pub(crate) fn encode_value_to_slice<T: Serialize>(
209    output: &mut [u8],
210    encoding: Encoding,
211    limits: Limits,
212    prepare: impl FnOnce(&WriteContext<'_>) -> Result<T, Error>,
213) -> Result<&[u8], Error> {
214    encode_value_to_slice_with(output, encoding, limits, |mut destination| {
215        let context = destination.context();
216        let dto = prepare(&context);
217        context.budget.check()?;
218        destination.write_value(&dto?)
219    })
220}
221
222/// Encode a DTO that borrows its projection context into caller-owned output.
223///
224/// The callback receives the destination for one final write. Use its context
225/// to prepare envelopes while Serde visits the DTO, for example when staging
226/// one sequence element at a time. Its output becomes visible only after the
227/// callback and the shared resource checks succeed.
228///
229/// # Errors
230/// Returns a callback, serialization or allowance error. Success requires
231/// one completed write. A failed callback or serialization may modify the
232/// caller's output and scratch.
233pub fn encode_projected_to_slice_with(
234    output: &mut [u8],
235    encoding: Encoding,
236    limits: Limits,
237    write: impl FnOnce(ProjectedOutput<'_>) -> Result<(), Error>,
238) -> Result<&[u8], Error> {
239    encode_value_to_slice_with(output, encoding, limits, write)
240}
241
242pub(crate) fn encode_value_to_slice_with(
243    output: &mut [u8],
244    encoding: Encoding,
245    limits: Limits,
246    write: impl FnOnce(ProjectedOutput<'_>) -> Result<(), Error>,
247) -> Result<&[u8], Error> {
248    let header = writer::frame_header(encoding);
249    let prefix = if header.is_some() { HEADER_BYTES } else { 0 };
250    let limits = limits.without_prefix(prefix)?;
251    let budget = Budget::new(limits);
252    budget.check()?;
253    let capacity = output
254        .get_mut(prefix..)
255        .ok_or(Error::Limit(LimitKind::Output))?;
256    let capacity_kind = if capacity.len() < limits.bytes {
257        LimitKind::Output
258    } else {
259        LimitKind::Bytes
260    };
261    let cap = capacity.len().min(limits.bytes);
262    let mut written = None;
263    let result = write(ProjectedOutput {
264        output: &mut capacity[..cap],
265        context: WriteContext {
266            budget: &budget,
267            depth: 1,
268            byte_limit: limits.bytes,
269        },
270        capacity_kind,
271        written: &mut written,
272    });
273    budget.check()?;
274    result?;
275    let size = written.ok_or(Error::Malformed)?;
276    if let Some(header) = header {
277        output[..prefix].copy_from_slice(&header);
278    }
279    Ok(&output[..prefix + size])
280}
281
282/// The caller's destination for one projected Serde write.
283pub struct ProjectedOutput<'scope> {
284    output: &'scope mut [u8],
285    context: WriteContext<'scope>,
286    capacity_kind: LimitKind,
287    written: &'scope mut Option<usize>,
288}
289
290impl<'scope> ProjectedOutput<'scope> {
291    /// Borrow the meter for envelope preparation, including during traversal.
292    #[must_use]
293    pub const fn context(&self) -> WriteContext<'scope> {
294        WriteContext {
295            budget: self.context.budget,
296            depth: self.context.depth,
297            byte_limit: self.context.byte_limit,
298        }
299    }
300
301    /// Consume this destination and serialize the DTO in the current scope.
302    ///
303    /// # Errors
304    /// Returns a serialization or allowance error. The destination's bytes
305    /// are available only from the successful outer operation.
306    pub fn write<T: Serialize>(mut self, value: &Projected<'_, T>) -> Result<(), Error> {
307        self.write_value(value)
308    }
309
310    pub(crate) fn write_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
311        let size = writer::write_bounded_slice::<T, false>(
312            value,
313            self.context.budget,
314            self.context.depth,
315            self.output,
316            self.capacity_kind,
317        )?;
318        *self.written = Some(size);
319        Ok(())
320    }
321}
322
323/// Admission context for one projection. It borrows the outer decode's meter.
324pub struct ReadContext<'a> {
325    budget: &'a Budget,
326    depth: usize,
327}
328
329impl ReadContext<'_> {
330    /// Run application projection at one greater depth on the same meter.
331    ///
332    /// # Errors
333    /// Returns an allowance refusal or the callback error.
334    pub fn nested<R>(
335        &self,
336        project: impl FnOnce(&ReadContext<'_>) -> Result<R, Error>,
337    ) -> Result<R, Error> {
338        let child = self.child();
339        admit_scope(child.budget, child.depth)?;
340        project(&child)
341    }
342
343    /// Charge storage for values the application will materialize.
344    ///
345    /// # Errors
346    /// Returns an allocation or traversal allowance refusal.
347    pub fn admit_allocation<T>(&self, count: usize) -> Result<(), Error> {
348        admit_materialization::<T>(self.budget, self.depth, count)
349    }
350
351    /// Context for an already admitted structural field.
352    #[doc(hidden)]
353    #[must_use]
354    pub fn child(&self) -> Self {
355        Self {
356            budget: self.budget,
357            depth: self.depth.saturating_add(1),
358        }
359    }
360}
361
362/// Admission context for envelope preparation on the outer encoder's meter.
363pub struct WriteContext<'a> {
364    budget: &'a Budget,
365    depth: usize,
366    byte_limit: usize,
367}
368
369impl WriteContext<'_> {
370    /// Run application preparation at one greater depth on the same meter.
371    ///
372    /// # Errors
373    /// Returns an allowance refusal or the callback error.
374    pub fn nested<R>(
375        &self,
376        prepare: impl FnOnce(&WriteContext<'_>) -> Result<R, Error>,
377    ) -> Result<R, Error> {
378        let child = self.child();
379        admit_scope(child.budget, child.depth)?;
380        prepare(&child)
381    }
382
383    /// Debit a generated preparation step before recursively staging a value.
384    ///
385    /// # Errors
386    /// Returns the first depth or work refusal.
387    #[doc(hidden)]
388    pub fn admit_preparation(&self) -> Result<(), Error> {
389        admit_scope(self.budget, self.depth)
390    }
391
392    /// Debit storage before constructing a temporary Serde view.
393    ///
394    /// # Errors
395    /// Returns the first allocation or traversal refusal.
396    #[doc(hidden)]
397    pub fn admit_allocation<T>(&self, count: usize) -> Result<(), Error> {
398        admit_materialization::<T>(self.budget, self.depth, count)
399    }
400
401    /// Context for recursively preparing a structural field.
402    #[doc(hidden)]
403    #[must_use]
404    pub fn child(&self) -> Self {
405        Self {
406            budget: self.budget,
407            depth: self.depth.saturating_add(1),
408            byte_limit: self.byte_limit,
409        }
410    }
411
412    fn write_once<T: Serialize + ?Sized>(
413        &self,
414        value: &T,
415        scratch: &mut [u8],
416    ) -> Result<usize, Error> {
417        let byte_limit = self.byte_limit.min(u32::MAX as usize);
418        let capacity_kind = if scratch.len() < byte_limit {
419            LimitKind::Scratch
420        } else {
421            LimitKind::Bytes
422        };
423        let cap = scratch.len().min(byte_limit);
424        writer::write_scratch(
425            value,
426            self.budget,
427            self.depth,
428            &mut scratch[..cap],
429            capacity_kind,
430        )
431    }
432}
433
434fn varint_width(value: u32) -> usize {
435    (u32::BITS - value.leading_zeros()).max(1).div_ceil(7) as usize
436}
437
438fn admit(budget: &Budget, depth: usize, units: usize) -> Result<(), Error> {
439    if budget.enter(depth, units) {
440        Ok(())
441    } else {
442        Err(budget.error())
443    }
444}
445
446fn admit_materialization<T>(budget: &Budget, depth: usize, count: usize) -> Result<(), Error> {
447    let units = size_of::<T>().checked_mul(count).ok_or_else(|| {
448        budget.refuse();
449        budget.error()
450    })?;
451    admit(budget, depth, units)
452}
453
454fn admit_scope(budget: &Budget, depth: usize) -> Result<(), Error> {
455    if budget.enter_scope(depth) {
456        Ok(())
457    } else {
458        Err(budget.error())
459    }
460}
461
462/// A bounded field or variant payload borrowed from an admitted envelope.
463pub struct Field<'meter, 'de> {
464    bytes: &'de [u8],
465    context: ReadContext<'meter>,
466}
467
468impl<'de> Field<'_, 'de> {
469    /// Decode the complete payload using stock Postcard on the shared meter.
470    ///
471    /// # Errors
472    /// Returns a limit refusal or malformed payload error. Trailing bytes
473    /// within this known field are malformed.
474    pub fn decode<T: Deserialize<'de>>(self) -> Result<T, Error> {
475        self.project(|value, _| Ok(value))
476    }
477
478    /// Decode the typed composition of an extension body.
479    ///
480    /// # Errors
481    /// Returns the first decode, projection or resource failure.
482    #[doc(hidden)]
483    pub fn project_inline<T: inline::Inline<'de>>(self) -> Result<T, Error> {
484        self.project(T::project)
485    }
486
487    /// Decode this field and project any nested envelopes at its depth.
488    ///
489    /// # Errors
490    /// Returns a field decode error or an error from projection.
491    pub fn project<T: Deserialize<'de>, R>(
492        self,
493        project: impl FnOnce(T, &ReadContext<'_>) -> Result<R, Error>,
494    ) -> Result<R, Error> {
495        let value = reader::decode_payload(self.bytes, self.context.budget, self.context.depth)
496            .map_err(|error| {
497                if error == Error::Trailing {
498                    Error::Malformed
499                } else {
500                    error
501                }
502            });
503        self.context.budget.check()?;
504        let result = project(value?, &self.context);
505        self.context.budget.check()?;
506        result
507    }
508}
509
510/// An opaque ordered collection of extension fields, represented as Postcard bytes.
511#[derive(Clone, Copy, Debug, PartialEq, Eq)]
512pub struct Extensions<'a>(&'a [u8]);
513
514impl<'a> Extensions<'a> {
515    /// Construct the empty extension block.
516    #[must_use]
517    pub const fn empty() -> Self {
518        Self(&[])
519    }
520
521    /// Visit all IDs and length-bounded fields in strictly increasing order.
522    ///
523    /// A callback can ignore the field or consume it with [Field::decode].
524    /// Successful visits check even the headers of fields the caller ignores.
525    ///
526    /// # Errors
527    /// Returns malformed for zero, duplicate or descending IDs and invalid
528    /// extents. Callback errors and allowance refusals propagate.
529    pub fn visit(
530        self,
531        context: &ReadContext<'_>,
532        mut visit: impl FnMut(u32, Field<'_, 'a>) -> Result<(), Error>,
533    ) -> Result<(), Error> {
534        let block = context.child();
535        admit_scope(block.budget, block.depth)?;
536        let mut rest = self.0;
537        let mut previous = 0;
538        while !rest.is_empty() {
539            let field_context = block.child();
540            admit_scope(field_context.budget, field_context.depth)?;
541            let (id, bytes, remaining) = extension_header(rest)?;
542            if id <= previous {
543                return Err(Error::Malformed);
544            }
545            visit(
546                id,
547                Field {
548                    bytes,
549                    context: field_context,
550                },
551            )?;
552            block.budget.check()?;
553            rest = remaining;
554            previous = id;
555        }
556        Ok(())
557    }
558}
559
560#[inline]
561fn extension_header(rest: &[u8]) -> Result<(u32, &[u8], &[u8]), Error> {
562    // Single-byte Postcard headers need one bounds check for the field span.
563    if let Some(([id, length], tail)) = rest.split_first_chunk::<2>()
564        && (id | length) < 128
565    {
566        let (bytes, remaining) = tail
567            .split_at_checked(usize::from(*length))
568            .ok_or(Error::Malformed)?;
569        return Ok((u32::from(*id), bytes, remaining));
570    }
571    postcard_extension_header(rest)
572}
573
574#[inline(never)]
575fn postcard_extension_header(rest: &[u8]) -> Result<(u32, &[u8], &[u8]), Error> {
576    // Preserve Postcard's acceptance of multi-byte and redundant encodings.
577    let ((id, bytes), remaining) =
578        postcard::take_from_bytes::<(u32, &Bytes)>(rest).map_err(|_| Error::Malformed)?;
579    Ok((id, bytes.as_ref(), remaining))
580}
581
582impl Serialize for Extensions<'_> {
583    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
584        serializer.serialize_bytes(self.0)
585    }
586}
587
588impl<'de: 'a, 'a> Deserialize<'de> for Extensions<'a> {
589    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
590        <&Bytes>::deserialize(deserializer).map(|bytes| Self(bytes.as_ref()))
591    }
592}
593
594/// Write sorted extension IDs into caller-owned scratch storage.
595pub struct ExtensionsWriter<'a> {
596    output: &'a mut [u8],
597    used: usize,
598    previous: u32,
599}
600
601impl<'a> ExtensionsWriter<'a> {
602    /// Start an empty block in a slice distinct from the final frame output.
603    #[must_use]
604    pub const fn new(output: &'a mut [u8]) -> Self {
605        Self {
606            output,
607            used: 0,
608            previous: 0,
609        }
610    }
611
612    /// Append a field with a greater, nonzero ID and a typed Postcard payload.
613    ///
614    /// # Errors
615    /// Returns an ordering, serialization, allowance or scratch capacity error.
616    /// A failed append may change bytes beyond the last successfully written field.
617    pub fn push<T: Serialize + ?Sized>(
618        &mut self,
619        context: &WriteContext<'_>,
620        id: u32,
621        value: &T,
622    ) -> Result<(), Error> {
623        self.push_with(context, id, |leaf, available| {
624            leaf.write_once(value, available)
625        })
626    }
627
628    /// Append a field after preparing its nested values in the free scratch.
629    ///
630    /// The preparation bytes are reusable after the field is committed. The
631    /// scratch must fit both the child view and the resulting field while the
632    /// writer is staging it.
633    ///
634    /// # Errors
635    /// Returns the first ordering, projection, serialization or limit refusal.
636    #[doc(hidden)]
637    pub fn push_projected<'de, T: inline::Inline<'de>>(
638        &mut self,
639        context: &WriteContext<'_>,
640        id: u32,
641        value: &T,
642    ) -> Result<(), Error> {
643        self.push_with(context, id, |leaf, available| {
644            let capacity = available.len();
645            let (view, tail) = value.prepare(leaf, available)?;
646            let staged = capacity.checked_sub(tail.len()).ok_or(Error::Malformed)?;
647            let len = leaf.write_once(&view, tail)?;
648            drop(view);
649            if staged != 0 {
650                available.copy_within(staged..staged + len, 0);
651            }
652            Ok(len)
653        })
654    }
655
656    fn push_with(
657        &mut self,
658        context: &WriteContext<'_>,
659        id: u32,
660        prepare: impl FnOnce(&WriteContext<'_>, &mut [u8]) -> Result<usize, Error>,
661    ) -> Result<(), Error> {
662        if id <= self.previous {
663            return Err(Error::Malformed);
664        }
665        let mut leaf = context.child().child();
666        admit_scope(leaf.budget, leaf.depth)?;
667        let bound = leaf.byte_limit.min(u32::MAX as usize);
668        let min_prefix = if id < 128 { 2 } else { varint_width(id) + 1 };
669        let body_at = self
670            .used
671            .checked_add(min_prefix)
672            .filter(|start| *start <= bound)
673            .ok_or_else(|| leaf.budget.refuse_with(LimitKind::Bytes))?;
674        let available = self
675            .output
676            .get_mut(body_at..)
677            .ok_or_else(|| leaf.budget.refuse_with(LimitKind::Scratch))?;
678        if !leaf.budget.charge_buffer(min_prefix) {
679            return Err(leaf.budget.error());
680        }
681        // Most fields fit a one-byte length. Materialize the payload once
682        // after that slot, shifting it only if the length consumes more bytes.
683        leaf.byte_limit = bound - body_at;
684        let len = prepare(&leaf, available)?;
685        self.used = if min_prefix == 2 && len < 128 {
686            // The reserved two bytes already fit both single-byte varints.
687            self.output[self.used..body_at].copy_from_slice(&[id as u8, len as u8]);
688            body_at + len
689        } else {
690            self.finish_wide_prefix(leaf.budget, bound, id, body_at, len)?
691        };
692        self.previous = id;
693        Ok(())
694    }
695
696    #[cold]
697    #[inline(never)]
698    fn finish_wide_prefix(
699        &mut self,
700        budget: &Budget,
701        bound: usize,
702        id: u32,
703        body_at: usize,
704        len: usize,
705    ) -> Result<usize, Error> {
706        let mut end = body_at + len;
707        if len >= 128 {
708            let extra = varint_width(len as u32) - 1;
709            end = end
710                .checked_add(extra)
711                .filter(|end| *end <= bound)
712                .ok_or_else(|| budget.refuse_with(LimitKind::Bytes))?;
713            if end > self.output.len() {
714                return Err(budget.refuse_with(LimitKind::Scratch));
715            }
716            if !budget.charge_buffer(extra) {
717                return Err(budget.error());
718            }
719            self.output
720                .copy_within(body_at..body_at + len, body_at + extra);
721        }
722        let prefix = &mut self.output[self.used..end - len];
723        postcard::to_slice(&(id, len as u32), prefix).map_err(|_| Error::Malformed)?;
724        Ok(end)
725    }
726
727    /// Borrow the completed extension bytes from the caller's scratch storage.
728    #[must_use]
729    pub fn finish(self) -> Extensions<'a> {
730        self.finish_and_tail().0
731    }
732
733    /// Borrow the completed block and return the remaining scratch space.
734    ///
735    /// The returned slice can stage the next field or record while the
736    /// completed block remains borrowed.
737    #[must_use]
738    pub fn finish_and_tail(self) -> (Extensions<'a>, &'a mut [u8]) {
739        let (bytes, tail) = self.output.split_at_mut(self.used);
740        (Extensions(bytes), tail)
741    }
742}
743
744/// An optional open variant with a stable numeric ID and opaque payload.
745///
746/// The first component is a Postcard u32. Its low bit selects a following
747/// nonempty Postcard byte span. The upper bits hold the ID, with zero reserved
748/// for absence. Unit variants have no payload length or payload bytes.
749#[derive(Clone, Copy, Debug, PartialEq, Eq)]
750pub struct OpaqueOpen<'a> {
751    id: u32,
752    bytes: &'a [u8],
753}
754
755impl<'a> OpaqueOpen<'a> {
756    /// Construct an absent open variant.
757    #[must_use]
758    pub const fn absent() -> Self {
759        Self { id: 0, bytes: &[] }
760    }
761
762    /// Construct a present unit variant without using scratch storage.
763    ///
764    /// # Errors
765    /// Returns malformed if the ID is zero or greater than 2³¹ minus one.
766    pub const fn unit(id: u32) -> Result<Self, Error> {
767        if id == 0 || id > (u32::MAX >> 1) {
768            return Err(Error::Malformed);
769        }
770        Ok(Self { id, bytes: &[] })
771    }
772
773    /// Write a typed open variant payload into scratch and borrow its extent.
774    ///
775    /// # Errors
776    /// Returns an invalid ID, serialization, allowance or scratch capacity error.
777    pub fn write<T: Serialize + ?Sized>(
778        context: &WriteContext<'_>,
779        id: u32,
780        value: &T,
781        scratch: &'a mut [u8],
782    ) -> Result<Self, Error> {
783        Self::write_in(context, id, value, scratch).map(|(open, _)| open)
784    }
785
786    /// Write a typed payload and return the open variant and unused scratch.
787    ///
788    /// # Errors
789    /// Returns an invalid ID, serialization, allowance or scratch capacity error.
790    pub fn write_in<T: Serialize + ?Sized>(
791        context: &WriteContext<'_>,
792        id: u32,
793        value: &T,
794        scratch: &'a mut [u8],
795    ) -> Result<(Self, &'a mut [u8]), Error> {
796        Self::unit(id)?;
797        let leaf = context.child().child();
798        let size = leaf.write_once(value, scratch)?;
799        let (bytes, tail) = scratch.split_at_mut(size);
800        Ok((Self { id, bytes }, tail))
801    }
802
803    /// Map a present selected tag, or keep absence.
804    ///
805    /// The callback can ignore any tag its schema does not understand and
806    /// decode a known tag's entire payload. Known unit tags should decode the
807    /// Rust unit value to reject a nonempty body.
808    ///
809    /// # Errors
810    /// Returns any allowance or callback error.
811    pub fn visit<R>(
812        self,
813        context: &ReadContext<'_>,
814        visit: impl FnOnce(u32, Field<'_, 'a>) -> Result<R, Error>,
815    ) -> Result<Option<R>, Error> {
816        let variant = context.child();
817        if self.id == 0 {
818            admit_scope(variant.budget, variant.depth)?;
819            return Ok(None);
820        }
821        let field_context = variant.child();
822        // A present case visits the variant and its payload. Batch the debit
823        // when both fit, and let the meter preserve their order on refusal.
824        if !variant
825            .budget
826            .enter_nested_scopes(variant.depth, field_context.depth)
827        {
828            return Err(variant.budget.error());
829        }
830        let result = visit(
831            self.id,
832            Field {
833                bytes: self.bytes,
834                context: field_context,
835            },
836        );
837        variant.budget.check()?;
838        result.map(Some)
839    }
840}
841
842impl Serialize for OpaqueOpen<'_> {
843    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
844        let has_payload = !self.bytes.is_empty();
845        let mut tuple = serializer.serialize_tuple(1 + usize::from(has_payload))?;
846        tuple.serialize_element(&((self.id << 1) | u32::from(has_payload)))?;
847        if has_payload {
848            tuple.serialize_element(Bytes::new(self.bytes))?;
849        }
850        tuple.end()
851    }
852}
853
854impl<'de: 'a, 'a> Deserialize<'de> for OpaqueOpen<'a> {
855    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
856        struct OpenVisitor;
857        impl<'de> Visitor<'de> for OpenVisitor {
858            type Value = OpaqueOpen<'de>;
859
860            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
861                formatter.write_str("open variant tag and optional nonempty payload")
862            }
863
864            fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
865                let header: u32 = access
866                    .next_element()?
867                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
868                let id = header >> 1;
869                let bytes = if header & 1 == 0 {
870                    &[]
871                } else {
872                    if id == 0 {
873                        return Err(de::Error::custom("absent open variant has a payload"));
874                    }
875                    let bytes: &Bytes = access
876                        .next_element()?
877                        .ok_or_else(|| de::Error::invalid_length(1, &self))?;
878                    if bytes.is_empty() {
879                        return Err(de::Error::custom("empty open variant payload extent"));
880                    }
881                    bytes.as_ref()
882                };
883                Ok(OpaqueOpen { id, bytes })
884            }
885        }
886        deserializer.deserialize_tuple(2, OpenVisitor)
887    }
888}