Skip to main content

ic_wire/encode/
mod.rs

1//! Shared preflight and destination-specific bounded Postcard output.
2
3mod admitted;
4
5use crate::{Direction, Encoding, Error, Limits, meter::Budget};
6use alloc::vec::Vec;
7use postcard::ser_flavors::Flavor;
8use serde::Serialize;
9
10fn preflight<T: Serialize + ?Sized>(
11    value: &T,
12    encoding: Encoding,
13    limits: Limits,
14) -> Result<(Option<[u8; 11]>, usize), Error> {
15    let header = match encoding {
16        Encoding::Payload => None,
17        Encoding::Frame { method, direction } => {
18            let mut header = [0; 11];
19            header[..2].copy_from_slice(b"IW");
20            header[2..10].copy_from_slice(&method.to_le_bytes());
21            header[10] = match direction {
22                Direction::Request => 0,
23                Direction::Response => 1,
24            };
25            Some(header)
26        }
27    };
28    let prefix = if header.is_some() { 11 } else { 0 };
29    let payload_limits = limits.without_prefix(prefix)?;
30    let budget = Budget::new(payload_limits);
31    let size = postcard::experimental::serialized_size(&admitted::Bounded {
32        value,
33        budget: &budget,
34        depth: 1,
35    })
36    .map_err(|_| budget.error())?;
37    if size > payload_limits.bytes {
38        return Err(Error::Limit);
39    }
40    // The byte allowance was reduced by prefix before sizing, so addition fits.
41    Ok((header, size + prefix))
42}
43
44/// Measure the complete selected encoding without allocating codec output.
45///
46/// Custom Serialize code is trusted and must be deterministic across calls.
47/// This does not return a reusable admission token.
48///
49/// # Errors
50/// Returns Limit for exhausted allowances, otherwise Malformed for serializer
51/// failure. Framed lengths include the 11-byte header.
52pub fn encoded_len<T: Serialize + ?Sized>(
53    value: &T,
54    encoding: Encoding,
55    limits: Limits,
56) -> Result<usize, Error> {
57    preflight(value, encoding, limits).map(|(_, size)| size)
58}
59
60/// Encode into owned storage after a complete sizing/admission pass.
61///
62/// # Errors
63/// Returns the same errors as [`encode_into`]. No partial output is returned.
64pub fn encode<T: Serialize + ?Sized>(
65    value: &T,
66    encoding: Encoding,
67    limits: Limits,
68) -> Result<Vec<u8>, Error> {
69    let mut output = Vec::new();
70    encode_into(value, encoding, limits, &mut output)?;
71    Ok(output)
72}
73
74/// Encode into reusable storage, returning only the completed prefix.
75///
76/// Prior contents are cleared, including on error; capacity retention on failure
77/// is not promised. Keep retained retry bytes elsewhere. Preflight completes
78/// before codec output reservation. Custom serializers must be deterministic;
79/// writes remain bounded by preflight length even if a second pass grows.
80///
81/// # Errors
82/// Returns Limit for exhausted allowances, Allocation for failed output
83/// reservation, otherwise Malformed for serialization failure.
84pub fn encode_into<'out, T: Serialize + ?Sized>(
85    value: &T,
86    encoding: Encoding,
87    limits: Limits,
88    output: &'out mut Vec<u8>,
89) -> Result<&'out [u8], Error> {
90    output.clear();
91    let (header, size) = preflight(value, encoding, limits)?;
92    output
93        .try_reserve_exact(size)
94        .map_err(|_| Error::Allocation)?;
95    if let Some(header) = header {
96        output.extend_from_slice(&header);
97    }
98    let budget = Budget::new(limits);
99    *output = postcard::serialize_with_flavor(
100        &admitted::Bounded {
101            value,
102            budget: &budget,
103            depth: 1,
104        },
105        Output {
106            bytes: core::mem::take(output),
107            limit: size,
108        },
109    )
110    .map_err(|_| budget.error())?;
111    Ok(output)
112}
113
114/// Encode into caller storage without allocating codec output.
115///
116/// A short destination is rejected before writing. Other failures may modify
117/// storage; only a successful returned slice may be published. Custom Serialize
118/// work is trusted and may allocate independently. Caller capacity does not
119/// reduce the configured allocation allowance.
120///
121/// # Errors
122/// Returns Limit for exhausted allowances or a short destination, otherwise
123/// Malformed for serialization failure (including growth between passes).
124pub fn encode_to_slice<'out, T: Serialize + ?Sized>(
125    value: &T,
126    encoding: Encoding,
127    limits: Limits,
128    output: &'out mut [u8],
129) -> Result<&'out [u8], Error> {
130    let (header, size) = preflight(value, encoding, limits)?;
131    let output = output.get_mut(..size).ok_or(Error::Limit)?;
132    let prefix = if let Some(header) = header {
133        output[..11].copy_from_slice(&header);
134        11
135    } else {
136        0
137    };
138    let budget = Budget::new(limits);
139    let payload = postcard::to_slice(
140        &admitted::Bounded {
141            value,
142            budget: &budget,
143            depth: 1,
144        },
145        &mut output[prefix..],
146    )
147    .map_err(|_| budget.error())?;
148    let written = prefix + payload.len();
149    Ok(&output[..written])
150}
151
152// Allocation capacity is not admission: every write is capped at preflight size.
153struct Output {
154    bytes: Vec<u8>,
155    limit: usize,
156}
157
158impl Flavor for Output {
159    type Output = Vec<u8>;
160
161    fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
162        if self.bytes.len() == self.limit {
163            return Err(postcard::Error::SerializeBufferFull);
164        }
165        self.bytes.push(byte);
166        Ok(())
167    }
168
169    fn try_extend(&mut self, bytes: &[u8]) -> postcard::Result<()> {
170        if bytes.len() > self.limit - self.bytes.len() {
171            return Err(postcard::Error::SerializeBufferFull);
172        }
173        self.bytes.extend_from_slice(bytes);
174        Ok(())
175    }
176
177    fn finalize(self) -> postcard::Result<Self::Output> {
178        Ok(self.bytes)
179    }
180}