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