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 = frame_header(encoding);
16    let prefix = if header.is_some() { HEADER_BYTES } else { 0 };
17    let payload_limits = limits.without_prefix(prefix)?;
18    let budget = Budget::new(payload_limits);
19    let size = measure_payload(value, &budget, 1)?;
20    if size > payload_limits.bytes {
21        return Err(Error::Limit(crate::LimitKind::Bytes));
22    }
23
24    // The byte allowance was reduced by prefix before sizing, so addition fits.
25    Ok((header, size + prefix))
26}
27
28pub(super) fn frame_header(encoding: Encoding) -> Option<[u8; HEADER_BYTES]> {
29    match encoding {
30        Encoding::Payload => None,
31        Encoding::Frame { method, direction } => {
32            let mut header = [0; HEADER_BYTES];
33            header[..2].copy_from_slice(b"IW");
34            header[2..10].copy_from_slice(&method.to_le_bytes());
35            header[10] = match direction {
36                Direction::Request => 0,
37                Direction::Response => 1,
38            };
39            Some(header)
40        }
41    }
42}
43
44pub(super) fn measure_payload<T: Serialize + ?Sized>(
45    value: &T,
46    budget: &Budget,
47    depth: usize,
48) -> Result<usize, Error> {
49    postcard::serialize_with_flavor(
50        &admitted::Bounded {
51            value,
52            budget,
53            depth,
54        },
55        Output::Count(0),
56    )
57    .map_err(|_| budget.error())
58}
59
60/// Measure the complete selected encoding without allocating codec output.
61///
62/// Custom Serialize code is trusted and must be deterministic across calls.
63/// This does not return a reusable admission token.
64///
65/// # Errors
66/// Returns Limit for exhausted allowances, otherwise Malformed for serializer
67/// failure. Framed lengths include the 11-byte header.
68pub fn encoded_len<T: Serialize + ?Sized>(
69    value: &T,
70    encoding: Encoding,
71    limits: Limits,
72) -> Result<usize, Error> {
73    preflight(value, encoding, limits).map(|(_, size)| size)
74}
75
76/// Encode into owned storage after a complete sizing/admission pass.
77///
78/// # Errors
79/// Returns the same errors as [`encode_into`]. No partial output is returned.
80pub fn encode<T: Serialize + ?Sized>(
81    value: &T,
82    encoding: Encoding,
83    limits: Limits,
84) -> Result<Vec<u8>, Error> {
85    let mut output = Vec::new();
86    encode_into(value, encoding, limits, &mut output)?;
87
88    Ok(output)
89}
90
91/// Encode into reusable storage, returning only the completed prefix.
92///
93/// Prior contents are cleared, including on error; capacity retention on failure
94/// is not promised. Keep retained retry bytes elsewhere. Preflight completes
95/// before codec output reservation. Custom serializers must be deterministic;
96/// writes remain bounded by preflight length even if a second pass grows.
97///
98/// # Errors
99/// Returns Limit for exhausted allowances, Allocation for failed output
100/// reservation, otherwise Malformed for serialization failure.
101pub fn encode_into<'out, T: Serialize + ?Sized>(
102    value: &T,
103    encoding: Encoding,
104    limits: Limits,
105    output: &'out mut Vec<u8>,
106) -> Result<&'out [u8], Error> {
107    output.clear();
108    let (header, size) = preflight(value, encoding, limits)?;
109    write_vec(value, &Budget::new(limits), header, size, output)?;
110    Ok(output)
111}
112
113pub(super) fn write_vec<T: Serialize + ?Sized>(
114    value: &T,
115    budget: &Budget,
116    header: Option<[u8; HEADER_BYTES]>,
117    size: usize,
118    output: &mut Vec<u8>,
119) -> Result<(), Error> {
120    output
121        .try_reserve_exact(size)
122        .map_err(|_| Error::Allocation)?;
123    let mut bytes = core::mem::take(output);
124    if let Some(header) = header {
125        bytes.extend_from_slice(&header);
126    }
127    postcard::serialize_with_flavor(
128        &admitted::Bounded {
129            value,
130            budget,
131            depth: 1,
132        },
133        Output::Buffer {
134            bytes: &mut bytes,
135            limit: size,
136        },
137    )
138    .map_err(|_| budget.error())?;
139    *output = bytes;
140    Ok(())
141}
142
143/// Encode into caller storage without allocating codec output.
144///
145/// A short destination is rejected before writing. Other failures may modify
146/// storage; only a successful returned slice may be published. Custom Serialize
147/// work is trusted and may allocate independently. Caller capacity does not
148/// reduce the configured allocation allowance.
149///
150/// # Errors
151/// Returns Limit for exhausted allowances or a short destination, otherwise
152/// Malformed for serialization failure (including growth between passes).
153pub fn encode_to_slice<'out, T: Serialize + ?Sized>(
154    value: &T,
155    encoding: Encoding,
156    limits: Limits,
157    output: &'out mut [u8],
158) -> Result<&'out [u8], Error> {
159    let (header, size) = preflight(value, encoding, limits)?;
160    let output = output
161        .get_mut(..size)
162        .ok_or(Error::Limit(crate::LimitKind::Output))?;
163    let prefix = if let Some(header) = header {
164        output[..HEADER_BYTES].copy_from_slice(&header);
165
166        HEADER_BYTES
167    } else {
168        0
169    };
170    let written = prefix + write_payload(value, &Budget::new(limits), 1, &mut output[prefix..])?;
171
172    Ok(&output[..written])
173}
174
175pub(super) fn write_payload<T: Serialize + ?Sized>(
176    value: &T,
177    budget: &Budget,
178    depth: usize,
179    output: &mut [u8],
180) -> Result<usize, Error> {
181    postcard::to_slice(
182        &admitted::Bounded {
183            value,
184            budget,
185            depth,
186        },
187        output,
188    )
189    .map(|payload| payload.len())
190    .map_err(|_| budget.error())
191}
192
193#[cfg(feature = "evolution")]
194pub(super) fn write_scratch<T: Serialize + ?Sized>(
195    value: &T,
196    budget: &Budget,
197    depth: usize,
198    output: &mut [u8],
199    capacity_kind: crate::LimitKind,
200) -> Result<usize, Error> {
201    write_bounded_slice::<T, true>(value, budget, depth, output, capacity_kind)
202}
203
204#[cfg(feature = "evolution")]
205pub(super) fn write_bounded_slice<T: Serialize + ?Sized, const CHARGE_SCRATCH: bool>(
206    value: &T,
207    budget: &Budget,
208    depth: usize,
209    output: &mut [u8],
210    capacity_kind: crate::LimitKind,
211) -> Result<usize, Error> {
212    let initial_len = output.len();
213    let result = postcard::serialize_with_flavor(
214        &admitted::Bounded {
215            value,
216            budget,
217            depth,
218        },
219        BoundedSlice::<CHARGE_SCRATCH> {
220            output,
221            budget,
222            capacity_kind,
223            initial_len,
224        },
225    );
226    budget.check()?;
227    result.map_err(|_| Error::Malformed)
228}
229
230// Final output uses the meter's configured byte reservation. Additional
231// staging writes debit the remaining allocation allowance.
232#[cfg(feature = "evolution")]
233struct BoundedSlice<'a, 'budget, const CHARGE_SCRATCH: bool> {
234    output: &'a mut [u8],
235    budget: &'budget Budget,
236    capacity_kind: crate::LimitKind,
237    initial_len: usize,
238}
239
240#[cfg(feature = "evolution")]
241impl<const CHARGE_SCRATCH: bool> BoundedSlice<'_, '_, CHARGE_SCRATCH> {
242    #[inline]
243    fn take(&mut self, len: usize) -> postcard::Result<&mut [u8]> {
244        let Some((head, rest)) = core::mem::take(&mut self.output).split_at_mut_checked(len) else {
245            self.budget.refuse_with(self.capacity_kind);
246            return Err(postcard::Error::SerializeBufferFull);
247        };
248        if CHARGE_SCRATCH && !self.budget.charge_buffer(len) {
249            return Err(postcard::Error::SerializeBufferFull);
250        }
251        self.output = rest;
252        Ok(head)
253    }
254}
255
256#[cfg(feature = "evolution")]
257impl<const CHARGE_SCRATCH: bool> Flavor for BoundedSlice<'_, '_, CHARGE_SCRATCH> {
258    type Output = usize;
259
260    #[inline]
261    fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
262        self.take(1)?[0] = byte;
263        Ok(())
264    }
265
266    #[inline]
267    fn try_extend(&mut self, bytes: &[u8]) -> postcard::Result<()> {
268        self.take(bytes.len())?.copy_from_slice(bytes);
269        Ok(())
270    }
271
272    fn finalize(self) -> postcard::Result<Self::Output> {
273        Ok(self.initial_len - self.output.len())
274    }
275}
276
277// Allocation capacity is not admission: every write is capped at preflight size.
278enum Output<'a> {
279    Count(usize),
280    Buffer {
281        bytes: &'a mut Vec<u8>,
282        limit: usize,
283    },
284}
285
286impl Flavor for Output<'_> {
287    type Output = usize;
288
289    fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
290        match self {
291            Self::Count(size) => {
292                *size = size
293                    .checked_add(1)
294                    .ok_or(postcard::Error::SerializeBufferFull)?
295            }
296            Self::Buffer { bytes, limit } => {
297                if bytes.len() >= *limit {
298                    return Err(postcard::Error::SerializeBufferFull);
299                }
300                bytes.push(byte);
301            }
302        }
303        Ok(())
304    }
305
306    fn try_extend(&mut self, span: &[u8]) -> postcard::Result<()> {
307        match self {
308            Self::Count(size) => {
309                *size = size
310                    .checked_add(span.len())
311                    .ok_or(postcard::Error::SerializeBufferFull)?
312            }
313            Self::Buffer { bytes, limit } => {
314                if span.len() > *limit - bytes.len() {
315                    return Err(postcard::Error::SerializeBufferFull);
316                }
317                bytes.extend_from_slice(span);
318            }
319        }
320        Ok(())
321    }
322
323    fn finalize(self) -> postcard::Result<Self::Output> {
324        Ok(match self {
325            Self::Count(size) => size,
326            Self::Buffer { bytes, .. } => bytes.len(),
327        })
328    }
329}