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