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