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