ic-wire 0.33.0

Bounded Serde/Postcard encoding with schema and TypeScript generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Typed request and reply framing over the evolutionary codec.

use crate::{Direction, Encoding, Error, Limits, method_id};
use alloc::vec::Vec;
use core::marker::PhantomData;

use super::inline::InlineMessage;

/// A value with typed encoding and projection through the evolutionary codec.
///
/// Decoded values may borrow from the frame or payload for `'de`.
/// Both directions must use a sparse message root.
pub trait Evolving<'de>: Sized {
    /// Encode one complete value into reusable output.
    ///
    /// # Errors
    /// Returns an encoding or admission error and leaves output empty.
    fn encode_evolving(
        &self,
        output: &mut Vec<u8>,
        encoding: Encoding,
        limits: Limits,
    ) -> Result<(), Error>;

    /// Decode and project one complete frame or payload from the given input.
    ///
    /// # Errors
    /// Returns a framing, decoding, incompatibility, or admission error.
    fn decode_evolving(input: &'de [u8], encoding: Encoding, limits: Limits)
    -> Result<Self, Error>;
}

/// Encode a complete Wire message into owned output.
///
/// # Errors
/// Returns the first preparation, encoding or allowance failure.
pub fn encode<'de, T: Evolving<'de>>(
    value: &T,
    encoding: Encoding,
    limits: Limits,
) -> Result<Vec<u8>, Error> {
    let mut output = Vec::new();
    encode_into(value, encoding, limits, &mut output)?;
    Ok(output)
}

/// Encode a complete Wire message into reusable output.
///
/// # Errors
/// Returns the first preparation, encoding or allowance failure. Output is
/// empty on error.
pub fn encode_into<'out, 'de, T: Evolving<'de>>(
    value: &T,
    encoding: Encoding,
    limits: Limits,
    output: &'out mut Vec<u8>,
) -> Result<&'out [u8], Error> {
    output.clear();
    if let Err(error) = value.encode_evolving(output, encoding, limits) {
        output.clear();
        return Err(error);
    }
    Ok(output)
}

/// Measure a derived message using its sparse projection and shared budget.
///
/// # Errors
/// Returns projection, serialization and admission errors.
pub fn encoded_len<'de, T: InlineMessage<'de>>(
    value: &T,
    encoding: Encoding,
    limits: Limits,
) -> Result<usize, Error> {
    let prefix = super::writer::frame_header(encoding).map_or(0, |_| crate::framing::HEADER_BYTES);
    let limits = limits.without_prefix(prefix)?;
    let budget = crate::meter::Budget::new(limits);
    budget.check()?;
    let context = super::WriteContext {
        budget: &budget,
        depth: 1,
        byte_limit: limits.bytes,
    };
    let mut length = 0;
    super::inline::with_scratch(T::MAY_STAGE, &budget, |scratch| {
        let (prepared, _) = value.prepare(&context, scratch)?;
        budget.check()?;
        length = super::writer::projected_size(&prepared, &budget, limits.bytes)?;
        Ok(())
    })?;
    budget.check()?;
    Ok(length + prefix)
}

/// Encode a derived Wire message directly into caller-owned output.
///
/// Use [`crate::evolution::encode_projected_to_slice`] for a manually
/// projected message. A fixed nested layout can implement `Evolving` with
/// a different root layout, so those bounds alone cannot select the slice
/// representation.
///
/// ```compile_fail,E0277
/// use ic_wire::{Encoding, Evolving, Limits, evolution::encode_to_slice};
/// use ic_wire::evolution::inline::Fixed;
/// use serde::{Deserialize, Serialize};
///
/// fn write_slice<'de, T>(value: &T, limits: Limits, output: &mut [u8])
/// where
///     T: Evolving<'de> + Fixed + Serialize + Deserialize<'de>,
/// {
///     encode_to_slice(value, Encoding::Payload, limits, output).unwrap();
/// }
/// ```
///
/// # Errors
/// Returns a preparation, encoding, allowance or destination capacity error.
/// A failed write may modify the destination. Only the prefix returned on
/// success contains a complete message.
pub fn encode_to_slice<'out, 'de, T: InlineMessage<'de>>(
    value: &T,
    encoding: Encoding,
    limits: Limits,
    output: &'out mut [u8],
) -> Result<&'out [u8], Error> {
    super::encode_value_to_slice_with(output, encoding, limits, |mut destination| {
        let context = destination.context();
        super::inline::with_scratch(T::MAY_STAGE, context.budget, |scratch| {
            let (prepared, _) = value.prepare(&context, scratch)?;
            destination.write_value(&prepared)
        })
    })
}

/// Admit and decode one complete Wire message with its typed projection.
///
/// # Errors
/// Returns a framing, decoding, compatibility or allowance error.
pub fn decode<'de, T: Evolving<'de>>(
    input: &'de [u8],
    encoding: Encoding,
    limits: Limits,
) -> Result<T, Error> {
    T::decode_evolving(input, encoding, limits)
}

/// Bind an export name, direction limits and Rust DTOs to Wire frames.
///
/// An application can infer the lifetimes of borrowing DTOs locally with a type
/// such as `Method<Request<'_>, Reply<'_>>`.
pub struct Method<Request, Reply> {
    name: &'static str,
    id: u64,
    request_limits: Limits,
    reply_limits: Limits,
    types: PhantomData<fn() -> (Request, Reply)>,
}

impl<Request, Reply> Method<Request, Reply> {
    /// Define the Wire method for the exact exported name.
    ///
    /// A `const` descriptor computes the routing ID at compile time. The
    /// configured byte limits include the frame header in each direction.
    #[must_use]
    pub const fn new(name: &'static str, request_limits: Limits, reply_limits: Limits) -> Self {
        Self {
            name,
            id: method_id(name),
            request_limits,
            reply_limits,
            types: PhantomData,
        }
    }

    /// Get the exact exported name.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// Get the routing ID derived from the exported name.
    #[must_use]
    pub const fn id(&self) -> u64 {
        self.id
    }

    /// Get the request limits.
    #[must_use]
    pub const fn request_limits(&self) -> Limits {
        self.request_limits
    }

    /// Get the reply limits.
    #[must_use]
    pub const fn reply_limits(&self) -> Limits {
        self.reply_limits
    }

    /// Encode a request frame into reusable output.
    ///
    /// # Errors
    /// Returns an encoding or request admission error.
    pub fn encode_request<'de>(&self, value: &Request, output: &mut Vec<u8>) -> Result<(), Error>
    where
        Request: Evolving<'de>,
    {
        encode_into(
            value,
            self.encoding(Direction::Request),
            self.request_limits,
            output,
        )
        .map(|_| ())
    }

    /// Decode a request frame for this method.
    ///
    /// # Errors
    /// Returns a framing, decoding, incompatibility, or request admission error.
    pub fn decode_request<'de>(&self, input: &'de [u8]) -> Result<Request, Error>
    where
        Request: Evolving<'de>,
    {
        decode(
            input,
            self.encoding(Direction::Request),
            self.request_limits,
        )
    }

    /// Encode a reply frame into reusable output.
    ///
    /// # Errors
    /// Returns an encoding or reply admission error.
    pub fn encode_reply<'de>(&self, value: &Reply, output: &mut Vec<u8>) -> Result<(), Error>
    where
        Reply: Evolving<'de>,
    {
        encode_into(
            value,
            self.encoding(Direction::Response),
            self.reply_limits,
            output,
        )
        .map(|_| ())
    }

    /// Decode a reply frame for this method.
    ///
    /// # Errors
    /// Returns a framing, decoding, incompatibility, or reply admission error.
    pub fn decode_reply<'de>(&self, input: &'de [u8]) -> Result<Reply, Error>
    where
        Reply: Evolving<'de>,
    {
        decode(input, self.encoding(Direction::Response), self.reply_limits)
    }

    const fn encoding(&self, direction: Direction) -> Encoding {
        Encoding::Frame {
            method: self.id,
            direction,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::evolution::{
        Projected, decode_projected, encode_projected_into, encode_projected_to_slice,
        inline::Fixed,
    };
    use crate::{LimitKind, TextRef};
    use serde::{Deserialize, Serialize};

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct Request<'a>(#[serde(borrow)] TextRef<'a, 16>);

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct Reply(u16);

    impl Fixed for Reply {}

    impl<'de: 'a, 'a> Evolving<'de> for Request<'a> {
        fn encode_evolving(
            &self,
            output: &mut Vec<u8>,
            encoding: Encoding,
            limits: Limits,
        ) -> Result<(), Error> {
            encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
                .map(|_| ())
        }

        fn decode_evolving(
            input: &'de [u8],
            encoding: Encoding,
            limits: Limits,
        ) -> Result<Self, Error> {
            decode_projected(
                input,
                encoding,
                limits,
                |root: Projected<'_, Self>, context| {
                    root.extensions.visit(context, |_, _| Ok(()))?;
                    Ok(root.core)
                },
            )
        }
    }

    impl<'de> Evolving<'de> for Reply {
        fn encode_evolving(
            &self,
            output: &mut Vec<u8>,
            encoding: Encoding,
            limits: Limits,
        ) -> Result<(), Error> {
            encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
                .map(|_| ())
        }

        fn decode_evolving(
            input: &'de [u8],
            encoding: Encoding,
            limits: Limits,
        ) -> Result<Self, Error> {
            decode_projected(
                input,
                encoding,
                limits,
                |root: Projected<'_, Self>, context| {
                    root.extensions.visit(context, |_, _| Ok(()))?;
                    Ok(root.core)
                },
            )
        }
    }

    const REQUEST_LIMITS: Limits = Limits {
        bytes: 64,
        allocation: 4096,
        nodes: 64,
        depth: 16,
    };
    const REPLY_LIMITS: Limits = Limits {
        bytes: 13,
        ..REQUEST_LIMITS
    };
    const LOOKUP: Method<Request<'static>, Reply> =
        Method::new("lookup", REQUEST_LIMITS, REPLY_LIMITS);

    #[test]
    fn typed_methods_round_trip_borrowed_requests_and_check_identity() {
        assert_eq!(LOOKUP.name(), "lookup");
        assert_eq!(LOOKUP.id(), method_id("lookup"));
        assert_eq!(LOOKUP.request_limits().bytes, 64);
        assert_eq!(LOOKUP.reply_limits().bytes, 13);

        let value = alloc::string::String::from("hello");
        let mut input = Vec::new();
        let method: Method<Request<'_>, Reply> = LOOKUP;
        method
            .encode_request(&Request(TextRef::new(&value).unwrap()), &mut input)
            .unwrap();
        let decoded = method.decode_request(&input).unwrap();
        assert_eq!(decoded.0.as_str(), "hello");
        assert_eq!(decoded.0.as_str().as_bytes().as_ptr(), input[12..].as_ptr());

        let other = Method::<Request<'_>, Reply>::new("other", REQUEST_LIMITS, REPLY_LIMITS);
        assert_eq!(other.decode_request(&input), Err(Error::Identity));
        let mut reply = Vec::new();
        method.encode_reply(&Reply(7), &mut reply).unwrap();
        assert_eq!(reply[10..], [1, 7, 0]);
        assert_eq!(method.decode_reply(&reply), Ok(Reply(7)));
        assert_eq!(method.decode_request(&reply), Err(Error::Identity));
    }

    #[test]
    fn reply_limits_apply_to_both_encoding_and_decoding() {
        let mut reply = alloc::vec![1, 2, 3];
        assert_eq!(
            LOOKUP.encode_reply(&Reply(128), &mut reply),
            Err(Error::Limit(LimitKind::Bytes))
        );
        assert!(reply.is_empty());
        let large = encode(
            &Reply(128),
            Encoding::Frame {
                method: LOOKUP.id(),
                direction: Direction::Response,
            },
            REQUEST_LIMITS,
        )
        .unwrap();
        assert_eq!(
            LOOKUP.decode_reply(&large),
            Err(Error::Limit(LimitKind::Bytes))
        );
    }

    #[test]
    fn fixed_nested_reply_uses_its_explicit_projection_at_the_root() {
        let value = Reply(42);
        let encoding = Encoding::Payload;
        let owned = encode(&value, encoding, REPLY_LIMITS).unwrap();
        let mut output = [0; 2];
        let slice = encode_projected_to_slice(&mut output, encoding, REPLY_LIMITS, |_| {
            Ok(Projected::empty(&value))
        })
        .unwrap();
        assert_eq!(slice, [42, 0]);
        assert_eq!(slice, owned);
        assert_eq!(decode::<Reply>(slice, encoding, REPLY_LIMITS), Ok(value));
    }
}