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