Skip to main content

ic_wire/evolution/
method.rs

1//! Typed request and reply framing over the evolutionary codec.
2
3use crate::{Direction, Encoding, Error, Limits, method_id};
4use alloc::vec::Vec;
5use core::marker::PhantomData;
6
7use super::inline::InlineMessage;
8
9/// A value with typed encoding and projection through the evolutionary codec.
10///
11/// Decoded values may borrow from the frame or payload for `'de`.
12/// Both directions must use a sparse message root.
13pub trait Evolving<'de>: Sized {
14    /// Encode one complete value into reusable output.
15    ///
16    /// # Errors
17    /// Returns an encoding or admission error and leaves output empty.
18    fn encode_evolving(
19        &self,
20        output: &mut Vec<u8>,
21        encoding: Encoding,
22        limits: Limits,
23    ) -> Result<(), Error>;
24
25    /// Decode and project one complete frame or payload from the given input.
26    ///
27    /// # Errors
28    /// Returns a framing, decoding, incompatibility, or admission error.
29    fn decode_evolving(input: &'de [u8], encoding: Encoding, limits: Limits)
30    -> Result<Self, Error>;
31}
32
33/// Encode a complete Wire message into owned output.
34///
35/// # Errors
36/// Returns the first preparation, encoding or allowance failure.
37pub fn encode<'de, T: Evolving<'de>>(
38    value: &T,
39    encoding: Encoding,
40    limits: Limits,
41) -> Result<Vec<u8>, Error> {
42    let mut output = Vec::new();
43    encode_into(value, encoding, limits, &mut output)?;
44    Ok(output)
45}
46
47/// Encode a complete Wire message into reusable output.
48///
49/// # Errors
50/// Returns the first preparation, encoding or allowance failure. Output is
51/// empty on error.
52pub fn encode_into<'out, 'de, T: Evolving<'de>>(
53    value: &T,
54    encoding: Encoding,
55    limits: Limits,
56    output: &'out mut Vec<u8>,
57) -> Result<&'out [u8], Error> {
58    output.clear();
59    if let Err(error) = value.encode_evolving(output, encoding, limits) {
60        output.clear();
61        return Err(error);
62    }
63    Ok(output)
64}
65
66/// Encode a derived Wire message directly into caller-owned output.
67///
68/// Use [`crate::evolution::encode_projected_to_slice`] for a manually
69/// projected message. A fixed nested layout can implement `Evolving` with
70/// a different root layout, so those bounds alone cannot select the slice
71/// representation.
72///
73/// ```compile_fail,E0277
74/// use ic_wire::{Encoding, Evolving, Limits, evolution::encode_to_slice};
75/// use ic_wire::evolution::inline::Fixed;
76/// use serde::{Deserialize, Serialize};
77///
78/// fn write_slice<'de, T>(value: &T, limits: Limits, output: &mut [u8])
79/// where
80///     T: Evolving<'de> + Fixed + Serialize + Deserialize<'de>,
81/// {
82///     encode_to_slice(value, Encoding::Payload, limits, output).unwrap();
83/// }
84/// ```
85///
86/// # Errors
87/// Returns a preparation, encoding, allowance or destination capacity error.
88/// A failed write may modify the destination. Only the prefix returned on
89/// success contains a complete message.
90pub fn encode_to_slice<'out, 'de, T: InlineMessage<'de>>(
91    value: &T,
92    encoding: Encoding,
93    limits: Limits,
94    output: &'out mut [u8],
95) -> Result<&'out [u8], Error> {
96    super::encode_value_to_slice_with(output, encoding, limits, |mut destination| {
97        let context = destination.context();
98        super::inline::with_scratch(T::MAY_STAGE, context.budget, |scratch| {
99            let (prepared, _) = value.prepare(&context, scratch)?;
100            destination.write_value(&prepared)
101        })
102    })
103}
104
105/// Admit and decode one complete Wire message with its typed projection.
106///
107/// # Errors
108/// Returns a framing, decoding, compatibility or allowance error.
109pub fn decode<'de, T: Evolving<'de>>(
110    input: &'de [u8],
111    encoding: Encoding,
112    limits: Limits,
113) -> Result<T, Error> {
114    T::decode_evolving(input, encoding, limits)
115}
116
117/// Bind an export name, direction limits and Rust DTOs to Wire frames.
118///
119/// An application can infer the lifetimes of borrowing DTOs locally with a type
120/// such as `Method<Request<'_>, Reply<'_>>`.
121pub struct Method<Request, Reply> {
122    name: &'static str,
123    id: u64,
124    request_limits: Limits,
125    reply_limits: Limits,
126    types: PhantomData<fn() -> (Request, Reply)>,
127}
128
129impl<Request, Reply> Method<Request, Reply> {
130    /// Define the Wire method for the exact exported name.
131    ///
132    /// A `const` descriptor computes the routing ID at compile time. The
133    /// configured byte limits include the frame header in each direction.
134    #[must_use]
135    pub const fn new(name: &'static str, request_limits: Limits, reply_limits: Limits) -> Self {
136        Self {
137            name,
138            id: method_id(name),
139            request_limits,
140            reply_limits,
141            types: PhantomData,
142        }
143    }
144
145    /// Get the exact exported name.
146    #[must_use]
147    pub const fn name(&self) -> &'static str {
148        self.name
149    }
150
151    /// Get the routing ID derived from the exported name.
152    #[must_use]
153    pub const fn id(&self) -> u64 {
154        self.id
155    }
156
157    /// Get the request limits.
158    #[must_use]
159    pub const fn request_limits(&self) -> Limits {
160        self.request_limits
161    }
162
163    /// Get the reply limits.
164    #[must_use]
165    pub const fn reply_limits(&self) -> Limits {
166        self.reply_limits
167    }
168
169    /// Encode a request frame into reusable output.
170    ///
171    /// # Errors
172    /// Returns an encoding or request admission error.
173    pub fn encode_request<'de>(&self, value: &Request, output: &mut Vec<u8>) -> Result<(), Error>
174    where
175        Request: Evolving<'de>,
176    {
177        encode_into(
178            value,
179            self.encoding(Direction::Request),
180            self.request_limits,
181            output,
182        )
183        .map(|_| ())
184    }
185
186    /// Decode a request frame for this method.
187    ///
188    /// # Errors
189    /// Returns a framing, decoding, incompatibility, or request admission error.
190    pub fn decode_request<'de>(&self, input: &'de [u8]) -> Result<Request, Error>
191    where
192        Request: Evolving<'de>,
193    {
194        decode(
195            input,
196            self.encoding(Direction::Request),
197            self.request_limits,
198        )
199    }
200
201    /// Encode a reply frame into reusable output.
202    ///
203    /// # Errors
204    /// Returns an encoding or reply admission error.
205    pub fn encode_reply<'de>(&self, value: &Reply, output: &mut Vec<u8>) -> Result<(), Error>
206    where
207        Reply: Evolving<'de>,
208    {
209        encode_into(
210            value,
211            self.encoding(Direction::Response),
212            self.reply_limits,
213            output,
214        )
215        .map(|_| ())
216    }
217
218    /// Decode a reply frame for this method.
219    ///
220    /// # Errors
221    /// Returns a framing, decoding, incompatibility, or reply admission error.
222    pub fn decode_reply<'de>(&self, input: &'de [u8]) -> Result<Reply, Error>
223    where
224        Reply: Evolving<'de>,
225    {
226        decode(input, self.encoding(Direction::Response), self.reply_limits)
227    }
228
229    const fn encoding(&self, direction: Direction) -> Encoding {
230        Encoding::Frame {
231            method: self.id,
232            direction,
233        }
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use crate::evolution::{
241        Projected, decode_projected, encode_projected_into, encode_projected_to_slice,
242        inline::Fixed,
243    };
244    use crate::{LimitKind, TextRef};
245    use serde::{Deserialize, Serialize};
246
247    #[derive(Debug, PartialEq, Serialize, Deserialize)]
248    struct Request<'a>(#[serde(borrow)] TextRef<'a, 16>);
249
250    #[derive(Debug, PartialEq, Serialize, Deserialize)]
251    struct Reply(u16);
252
253    impl Fixed for Reply {}
254
255    impl<'de: 'a, 'a> Evolving<'de> for Request<'a> {
256        fn encode_evolving(
257            &self,
258            output: &mut Vec<u8>,
259            encoding: Encoding,
260            limits: Limits,
261        ) -> Result<(), Error> {
262            encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
263                .map(|_| ())
264        }
265
266        fn decode_evolving(
267            input: &'de [u8],
268            encoding: Encoding,
269            limits: Limits,
270        ) -> Result<Self, Error> {
271            decode_projected(
272                input,
273                encoding,
274                limits,
275                |root: Projected<'_, Self>, context| {
276                    root.extensions.visit(context, |_, _| Ok(()))?;
277                    Ok(root.core)
278                },
279            )
280        }
281    }
282
283    impl<'de> Evolving<'de> for Reply {
284        fn encode_evolving(
285            &self,
286            output: &mut Vec<u8>,
287            encoding: Encoding,
288            limits: Limits,
289        ) -> Result<(), Error> {
290            encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
291                .map(|_| ())
292        }
293
294        fn decode_evolving(
295            input: &'de [u8],
296            encoding: Encoding,
297            limits: Limits,
298        ) -> Result<Self, Error> {
299            decode_projected(
300                input,
301                encoding,
302                limits,
303                |root: Projected<'_, Self>, context| {
304                    root.extensions.visit(context, |_, _| Ok(()))?;
305                    Ok(root.core)
306                },
307            )
308        }
309    }
310
311    const REQUEST_LIMITS: Limits = Limits {
312        bytes: 64,
313        allocation: 4096,
314        nodes: 64,
315        depth: 16,
316    };
317    const REPLY_LIMITS: Limits = Limits {
318        bytes: 13,
319        ..REQUEST_LIMITS
320    };
321    const LOOKUP: Method<Request<'static>, Reply> =
322        Method::new("lookup", REQUEST_LIMITS, REPLY_LIMITS);
323
324    #[test]
325    fn typed_methods_round_trip_borrowed_requests_and_check_identity() {
326        assert_eq!(LOOKUP.name(), "lookup");
327        assert_eq!(LOOKUP.id(), method_id("lookup"));
328        assert_eq!(LOOKUP.request_limits().bytes, 64);
329        assert_eq!(LOOKUP.reply_limits().bytes, 13);
330
331        let value = alloc::string::String::from("hello");
332        let mut input = Vec::new();
333        let method: Method<Request<'_>, Reply> = LOOKUP;
334        method
335            .encode_request(&Request(TextRef::new(&value).unwrap()), &mut input)
336            .unwrap();
337        let decoded = method.decode_request(&input).unwrap();
338        assert_eq!(decoded.0.as_str(), "hello");
339        assert_eq!(decoded.0.as_str().as_bytes().as_ptr(), input[12..].as_ptr());
340
341        let other = Method::<Request<'_>, Reply>::new("other", REQUEST_LIMITS, REPLY_LIMITS);
342        assert_eq!(other.decode_request(&input), Err(Error::Identity));
343        let mut reply = Vec::new();
344        method.encode_reply(&Reply(7), &mut reply).unwrap();
345        assert_eq!(reply[10..], [1, 7, 0]);
346        assert_eq!(method.decode_reply(&reply), Ok(Reply(7)));
347        assert_eq!(method.decode_request(&reply), Err(Error::Identity));
348    }
349
350    #[test]
351    fn reply_limits_apply_to_both_encoding_and_decoding() {
352        let mut reply = alloc::vec![1, 2, 3];
353        assert_eq!(
354            LOOKUP.encode_reply(&Reply(128), &mut reply),
355            Err(Error::Limit(LimitKind::Bytes))
356        );
357        assert!(reply.is_empty());
358        let large = encode(
359            &Reply(128),
360            Encoding::Frame {
361                method: LOOKUP.id(),
362                direction: Direction::Response,
363            },
364            REQUEST_LIMITS,
365        )
366        .unwrap();
367        assert_eq!(
368            LOOKUP.decode_reply(&large),
369            Err(Error::Limit(LimitKind::Bytes))
370        );
371    }
372
373    #[test]
374    fn fixed_nested_reply_uses_its_explicit_projection_at_the_root() {
375        let value = Reply(42);
376        let encoding = Encoding::Payload;
377        let owned = encode(&value, encoding, REPLY_LIMITS).unwrap();
378        let mut output = [0; 2];
379        let slice = encode_projected_to_slice(&mut output, encoding, REPLY_LIMITS, |_| {
380            Ok(Projected::empty(&value))
381        })
382        .unwrap();
383        assert_eq!(slice, [42, 0]);
384        assert_eq!(slice, owned);
385        assert_eq!(decode::<Reply>(slice, encoding, REPLY_LIMITS), Ok(value));
386    }
387}