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