wire-repr 0.5.1

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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#![deny(missing_docs, unsafe_code)]

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

use core::{
    convert::Infallible,
    sync::atomic::{AtomicUsize, Ordering},
};

use wire_repr::{EncodePlan, FixedCodec, OutputTooShortError, wire_repr};

/// A borrowed two-byte builder value.
#[derive(Debug, PartialEq, Eq)]
struct Borrowed<'wire>(&'wire [u8]);

/// A two-byte codec with borrowed values.
struct Borrowing;

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

/// An encoding error used by the fallible codec.
#[derive(Debug, PartialEq, Eq)]
enum EncodeError {
    Rejected,
}

/// A one-byte codec that rejects zero while planning.
struct Failing;

impl FixedCodec for Failing {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = EncodeError;
    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(EncodeError::Rejected)
        } else {
            Ok([value])
        }
    }
}

/// Counts attempted plans for the structurally invalid zero-width codec.
static ZERO_WIDTH_PLAN_CALLS: AtomicUsize = AtomicUsize::new(0);

/// A zero-width codec that violates the fixed codec law.
struct ZeroWidth;

impl FixedCodec for ZeroWidth {
    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_WIDTH_PLAN_CALLS.fetch_add(1, Ordering::Relaxed);
        Ok([])
    }
}

/// A plan reporting an enormous encoded length without allocating bytes.
struct HugePlan;

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

/// Counts attempted plans for the codec in the overflowing layout.
static HUGE_PLAN_CALLS: AtomicUsize = AtomicUsize::new(0);

/// A codec whose valid width reaches the largest representable extent.
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_PLAN_CALLS.fetch_add(1, Ordering::Relaxed);
        Ok(HugePlan)
    }
}

/// A deliberately invalid successful encoding plan.
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])
    }
}

/// Counts plans requested by the prepared-layout coverage codec.
static PREPARED_PLAN_CALLS: AtomicUsize = AtomicUsize::new(0);

/// A codec whose plan retains its borrowed input until commit.
struct PreparedBorrowing;

impl FixedCodec for PreparedBorrowing {
    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)
    }
    fn plan<'value>(value: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        PREPARED_PLAN_CALLS.fetch_add(1, Ordering::Relaxed);
        Ok(value.0)
    }
}

wire_repr! {
    /// A mixed physical-order layout with opaque spacing.
    pub layout Mixed {
        /// The trailing big-endian word.
        tail @ 4: BeU16;
        align(4) @ 3;
        padding(2) @ 2;
        /// The leading byte.
        head @ 1: U8;
    }

    /// A layout combining scalar and borrowed builder values.
    pub layout BorrowedPacket {
        /// Borrowed bytes physically after the scalar.
        borrowed @ 2: crate::Borrowing;
        /// A scalar first byte.
        scalar @ 1: U8;
    }

    /// A layout whose codecs exercise atomic preparation failures.
    pub layout Problem {
        /// The first declared field.
        failing @ 1: crate::Failing;
        /// The second declared field.
        wrong @ 2: crate::WrongPlan;
    }

    /// A layout that rejects a zero-width custom fixed codec while building.
    pub layout ZeroWidthPacket {
        /// The invalid custom field.
        zero @ 1: crate::ZeroWidth;
    }

    /// A layout whose padding advances beyond the largest representable extent.
    pub layout OverflowPacket {
        /// The maximal-width custom field.
        huge @ 1: crate::Huge;
        padding(1) @ 2;
    }

    /// A layout proving builder preparation uses declaration rather than physical order.
    pub layout DeclarationOrder {
        /// The first declared field, physically second.
        first @ 2: crate::Failing;
        /// The second declared field, physically first.
        second @ 1: crate::Failing;
    }

    /// A layout used to exercise explicit prepared commits.
    pub layout PreparedPacket {
        head @ 1: U8;
        padding(1) @ 2;
        payload @ 3: crate::PreparedBorrowing;
    }
}

#[test]
fn mutable_views_validate_split_and_convert_without_exposing_mutable_bytes() {
    let mut input = [7, 0xaa, 0xbb, 0xcc, 0x12, 0x34, 0x99];
    let (mut view, suffix) = MixedViewMut::parse_prefix_mut(&mut input).expect("valid prefix");
    assert_eq!(suffix, [0x99]);
    assert_eq!(view.head(), 7);
    assert_eq!(view.tail(), 0x1234);
    assert_eq!(
        view.as_view().as_bytes(),
        &[7, 0xaa, 0xbb, 0xcc, 0x12, 0x34]
    );
    view.set_head(8).expect("built-in plan succeeds");
    let immutable = view.into_view();
    assert_eq!(immutable.head(), 8);
    assert_eq!(immutable.as_bytes(), &[8, 0xaa, 0xbb, 0xcc, 0x12, 0x34]);
    let mut exact_bytes = [7, 0xaa, 0xbb, 0xcc, 0x12, 0x34];
    let exact = MixedViewMut::parse_exact_mut(&mut exact_bytes).expect("exact mutable layout");
    assert_eq!(exact.tail(), 0x1234);
    assert!(matches!(
        MixedViewMut::parse_exact_mut(&mut [7, 0, 0, 0, 0, 1, 2]),
        Err(MixedError::TrailingBytes { .. })
    ));
}

#[test]
fn setters_preflight_before_changing_the_owned_field() {
    let mut bytes = [1, 2, 3];
    let mut view = ProblemViewMut::parse_exact_mut(&mut bytes).expect("valid bytes");
    assert!(matches!(
        view.set_failing(0),
        Err(ProblemMutationError::FieldFailing(EncodeError::Rejected))
    ));
    assert_eq!(view.as_bytes(), &[1, 2, 3]);
    assert!(matches!(
        view.set_wrong(9),
        Err(ProblemMutationError::InvalidPlanLength {
            field: "wrong",
            expected: 2,
            actual: 1
        })
    ));
    assert_eq!(view.as_bytes(), &[1, 2, 3]);
}

#[test]
fn builders_are_atomic_and_write_in_physical_order() {
    let borrowed = [0xca, 0xfe];
    let mut borrowed_output = [0; 3];
    let (borrowed_view, borrowed_suffix) = BorrowedPacketBuilder::new()
        .scalar(7)
        .borrowed(Borrowed(&borrowed))
        .build_into(&mut borrowed_output)
        .expect("scalar and borrowed values infer one lifetime");
    assert!(borrowed_suffix.is_empty());
    assert_eq!(borrowed_view.as_bytes(), &[7, 0xca, 0xfe]);
    assert_eq!(borrowed_view.borrowed(), Borrowed(&borrowed));

    let mut unchanged = [0x55; 6];
    assert!(matches!(
        ProblemBuilder::new().wrong(2).build_into(&mut unchanged),
        Err(ProblemWriteError::MissingField { field: "failing" })
    ));
    assert_eq!(unchanged, [0x55; 6]);
    assert!(matches!(
        ProblemBuilder::new()
            .failing(0)
            .wrong(2)
            .build_into(&mut unchanged),
        Err(ProblemWriteError::FieldFailing(EncodeError::Rejected))
    ));
    assert_eq!(unchanged, [0x55; 6]);
    assert!(matches!(
        ProblemBuilder::new()
            .failing(1)
            .wrong(2)
            .build_into(&mut unchanged),
        Err(ProblemWriteError::InvalidPlanLength {
            field: "wrong",
            expected: 2,
            actual: 1
        })
    ));
    assert_eq!(unchanged, [0x55; 6]);

    let mut short = [0x44; 5];
    assert!(matches!(
        MixedBuilder::new()
            .tail(0x1234)
            .head(7)
            .build_into(&mut short),
        Err(MixedWriteError::OutputTooShort {
            needed: 6,
            available: 5
        })
    ));
    assert_eq!(short, [0x44; 5]);

    let mut output = [0xde, 0xaa, 0xbb, 0xcc, 0xad, 0xbe, 0x99];
    let (mut view, suffix) = MixedBuilder::new()
        .tail(0x1234)
        .head(7)
        .build_into(&mut output)
        .expect("complete builder");
    assert_eq!(view.as_bytes(), &[7, 0xaa, 0xbb, 0xcc, 0x12, 0x34]);
    view.set_head(8).expect("built view remains mutable");
    assert_eq!(view.as_bytes(), &[8, 0xaa, 0xbb, 0xcc, 0x12, 0x34]);
    assert_eq!(suffix, [0x99]);
    assert_eq!(output, [8, 0xaa, 0xbb, 0xcc, 0x12, 0x34, 0x99]);
}

#[test]
fn builders_reject_zero_width_codecs_before_missing_values_or_writing() {
    ZERO_WIDTH_PLAN_CALLS.store(0, Ordering::Relaxed);
    let mut output = [0xa5];
    assert!(matches!(
        ZeroWidthPacketBuilder::new().build_into(&mut output),
        Err(ZeroWidthPacketWriteError::InvalidCodecWidth { field: "zero" })
    ));
    assert_eq!(ZERO_WIDTH_PLAN_CALLS.load(Ordering::Relaxed), 0);
    assert_eq!(output, [0xa5]);
}

#[test]
fn overflowing_fixed_extents_fail_before_slicing_or_writing() {
    assert_eq!(OverflowPacket::WIDTH, usize::MAX);
    assert!(matches!(
        OverflowPacket::view(&[]).with_remainder(),
        Err(OverflowPacketError::InvalidLayoutExtent {
            position: 2,
            offset: usize::MAX,
            advance: 1
        })
    ));
    let mut input = [];
    assert!(matches!(
        OverflowPacketViewMut::parse_prefix_mut(&mut input),
        Err(OverflowPacketError::InvalidLayoutExtent {
            position: 2,
            offset: usize::MAX,
            advance: 1
        })
    ));
    HUGE_PLAN_CALLS.store(0, Ordering::Relaxed);
    let mut output = [0x5a];
    assert!(matches!(
        OverflowPacketBuilder::new().huge(0).build_into(&mut output),
        Err(OverflowPacketWriteError::InvalidLayoutExtent {
            position: 2,
            offset: usize::MAX,
            advance: 1
        })
    ));
    assert_eq!(HUGE_PLAN_CALLS.load(Ordering::Relaxed), 0);
    assert_eq!(output, [0x5a]);
}

#[test]
fn builder_plan_errors_follow_declaration_order() {
    let mut output = [0x3c; 2];
    assert!(matches!(
        DeclarationOrderBuilder::new()
            .first(0)
            .second(0)
            .build_into(&mut output),
        Err(DeclarationOrderWriteError::FieldFirst(
            EncodeError::Rejected
        ))
    ));
    assert_eq!(output, [0x3c; 2]);
}

#[test]
fn prepared_layouts_preflight_once_and_commit_without_replanning() {
    let missing = ProblemBuilder::new().wrong(2).prepare();
    assert!(matches!(
        missing,
        Err(ProblemWriteError::MissingField { field: "failing" })
    ));
    let rejected = ProblemBuilder::new().failing(0).wrong(2).prepare();
    assert!(matches!(
        rejected,
        Err(ProblemWriteError::FieldFailing(EncodeError::Rejected))
    ));

    PREPARED_PLAN_CALLS.store(0, Ordering::Relaxed);
    let payload = [0xca, 0xfe];
    let plan = PreparedPacketBuilder::new()
        .head(7)
        .payload(Borrowed(&payload))
        .prepare()
        .expect("preparation does not require a destination");
    assert_eq!(plan.encoded_len(), 4);
    assert_eq!(PREPARED_PLAN_CALLS.load(Ordering::Relaxed), 1);

    let mut short = [0x55; 3];
    assert!(matches!(
        plan.commit_into(&mut short),
        Err(OutputTooShortError {
            required: 4,
            available: 3
        })
    ));
    assert_eq!(short, [0x55; 3]);

    let plan = PreparedPacketBuilder::new()
        .head(7)
        .payload(Borrowed(&payload))
        .prepare()
        .expect("a fresh plan commits once");
    let mut output = [0, 0xaa, 0, 0, 0x99];
    let (view, suffix) = plan.commit_into(&mut output).expect("enough output");
    assert_eq!(view.as_bytes(), &[7, 0xaa, 0xca, 0xfe]);
    assert_eq!(suffix, [0x99]);
    assert_eq!(PREPARED_PLAN_CALLS.load(Ordering::Relaxed), 2);
}