ic-wire 0.34.9

Bounded Serde/Postcard encoding with schema and TypeScript generation
Documentation
//! Stock Serde projections used by derived Wire messages.

use super::{
    Evolving, ReadContext, WriteContext, decode_value, encode_value_into_with, write_value_into,
};
use crate::{Encoding, Error, LimitKind, Limits, meter::Budget};
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

mod containers;

/// A leaf that uses its ordinary Serde representation inside evolving values.
///
/// Derives and the built-in fields supply this marker. The complete Serde value
/// is a fixed contract, including any nested contents it serializes itself.
pub trait Fixed {}

/// Compose a typed value with the Serde projections of its children.
///
/// The derive builds a transport view without replacing the application's own
/// Serde implementations. Borrowed reader and writer views retain their storage.
pub trait Inline<'de>: Sized {
    /// True when preparing this shape can write extension bytes.
    #[doc(hidden)]
    const MAY_STAGE: bool = true;

    /// The staged Serde value and its borrowed application data or scratch.
    type Encoded<'s>: Serialize
    where
        Self: 's;

    /// The raw Serde value to project with the enclosing read context.
    type Decoded: Deserialize<'de>;

    /// Stage this value and return the unused suffix of the supplied scratch.
    ///
    /// # Errors
    /// Propagates resource, scratch and nested value serialization failures.
    fn prepare<'s>(
        &'s self,
        context: &WriteContext<'_>,
        scratch: &'s mut [u8],
    ) -> Result<(Self::Encoded<'s>, &'s mut [u8]), Error>;

    /// Validate nested envelopes and construct the application value.
    ///
    /// # Errors
    /// Propagates structural, compatibility and resource failures.
    fn project(input: Self::Decoded, context: &ReadContext<'_>) -> Result<Self, Error>;
}

/// A typed message whose inline projection includes the sparse root.
///
/// Deriving `Wire` on an evolving struct supplies this implementation. The
/// inline projection must use the same root layout as its `Evolving`
/// implementation.
pub trait InlineMessage<'de>: Evolving<'de> + Inline<'de> {}

impl<'de, T: Fixed + Serialize + Deserialize<'de>> Inline<'de> for T {
    const MAY_STAGE: bool = false;

    type Encoded<'s>
        = &'s T
    where
        Self: 's;
    type Decoded = T;

    fn prepare<'s>(
        &'s self,
        _: &WriteContext<'_>,
        scratch: &'s mut [u8],
    ) -> Result<(Self::Encoded<'s>, &'s mut [u8]), Error> {
        Ok((self, scratch))
    }

    fn project(input: Self::Decoded, _: &ReadContext<'_>) -> Result<Self, Error> {
        Ok(input)
    }
}

/// Record an incompatibility so known siblings still receive validation.
///
/// # Errors
/// Propagates hard failures immediately.
pub fn preserve_incompatible<T>(
    result: Result<T, Error>,
    incompatible: &mut bool,
) -> Result<Option<T>, Error> {
    match result {
        Ok(value) => Ok(Some(value)),
        Err(Error::Incompatible) => {
            *incompatible = true;
            Ok(None)
        }
        Err(error) => Err(error),
    }
}

/// Sorted extension destinations for a derived sparse record.
#[doc(hidden)]
pub trait FieldTargets<'de> {
    /// Assign a bounded field to its declared destination, if present.
    ///
    /// # Errors
    /// Propagates structural and resource failures from known fields.
    fn assign(
        &mut self,
        id: u32,
        field: super::Field<'_, 'de>,
        incompatible: &mut bool,
    ) -> Result<(), Error>;
}

impl<'de> FieldTargets<'de> for () {
    fn assign(&mut self, _: u32, _: super::Field<'_, 'de>, _: &mut bool) -> Result<(), Error> {
        Ok(())
    }
}

impl<'de, T: Inline<'de>> FieldTargets<'de> for (u32, &mut Option<T>) {
    fn assign(
        &mut self,
        id: u32,
        field: super::Field<'_, 'de>,
        incompatible: &mut bool,
    ) -> Result<(), Error> {
        if id == self.0 {
            *self.1 = preserve_incompatible(field.project_inline::<T>(), incompatible)?;
        }
        Ok(())
    }
}

impl<'de, L: FieldTargets<'de>, R: FieldTargets<'de>> FieldTargets<'de> for (u32, L, R) {
    fn assign(
        &mut self,
        id: u32,
        field: super::Field<'_, 'de>,
        incompatible: &mut bool,
    ) -> Result<(), Error> {
        if id < self.0 {
            self.1.assign(id, field, incompatible)
        } else {
            self.2.assign(id, field, incompatible)
        }
    }
}

/// Validate the block and fill its known destinations.
///
/// # Errors
/// Propagates structural and resource failures in input order.
#[doc(hidden)]
#[inline(never)]
pub fn read_fields<'de>(
    extensions: super::Extensions<'de>,
    context: &ReadContext<'_>,
    mut targets: impl FieldTargets<'de>,
    incompatible: &mut bool,
) -> Result<(), Error> {
    extensions.visit(context, |id, field| targets.assign(id, field, incompatible))
}

/// Stage and encode an inline value into the existing projected frame path.
///
/// # Errors
/// Returns the first projection, encoding or admission error. Output is empty
/// on failure.
#[doc(hidden)]
pub fn encode<'de, T: InlineMessage<'de>>(
    value: &T,
    output: &mut Vec<u8>,
    encoding: Encoding,
    limits: Limits,
) -> Result<(), Error> {
    type FrameWriter<'a> = dyn FnMut(
            &mut Vec<u8>,
            Option<[u8; crate::framing::HEADER_BYTES]>,
            &WriteContext<'_>,
        ) -> Result<(), Error>
        + 'a;
    let write: &mut FrameWriter<'_> = &mut |output, header, context| {
        with_scratch(T::MAY_STAGE, context.budget, |scratch| {
            let (prepared, _) = value.prepare(context, scratch)?;
            context.budget.check()?;
            write_value_into(output, header, context, &prepared)
        })
    };
    encode_value_into_with(output, encoding, limits, write).map(|_| ())
}

const STACK_SCRATCH: usize = 32;
const INITIAL_HEAP_SCRATCH: usize = 256;

pub(super) fn with_scratch(
    may_stage: bool,
    budget: &Budget,
    mut encode: impl FnMut(&mut [u8]) -> Result<(), Error>,
) -> Result<(), Error> {
    if !may_stage {
        return encode(&mut []);
    }
    with_staging_scratch(budget, &mut encode)
}

#[inline(never)]
fn with_staging_scratch(
    budget: &Budget,
    encode: &mut dyn FnMut(&mut [u8]) -> Result<(), Error>,
) -> Result<(), Error> {
    let mut allocation_checkpoint = budget.scratch_headroom();
    let mut stack = [0; STACK_SCRATCH];
    let outcome = encode(&mut stack);
    if outcome != Err(Error::Limit(LimitKind::Scratch)) {
        return outcome;
    }
    let mut scratch = Vec::new();
    loop {
        grow_scratch(budget, &mut scratch, &mut allocation_checkpoint)?;
        let outcome = encode(&mut scratch);
        if outcome != Err(Error::Limit(LimitKind::Scratch)) {
            return outcome;
        }
    }
}

#[cold]
#[inline(never)]
fn grow_scratch(
    budget: &Budget,
    scratch: &mut Vec<u8>,
    allocation_checkpoint: &mut usize,
) -> Result<(), Error> {
    budget.resume_after_scratch(*allocation_checkpoint);
    budget.check()?;
    let size = scratch.len().max(STACK_SCRATCH);
    let capacity = scratch.capacity();
    let available = capacity.saturating_add(budget.scratch_headroom());
    let next = size
        .saturating_mul(2)
        .max(INITIAL_HEAP_SCRATCH)
        .min(available);
    if next <= size || !budget.charge_buffer(next.saturating_sub(capacity).div_ceil(8)) {
        return Err(budget.refuse_with(LimitKind::Allocation));
    }
    scratch
        .try_reserve_exact(next - scratch.len())
        .map_err(|_| Error::Allocation)?;
    let extra = scratch.capacity().saturating_sub(capacity.max(next));
    if extra != 0 && !budget.charge_buffer(extra.div_ceil(8)) {
        return Err(budget.error());
    }
    *allocation_checkpoint = budget.scratch_headroom();
    scratch.resize(next, 0);
    Ok(())
}

/// Decode and project an inline value with one shared resource meter.
///
/// # Errors
/// Returns a frame, known value, payload or admission error.
#[doc(hidden)]
pub fn decode<'de, T: InlineMessage<'de>>(
    input: &'de [u8],
    encoding: Encoding,
    limits: Limits,
) -> Result<T, Error> {
    decode_inline(input, encoding, limits)
}

fn decode_inline<'de, T: Inline<'de>>(
    input: &'de [u8],
    encoding: Encoding,
    limits: Limits,
) -> Result<T, Error> {
    decode_value(input, encoding, limits, T::project)
}

#[cfg(test)]
mod tests;