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