wire-repr 0.5.2

A no_std, no_alloc Rust library for wire representations.
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
427
428
429
430
431
#![deny(missing_docs, unsafe_code)]

//! Public mutable fixed-absolute view and builder coverage.

use core::{
    convert::Infallible,
    sync::atomic::{AtomicUsize, Ordering},
};
use wire_repr::{EncodePlan, FixedCodec, OutputTooShortError, wire_repr};

#[derive(Debug, PartialEq, Eq)]
struct Borrowed<'wire>(&'wire [u8; 2]);

struct Borrowing;
static BORROWING_PLANS: AtomicUsize = AtomicUsize::new(0);
impl FixedCodec for Borrowing {
    type Value<'wire>
        = Borrowed<'wire>
    where
        Self: 'wire;
    type EncodeError = Infallible;
    type Plan<'value>
        = &'value [u8]
    where
        Self: 'value;
    const WIDTH: usize = 2;
    fn decode<'wire>(bytes: &'wire [u8]) -> Self::Value<'wire> {
        Borrowed(
            bytes
                .try_into()
                .expect("fixed codec receives its exact declared width"),
        )
    }
    fn plan<'value>(value: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        BORROWING_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok(value.0)
    }
}

#[derive(Debug, PartialEq, Eq)]
enum PlanError {
    Rejected,
}

struct Failing;
impl FixedCodec for Failing {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = PlanError;
    type Plan<'value>
        = [u8; 1]
    where
        Self: 'value;
    const WIDTH: usize = 1;
    fn decode<'wire>(bytes: &'wire [u8]) -> Self::Value<'wire> {
        bytes[0]
    }
    fn plan<'value>(value: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        if value == 0 {
            Err(PlanError::Rejected)
        } else {
            Ok([value])
        }
    }
}

struct WrongPlan;
impl FixedCodec for WrongPlan {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = Infallible;
    type Plan<'value>
        = [u8; 1]
    where
        Self: 'value;
    const WIDTH: usize = 2;
    fn decode<'wire>(bytes: &'wire [u8]) -> Self::Value<'wire> {
        bytes[0]
    }
    fn plan<'value>(value: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        Ok([value])
    }
}

static ZERO_PLANS: AtomicUsize = AtomicUsize::new(0);
struct Zero;
impl FixedCodec for Zero {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = Infallible;
    type Plan<'value>
        = [u8; 0]
    where
        Self: 'value;
    const WIDTH: usize = 0;
    fn decode<'wire>(_: &'wire [u8]) -> Self::Value<'wire> {
        0
    }
    fn plan<'value>(_: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        ZERO_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok([])
    }
}

struct HugePlan;
impl EncodePlan for HugePlan {
    fn encoded_len(&self) -> usize {
        usize::MAX
    }
    fn write_into(&self, _: &mut [u8]) {}
}

static HUGE_PLANS: AtomicUsize = AtomicUsize::new(0);
struct Huge;
impl FixedCodec for Huge {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = Infallible;
    type Plan<'value>
        = HugePlan
    where
        Self: 'value;
    const WIDTH: usize = usize::MAX;
    fn decode<'wire>(_: &'wire [u8]) -> Self::Value<'wire> {
        0
    }
    fn plan<'value>(_: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        HUGE_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok(HugePlan)
    }
}

static WIDE_PLANS: AtomicUsize = AtomicUsize::new(0);
struct Wide;
impl FixedCodec for Wide {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = Infallible;
    type Plan<'value>
        = [u8; 3]
    where
        Self: 'value;
    const WIDTH: usize = 3;
    fn decode<'wire>(bytes: &'wire [u8]) -> Self::Value<'wire> {
        bytes[0]
    }
    fn plan<'value>(value: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        WIDE_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok([value; 3])
    }
}

wire_repr! {
    /// A sparse layout declared opposite to physical order.
    pub absolute layout Packet {
        /// The trailing word.
        tail @ 4: BeU16;
        /// Borrowed bytes in the middle.
        borrowed @ 1: crate::Borrowing;
        /// The leading byte.
        head @ 0: U8;
    }
    /// Planning failures in declaration order.
    pub absolute layout Problem {
        /// First declaration, physically later.
        first @ 2: crate::Failing;
        /// Second declaration, physically first.
        wrong @ 0: crate::WrongPlan;
    }
    /// A zero-width structural failure.
    pub absolute layout ZeroLayout {
        /// Invalid codec.
        zero @ 3: crate::Zero;
    }
    /// An overflowing structural failure.
    pub absolute layout OverflowLayout {
        /// Invalid codec extent.
        huge @ 1: crate::Huge;
    }
    /// An overlapping structural failure.
    pub absolute layout OverlapLayout {
        /// Earlier wide field.
        wide @ 0: crate::Wide;
        /// Later overlap.
        later @ 2: U8;
    }
}

#[test]
fn mutable_parsing_preserves_suffix_and_immutable_conversions() {
    let mut input = [7, 0xca, 0xfe, 0xaa, 0x12, 0x34, 0x99];
    let (mut view, suffix) = PacketViewMut::parse_prefix_mut(&mut input).expect("valid prefix");
    assert_eq!(suffix, [0x99]);
    assert_eq!(view.head(), 7);
    assert_eq!(view.borrowed(), Borrowed(&[0xca, 0xfe]));
    assert_eq!(view.tail(), 0x1234);
    assert_eq!(view.as_bytes(), &[7, 0xca, 0xfe, 0xaa, 0x12, 0x34]);
    view.set_head(8).expect("built-in plan");
    assert_eq!(view.as_view().head(), 8);
    assert_eq!(
        view.into_view().as_bytes(),
        &[8, 0xca, 0xfe, 0xaa, 0x12, 0x34]
    );

    let mut exact = [7, 0xca, 0xfe, 0xaa, 0x12, 0x34];
    assert_eq!(
        PacketViewMut::parse_exact_mut(&mut exact)
            .expect("exact")
            .tail(),
        0x1234
    );
    assert!(matches!(
        PacketViewMut::parse_exact_mut(&mut [7, 0, 0, 0, 0, 1, 2]),
        Err(PacketError::TrailingBytes {
            expected: 6,
            actual: 7
        })
    ));
}

#[test]
fn setters_are_atomic_and_write_only_the_field_span() {
    let mut bytes = [0x10, 0x20, 0x30];
    let mut view = ProblemViewMut::parse_exact_mut(&mut bytes).expect("valid bytes");
    assert!(matches!(
        view.set_first(0),
        Err(ProblemMutationError::FieldFirst(PlanError::Rejected))
    ));
    assert_eq!(view.as_bytes(), &[0x10, 0x20, 0x30]);
    assert!(matches!(
        view.set_wrong(9),
        Err(ProblemMutationError::InvalidPlanLength {
            field: "wrong",
            expected: 2,
            actual: 1
        })
    ));
    assert_eq!(view.as_bytes(), &[0x10, 0x20, 0x30]);
    view.set_first(0x77).expect("exact plan");
    assert_eq!(view.as_bytes(), &[0x10, 0x20, 0x77]);
}

#[test]
fn builder_is_atomic_preserves_gaps_and_returns_a_mutable_view() {
    let borrowed = [0xca, 0xfe];
    let mut output = [0xde, 0xaa, 0xbb, 0xcc, 0xad, 0xbe, 0x99];
    let (mut view, suffix) = PacketBuilder::new()
        .tail(0x1234)
        .borrowed(Borrowed(&borrowed))
        .head(7)
        .build_into(&mut output)
        .expect("complete builder");
    assert_eq!(view.as_bytes(), &[7, 0xca, 0xfe, 0xcc, 0x12, 0x34]);
    assert_eq!(suffix, [0x99]);
    view.set_head(8).expect("remains mutable");
    assert_eq!(output, [8, 0xca, 0xfe, 0xcc, 0x12, 0x34, 0x99]);

    let mut unchanged = [0x55; 5];
    assert!(matches!(
        ProblemBuilder::new().wrong(2).build_into(&mut unchanged),
        Err(ProblemWriteError::MissingField { field: "first" })
    ));
    assert_eq!(unchanged, [0x55; 5]);
    assert!(matches!(
        ProblemBuilder::new()
            .first(0)
            .wrong(2)
            .build_into(&mut unchanged),
        Err(ProblemWriteError::FieldFirst(PlanError::Rejected))
    ));
    assert_eq!(unchanged, [0x55; 5]);
    assert!(matches!(
        ProblemBuilder::new()
            .first(1)
            .wrong(2)
            .build_into(&mut unchanged),
        Err(ProblemWriteError::InvalidPlanLength {
            field: "wrong",
            expected: 2,
            actual: 1
        })
    ));
    assert_eq!(unchanged, [0x55; 5]);
    assert!(matches!(
        PacketBuilder::new()
            .tail(1)
            .borrowed(Borrowed(&borrowed))
            .head(2)
            .build_into(&mut unchanged),
        Err(PacketWriteError::OutputTooShort {
            needed: 6,
            available: 5
        })
    ));
    assert_eq!(unchanged, [0x55; 5]);
}

#[test]
fn structural_errors_precede_missing_values_and_planning() {
    ZERO_PLANS.store(0, Ordering::Relaxed);
    let mut output = [0xa5];
    assert!(matches!(
        ZeroLayoutBuilder::new().build_into(&mut output),
        Err(ZeroLayoutWriteError::InvalidCodecWidth { offset: 3 })
    ));
    assert_eq!(ZERO_PLANS.load(Ordering::Relaxed), 0);
    assert_eq!(output, [0xa5]);

    HUGE_PLANS.store(0, Ordering::Relaxed);
    assert_eq!(OverflowLayout::WIDTH, usize::MAX);
    assert!(matches!(
        OverflowLayoutViewMut::parse_prefix_mut(&mut []),
        Err(OverflowLayoutError::InvalidCodecExtent { offset: 1, width }) if width == usize::MAX
    ));
    assert!(matches!(
        OverflowLayoutBuilder::new().huge(0).build_into(&mut output),
        Err(OverflowLayoutWriteError::InvalidCodecExtent { offset: 1, width }) if width == usize::MAX
    ));
    assert_eq!(HUGE_PLANS.load(Ordering::Relaxed), 0);
    assert_eq!(output, [0xa5]);

    WIDE_PLANS.store(0, Ordering::Relaxed);
    assert!(matches!(
        OverlapLayoutBuilder::new().build_into(&mut output),
        Err(OverlapLayoutWriteError::OverlappingFields {
            earlier_offset: 0,
            later_offset: 2
        })
    ));
    assert_eq!(WIDE_PLANS.load(Ordering::Relaxed), 0);
    assert_eq!(output, [0xa5]);
}

#[test]
fn prepared_absolute_layouts_preflight_once_and_commit_without_replanning() {
    let borrowed = [0xca, 0xfe];

    assert!(matches!(
        ProblemBuilder::new().wrong(2).prepare(),
        Err(ProblemWriteError::MissingField { field: "first" })
    ));
    assert!(matches!(
        ProblemBuilder::new().first(0).wrong(2).prepare(),
        Err(ProblemWriteError::FieldFirst(PlanError::Rejected))
    ));
    assert!(matches!(
        ProblemBuilder::new().first(1).wrong(2).prepare(),
        Err(ProblemWriteError::InvalidPlanLength {
            field: "wrong",
            expected: 2,
            actual: 1
        })
    ));

    ZERO_PLANS.store(0, Ordering::Relaxed);
    assert!(matches!(
        ZeroLayoutBuilder::new().prepare(),
        Err(ZeroLayoutWriteError::InvalidCodecWidth { offset: 3 })
    ));
    assert_eq!(ZERO_PLANS.load(Ordering::Relaxed), 0);
    HUGE_PLANS.store(0, Ordering::Relaxed);
    assert!(matches!(
        OverflowLayoutBuilder::new().huge(0).prepare(),
        Err(OverflowLayoutWriteError::InvalidCodecExtent { offset: 1, width }) if width == usize::MAX
    ));
    assert_eq!(HUGE_PLANS.load(Ordering::Relaxed), 0);
    WIDE_PLANS.store(0, Ordering::Relaxed);
    assert!(matches!(
        OverlapLayoutBuilder::new().wide(1).later(2).prepare(),
        Err(OverlapLayoutWriteError::OverlappingFields {
            earlier_offset: 0,
            later_offset: 2
        })
    ));
    assert_eq!(WIDE_PLANS.load(Ordering::Relaxed), 0);

    BORROWING_PLANS.store(0, Ordering::Relaxed);
    let plan = PacketBuilder::new()
        .tail(0x1234)
        .borrowed(Borrowed(&borrowed))
        .head(7)
        .prepare()
        .expect("preparation does not require a destination");
    assert_eq!(plan.encoded_len(), 6);
    assert_eq!(BORROWING_PLANS.load(Ordering::Relaxed), 1);

    let mut short = [0x55; 5];
    assert!(matches!(
        plan.commit_into(&mut short),
        Err(OutputTooShortError {
            required: 6,
            available: 5
        })
    ));
    assert_eq!(short, [0x55; 5]);
    assert_eq!(BORROWING_PLANS.load(Ordering::Relaxed), 1);

    let plan = PacketBuilder::new()
        .tail(0x1234)
        .borrowed(Borrowed(&borrowed))
        .head(7)
        .prepare()
        .expect("a fresh borrowed plan commits into the exact extent");
    let mut exact = [0xde, 0xaa, 0xbb, 0xcc, 0xad, 0xbe];
    let (view, suffix) = plan.commit_into(&mut exact).expect("exact output");
    assert_eq!(view.as_bytes(), &[7, 0xca, 0xfe, 0xcc, 0x12, 0x34]);
    assert!(suffix.is_empty());
    assert_eq!(BORROWING_PLANS.load(Ordering::Relaxed), 2);

    let plan = PacketBuilder::new()
        .tail(0x1234)
        .borrowed(Borrowed(&borrowed))
        .head(7)
        .prepare()
        .expect("a fresh borrowed plan commits with a suffix");
    let mut output = [0xde, 0xaa, 0xbb, 0xcc, 0xad, 0xbe, 0x99];
    let (view, suffix) = plan.commit_into(&mut output).expect("extra output");
    assert_eq!(view.as_bytes(), &[7, 0xca, 0xfe, 0xcc, 0x12, 0x34]);
    assert_eq!(suffix, [0x99]);
    assert_eq!(BORROWING_PLANS.load(Ordering::Relaxed), 3);
}