ic-wire 0.33.1

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
417
418
419
420
421
422
423
424
425
426
//! Stock Serde projections used by derived Wire messages.

#[cfg(test)]
use super::encode_value_into;
use super::{
    Evolving, ReadContext, WriteContext, decode_value, encode_value_into_with, write_value_into,
};
use crate::{Encoding, Error, LimitKind, Limits, meter::Budget};
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

mod containers;

/// A leaf that uses its ordinary Serde representation inside evolving values.
///
/// Derives and the built-in fields supply this marker. The complete Serde value
/// is a fixed contract, including any nested contents it serializes itself.
pub trait Fixed {}

/// Compose a typed value with the Serde projections of its children.
///
/// The derive builds a transport view without replacing the application's own
/// Serde implementations. Borrowed reader and writer views retain their storage.
pub trait Inline<'de>: Sized {
    /// True when preparing this shape can write extension bytes.
    #[doc(hidden)]
    const MAY_STAGE: bool = true;

    /// The staged Serde value and its borrowed application data or scratch.
    type Encoded<'s>: Serialize
    where
        Self: 's;

    /// The raw Serde value to project with the enclosing read context.
    type Decoded: Deserialize<'de>;

    /// Stage this value and return the unused suffix of the supplied scratch.
    ///
    /// # Errors
    /// Propagates resource, scratch and nested value serialization failures.
    fn prepare<'s>(
        &'s self,
        context: &WriteContext<'_>,
        scratch: &'s mut [u8],
    ) -> Result<(Self::Encoded<'s>, &'s mut [u8]), Error>;

    /// Validate nested envelopes and construct the application value.
    ///
    /// # Errors
    /// Propagates structural, compatibility and resource failures.
    fn project(input: Self::Decoded, context: &ReadContext<'_>) -> Result<Self, Error>;
}

/// A typed message whose inline projection includes the sparse root.
///
/// Deriving `Wire` on an evolving struct supplies this implementation. The
/// inline projection must use the same root layout as its `Evolving`
/// implementation.
pub trait InlineMessage<'de>: Evolving<'de> + Inline<'de> {}

impl<'de, T: Fixed + Serialize + Deserialize<'de>> Inline<'de> for T {
    const MAY_STAGE: bool = false;

    type Encoded<'s>
        = &'s T
    where
        Self: 's;
    type Decoded = T;

    fn prepare<'s>(
        &'s self,
        _: &WriteContext<'_>,
        scratch: &'s mut [u8],
    ) -> Result<(Self::Encoded<'s>, &'s mut [u8]), Error> {
        Ok((self, scratch))
    }

    fn project(input: Self::Decoded, _: &ReadContext<'_>) -> Result<Self, Error> {
        Ok(input)
    }
}

/// Record an incompatibility so known siblings still receive validation.
///
/// # Errors
/// Propagates hard failures immediately.
pub fn preserve_incompatible<T>(
    result: Result<T, Error>,
    incompatible: &mut bool,
) -> Result<Option<T>, Error> {
    match result {
        Ok(value) => Ok(Some(value)),
        Err(Error::Incompatible) => {
            *incompatible = true;
            Ok(None)
        }
        Err(error) => Err(error),
    }
}

/// Sorted extension destinations for a derived sparse record.
#[doc(hidden)]
pub trait FieldTargets<'de> {
    /// Assign a bounded field to its declared destination, if present.
    ///
    /// # Errors
    /// Propagates structural and resource failures from known fields.
    fn assign(
        &mut self,
        id: u32,
        field: super::Field<'_, 'de>,
        incompatible: &mut bool,
    ) -> Result<(), Error>;
}

impl<'de> FieldTargets<'de> for () {
    fn assign(&mut self, _: u32, _: super::Field<'_, 'de>, _: &mut bool) -> Result<(), Error> {
        Ok(())
    }
}

impl<'de, T: Inline<'de>> FieldTargets<'de> for (u32, &mut Option<T>) {
    fn assign(
        &mut self,
        id: u32,
        field: super::Field<'_, 'de>,
        incompatible: &mut bool,
    ) -> Result<(), Error> {
        if id == self.0 {
            *self.1 = preserve_incompatible(field.project_inline::<T>(), incompatible)?;
        }
        Ok(())
    }
}

impl<'de, L: FieldTargets<'de>, R: FieldTargets<'de>> FieldTargets<'de> for (u32, L, R) {
    fn assign(
        &mut self,
        id: u32,
        field: super::Field<'_, 'de>,
        incompatible: &mut bool,
    ) -> Result<(), Error> {
        if id < self.0 {
            self.1.assign(id, field, incompatible)
        } else {
            self.2.assign(id, field, incompatible)
        }
    }
}

/// Validate the block and fill its known destinations.
///
/// # Errors
/// Propagates structural and resource failures in input order.
#[doc(hidden)]
#[inline(never)]
pub fn read_fields<'de>(
    extensions: super::Extensions<'de>,
    context: &ReadContext<'_>,
    mut targets: impl FieldTargets<'de>,
    incompatible: &mut bool,
) -> Result<(), Error> {
    extensions.visit(context, |id, field| targets.assign(id, field, incompatible))
}

/// Stage and encode an inline value into the existing projected frame path.
///
/// # Errors
/// Returns the first projection, encoding or admission error. Output is empty
/// on failure.
#[doc(hidden)]
pub fn encode<'de, T: InlineMessage<'de>>(
    value: &T,
    output: &mut Vec<u8>,
    encoding: Encoding,
    limits: Limits,
) -> Result<(), Error> {
    type FrameWriter<'a> = dyn FnMut(
            &mut Vec<u8>,
            Option<[u8; crate::framing::HEADER_BYTES]>,
            &WriteContext<'_>,
        ) -> Result<(), Error>
        + 'a;
    let write: &mut FrameWriter<'_> = &mut |output, header, context| {
        with_scratch(T::MAY_STAGE, context.budget, |scratch| {
            let (prepared, _) = value.prepare(context, scratch)?;
            context.budget.check()?;
            write_value_into(output, header, context, &prepared)
        })
    };
    encode_value_into_with(output, encoding, limits, write).map(|_| ())
}

const STACK_SCRATCH: usize = 32;
const INITIAL_HEAP_SCRATCH: usize = 256;

pub(super) fn with_scratch(
    may_stage: bool,
    budget: &Budget,
    mut encode: impl FnMut(&mut [u8]) -> Result<(), Error>,
) -> Result<(), Error> {
    if !may_stage {
        return encode(&mut []);
    }
    with_staging_scratch(budget, &mut encode)
}

#[inline(never)]
fn with_staging_scratch(
    budget: &Budget,
    encode: &mut dyn FnMut(&mut [u8]) -> Result<(), Error>,
) -> Result<(), Error> {
    let mut allocation_checkpoint = budget.scratch_headroom();
    let mut stack = [0; STACK_SCRATCH];
    let outcome = encode(&mut stack);
    if outcome != Err(Error::Limit(LimitKind::Scratch)) {
        return outcome;
    }
    let mut scratch = Vec::new();
    loop {
        grow_scratch(budget, &mut scratch, &mut allocation_checkpoint)?;
        let outcome = encode(&mut scratch);
        if outcome != Err(Error::Limit(LimitKind::Scratch)) {
            return outcome;
        }
    }
}

#[cold]
#[inline(never)]
fn grow_scratch(
    budget: &Budget,
    scratch: &mut Vec<u8>,
    allocation_checkpoint: &mut usize,
) -> Result<(), Error> {
    budget.resume_after_scratch(*allocation_checkpoint);
    budget.check()?;
    let size = scratch.len().max(STACK_SCRATCH);
    let capacity = scratch.capacity();
    let available = capacity.saturating_add(budget.scratch_headroom());
    let next = size
        .saturating_mul(2)
        .max(INITIAL_HEAP_SCRATCH)
        .min(available);
    if next <= size || !budget.charge_buffer(next.saturating_sub(capacity).div_ceil(8)) {
        return Err(budget.refuse_with(LimitKind::Allocation));
    }
    scratch
        .try_reserve_exact(next - scratch.len())
        .map_err(|_| Error::Allocation)?;
    let extra = scratch.capacity().saturating_sub(capacity.max(next));
    if extra != 0 && !budget.charge_buffer(extra.div_ceil(8)) {
        return Err(budget.error());
    }
    *allocation_checkpoint = budget.scratch_headroom();
    scratch.resize(next, 0);
    Ok(())
}

#[cfg(test)]
fn encode_inline<'de, T: Inline<'de>>(
    value: &T,
    output: &mut Vec<u8>,
    encoding: Encoding,
    limits: Limits,
    scratch: &mut [u8],
) -> Result<(), Error> {
    encode_value_into(output, encoding, limits, |context| {
        let (value, _) = value.prepare(context, scratch)?;
        Ok(value)
    })
    .map(|_| ())
}

/// Decode and project an inline value with one shared resource meter.
///
/// # Errors
/// Returns a frame, known value, payload or admission error.
#[doc(hidden)]
pub fn decode<'de, T: InlineMessage<'de>>(
    input: &'de [u8],
    encoding: Encoding,
    limits: Limits,
) -> Result<T, Error> {
    decode_inline(input, encoding, limits)
}

fn decode_inline<'de, T: Inline<'de>>(
    input: &'de [u8],
    encoding: Encoding,
    limits: Limits,
) -> Result<T, Error> {
    decode_value(input, encoding, limits, T::project)
}

#[cfg(test)]
mod tests {
    use super::super::{Extensions, ExtensionsWriter};
    use super::*;

    #[test]
    fn retry_charges_preparation_to_the_same_node_allowance() {
        let budget = Budget::new(Limits {
            bytes: 512,
            allocation: 4096,
            nodes: 1,
            depth: 1,
        });
        let result = with_scratch(true, &budget, |scratch| {
            if !budget.enter_scope(1) {
                return Err(budget.error());
            }
            if scratch.len() == STACK_SCRATCH {
                return Err(budget.refuse_with(LimitKind::Scratch));
            }
            Ok(())
        });
        assert_eq!(result, Err(Error::Limit(LimitKind::Nodes)));
    }
    use crate::LimitKind;

    #[derive(Debug, PartialEq, Eq)]
    struct Nested {
        fixed: u8,
        added: u8,
    }

    impl<'de> Inline<'de> for Nested {
        type Encoded<'s> = (u8, Extensions<'s>);
        type Decoded = (u8, Extensions<'de>);

        fn prepare<'s>(
            &'s self,
            context: &WriteContext<'_>,
            scratch: &'s mut [u8],
        ) -> Result<(Self::Encoded<'s>, &'s mut [u8]), Error> {
            context.admit_preparation()?;
            let mut block = ExtensionsWriter::new(scratch);
            block.push(context, 2, &self.added)?;
            let (block, tail) = block.finish_and_tail();
            Ok(((self.fixed, block), tail))
        }

        fn project(
            (fixed, block): Self::Decoded,
            context: &ReadContext<'_>,
        ) -> Result<Self, Error> {
            let mut added = None;
            block.visit(context, |id, value| {
                if id == 2 {
                    added = Some(value.decode()?);
                }
                Ok(())
            })?;
            Ok(Self {
                fixed,
                added: added.ok_or(Error::Incompatible)?,
            })
        }
    }

    #[test]
    fn staged_child_bytes_are_reused_by_following_extension() {
        const LIMITS: Limits = Limits {
            bytes: 32,
            allocation: 2048,
            nodes: 64,
            depth: 8,
        };
        let child = Nested {
            fixed: 42,
            added: 17,
        };
        let mut output = Vec::new();
        let mut scratch = [0; 10];
        fn stage<'out>(
            output: &'out mut Vec<u8>,
            child: &Nested,
            scratch: &mut [u8],
        ) -> Result<&'out [u8], Error> {
            encode_value_into(output, Encoding::Payload, LIMITS, |context| {
                let mut block = ExtensionsWriter::new(scratch);
                block.push_projected(context, 1, child)?;
                block.push(context, 5, &9_u8)?;
                Ok(block.finish())
            })
        }
        assert_eq!(
            stage(&mut output, &child, &mut scratch),
            Ok([10, 1, 5, 42, 3, 2, 1, 17, 5, 1, 9].as_slice()),
        );
        let actual = decode_value(
            &output,
            Encoding::Payload,
            LIMITS,
            |block: Extensions<'_>, context| {
                let mut child = None;
                let mut sibling = None;
                block.visit(context, |id, field| {
                    match id {
                        1 => child = Some(field.project_inline::<Nested>()?),
                        5 => sibling = Some(field.decode::<u8>()?),
                        _ => (),
                    }
                    Ok(())
                })?;
                Ok((child, sibling))
            },
        );
        assert_eq!(
            actual,
            Ok((
                Some(Nested {
                    fixed: 42,
                    added: 17
                }),
                Some(9)
            ))
        );
        assert_eq!(
            stage(&mut output, &child, &mut scratch[..9]),
            Err(Error::Limit(LimitKind::Scratch)),
        );
        assert!(output.is_empty());
    }
}