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