wire-repr 0.1.0

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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
use core::convert::Infallible;
use core::num::NonZeroUsize;
use core::sync::atomic::{AtomicUsize, Ordering};

use wire_repr::{EncodePlan, FixedCodec, PrefixCodec, PrefixExtent, wire_repr};

struct TwoBytePrefix;

impl PrefixCodec for TwoBytePrefix {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type DecodeError = Infallible;
    type EncodeError = Infallible;
    type Plan<'value>
        = [u8; 2]
    where
        Self: 'value;

    fn validate_prefix(_: &[u8]) -> Result<PrefixExtent, Self::DecodeError> {
        Ok(PrefixExtent::new(NonZeroUsize::new(2).unwrap()))
    }

    fn decode<'wire>(bytes: &'wire [u8]) -> Self::Value<'wire> {
        bytes[1]
    }

    fn plan<'value>(value: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        Ok([0xf0, value])
    }
}

struct LengthPrefix;

impl PrefixCodec for LengthPrefix {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type DecodeError = Infallible;
    type EncodeError = Infallible;
    type Plan<'value>
        = [u8; 1]
    where
        Self: 'value;

    fn validate_prefix(_: &[u8]) -> Result<PrefixExtent, Self::DecodeError> {
        Ok(PrefixExtent::new(NonZeroUsize::MIN))
    }

    fn decode<'wire>(bytes: &'wire [u8]) -> Self::Value<'wire> {
        bytes[0] - 0x80
    }

    fn plan<'value>(value: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        Ok([value + 0x80])
    }
}

static SHARED_SOURCE_PLANS: AtomicUsize = AtomicUsize::new(0);

struct SharedLength;

impl FixedCodec for SharedLength {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = Infallible;
    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> {
        SHARED_SOURCE_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok([value])
    }
}

static MISSING_PLANS: AtomicUsize = AtomicUsize::new(0);

struct MissingCount;

impl FixedCodec for MissingCount {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = Infallible;
    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> {
        MISSING_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok([value])
    }
}

static ZERO_WIDTH_PLANS: AtomicUsize = AtomicUsize::new(0);

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_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok([])
    }
}

static REVERSE_SOURCE_PLANS: AtomicUsize = AtomicUsize::new(0);

struct ReverseLength;

impl FixedCodec for ReverseLength {
    type Value<'wire>
        = u8
    where
        Self: 'wire;
    type EncodeError = Infallible;
    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> {
        REVERSE_SOURCE_PLANS.fetch_add(1, Ordering::Relaxed);
        Ok([value])
    }
}

#[derive(Debug, Eq, PartialEq)]
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>(_: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        Err(PlanError::Rejected)
    }
}

struct FailingLength(u8);

impl TryFrom<usize> for FailingLength {
    type Error = ();

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        u8::try_from(value).map(Self).map_err(|_| ())
    }
}

impl From<FailingLength> for usize {
    fn from(value: FailingLength) -> Self {
        usize::from(value.0)
    }
}

struct SourceFailing;

impl FixedCodec for SourceFailing {
    type Value<'wire>
        = FailingLength
    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> {
        FailingLength(bytes[0])
    }
    fn plan<'value>(_: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        Err(PlanError::Rejected)
    }
}

struct WrongFixedPlan;

impl FixedCodec for WrongFixedPlan {
    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])
    }
}

struct EmptyPrefixPlan;

impl PrefixCodec for EmptyPrefixPlan {
    type Value<'wire>
        = ()
    where
        Self: 'wire;
    type DecodeError = Infallible;
    type EncodeError = Infallible;
    type Plan<'value>
        = [u8; 0]
    where
        Self: 'value;

    fn validate_prefix(_: &[u8]) -> Result<PrefixExtent, Self::DecodeError> {
        Ok(PrefixExtent::new(NonZeroUsize::MIN))
    }
    fn decode<'wire>(_: &'wire [u8]) -> Self::Value<'wire> {}
    fn plan<'value>(_: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        Ok([])
    }
}

struct MaxPrefixPlan;

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

struct OverflowingPrefixPlan;

impl PrefixCodec for OverflowingPrefixPlan {
    type Value<'wire>
        = ()
    where
        Self: 'wire;
    type DecodeError = Infallible;
    type EncodeError = Infallible;
    type Plan<'value>
        = MaxPrefixPlan
    where
        Self: 'value;

    fn validate_prefix(_: &[u8]) -> Result<PrefixExtent, Self::DecodeError> {
        Ok(PrefixExtent::new(NonZeroUsize::MIN))
    }
    fn decode<'wire>(_: &'wire [u8]) -> Self::Value<'wire> {}
    fn plan<'value>(_: Self::Value<'value>) -> Result<Self::Plan<'value>, Self::EncodeError> {
        Ok(MaxPrefixPlan)
    }
}

static CAPACITY_FIRST_PLANS: AtomicUsize = AtomicUsize::new(0);
static CAPACITY_SECOND_PLANS: AtomicUsize = AtomicUsize::new(0);
static CAPACITY_WRITES: AtomicUsize = AtomicUsize::new(0);

struct CapacityFirst;
struct CapacitySecond;

macro_rules! capacity_codec {
    ($name:ident, $plans:ident) => {
        impl FixedCodec for $name {
            type Value<'wire>
                = u8
            where
                Self: 'wire;
            type EncodeError = Infallible;
            type Plan<'value>
                = CapacityPlan
            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> {
                $plans.fetch_add(1, Ordering::Relaxed);
                Ok(CapacityPlan(value))
            }
        }
    };
}

struct CapacityPlan(u8);
impl EncodePlan for CapacityPlan {
    fn encoded_len(&self) -> usize {
        1
    }
    fn write_into(&self, output: &mut [u8]) {
        CAPACITY_WRITES.fetch_add(1, Ordering::Relaxed);
        output[0] = self.0;
    }
}
capacity_codec!(CapacityFirst, CAPACITY_FIRST_PLANS);
capacity_codec!(CapacitySecond, CAPACITY_SECOND_PLANS);

static ORDER_SEQUENCE: AtomicUsize = AtomicUsize::new(0);
static FIRST_PLAN_ORDER: AtomicUsize = AtomicUsize::new(usize::MAX);
static SECOND_PLAN_ORDER: AtomicUsize = AtomicUsize::new(usize::MAX);
static FIRST_WRITE_ORDER: AtomicUsize = AtomicUsize::new(usize::MAX);
static SECOND_WRITE_ORDER: AtomicUsize = AtomicUsize::new(usize::MAX);

struct First;
struct Second;
struct OrderedPlan {
    byte: u8,
    write_order: &'static AtomicUsize,
}

impl EncodePlan for OrderedPlan {
    fn encoded_len(&self) -> usize {
        1
    }
    fn write_into(&self, output: &mut [u8]) {
        self.write_order.store(
            ORDER_SEQUENCE.fetch_add(1, Ordering::Relaxed),
            Ordering::Relaxed,
        );
        output[0] = self.byte;
    }
}

macro_rules! ordered_codec {
    ($name:ident, $byte:literal, $plan_order:ident, $write_order:ident) => {
        impl FixedCodec for $name {
            type Value<'wire>
                = ()
            where
                Self: 'wire;
            type EncodeError = Infallible;
            type Plan<'value>
                = OrderedPlan
            where
                Self: 'value;
            const WIDTH: usize = 1;
            fn decode<'wire>(_: &'wire [u8]) -> Self::Value<'wire> {}
            fn plan<'value>(
                _: Self::Value<'value>,
            ) -> Result<Self::Plan<'value>, Self::EncodeError> {
                $plan_order.store(
                    ORDER_SEQUENCE.fetch_add(1, Ordering::Relaxed),
                    Ordering::Relaxed,
                );
                Ok(OrderedPlan {
                    byte: $byte,
                    write_order: &$write_order,
                })
            }
        }
    };
}
ordered_codec!(First, 1, FIRST_PLAN_ORDER, FIRST_WRITE_ORDER);
ordered_codec!(Second, 2, SECOND_PLAN_ORDER, SECOND_WRITE_ORDER);

wire_repr! {
    /// A mixed dynamic layout for builder coverage.
    pub layout Stem {
        /// A trailing fixed word.
        field tail: BeU16 { position: 7; }
        /// The auto-derived region length.
        field length: U8 { position: 1; }
        /// An ordinary fixed prefix field.
        field tag: U8 { position: 2; }
        /// A planned variable-width prefix.
        field prefix: prefix(TwoBytePrefix) { position: 3; }
        /// Opaque region bytes.
        field body: region(length) { position: 4; }
        padding { position: 5; length: 1; }
        align { position: 6; boundary: 4; }
    }

    /// A layout with a prefix length source.
    pub layout PrefixLength {
        /// The auto-derived prefix length.
        field length: prefix(LengthPrefix) { position: 1; }
        /// The possibly empty region.
        field body: region(length) { position: 2; }
    }

    /// Two regions sharing one source.
    pub layout SharedRegions {
        /// The auto-derived shared length.
        field length: codec(SharedLength) { position: 1; }
        /// The first region.
        field first: region(length) { position: 2; }
        /// The second region.
        field second: region(length) { position: 3; }
    }

    /// Shared-source conflicts follow region declaration order.
    pub layout SharedConflictOrder {
        /// The source whose conflict is declared later.
        field source_a: U8 { position: 1; }
        /// The source whose conflict is declared first.
        field source_b: U8 { position: 2; }
        /// The first region for the second source.
        field b_first: region(source_b) { position: 3; }
        /// The first region for the first source.
        field a_first: region(source_a) { position: 4; }
        /// The first conflicting region in declaration order.
        field b_second: region(source_b) { position: 5; }
        /// A later conflicting region.
        field a_second: region(source_a) { position: 6; }
    }

    /// Inputs declared separately from their physical order.
    pub layout MissingOrder {
        /// Declared first but physical third.
        field later: codec(MissingCount) { position: 3; }
        /// The auto-derived length.
        field length: U8 { position: 1; }
        /// Declared before the final ordinary codec.
        field body: region(length) { position: 2; }
        /// Declared last and physical fourth.
        field final_field: codec(MissingCount) { position: 4; }
    }

    /// An invalid-width field physically before all user inputs.
    pub layout ZeroWidthBeforeInputs {
        /// The invalid codec.
        field zero: codec(ZeroWidth) { position: 1; }
        /// A later required field.
        field required: U8 { position: 2; }
        /// Keeps this scenario on the dynamic builder path.
        field dynamic: prefix(TwoBytePrefix) { position: 3; }
    }

    /// A region whose source cannot represent all lengths.
    pub layout ReverseFailure {
        /// The auto-derived narrow length.
        field length: codec(ReverseLength) { position: 1; }
        /// The large region.
        field body: region(length) { position: 2; }
    }

    /// A planning-error layout.
    pub layout OrdinaryPlanningFailure {
        /// A rejecting field.
        field value: codec(Failing) { position: 1; }
        /// Keeps this scenario on the dynamic builder path.
        field dynamic: prefix(TwoBytePrefix) { position: 2; }
    }

    /// A layout whose derived source rejects encoding.
    pub layout SourcePlanningFailure {
        /// The auto-derived source.
        field length: codec(SourceFailing) { position: 1; }
        /// The region which supplies its source value.
        field body: region(length) { position: 2; }
    }

    /// A fixed plan-length error layout.
    pub layout WrongFixedPlanning {
        /// A contract-invalid fixed plan.
        field value: codec(WrongFixedPlan) { position: 1; }
        /// Keeps this scenario on the dynamic builder path.
        field dynamic: prefix(TwoBytePrefix) { position: 2; }
    }

    /// A prefix plan-length error layout.
    pub layout EmptyPrefixPlanning {
        /// A contract-invalid empty prefix plan.
        field value: prefix(EmptyPrefixPlan) { position: 1; }
    }

    /// A layout containing an explicitly law-violating error fixture.
    pub layout OverflowAfterPrefix {
        /// The error-fixture prefix.
        field prefix: prefix(OverflowingPrefixPlan) { position: 1; }
        /// The physical advance after it.
        field tail: U8 { position: 2; }
    }

    /// A capacity preflight layout.
    pub layout CapacityCheck {
        /// First planned field.
        field first: codec(CapacityFirst) { position: 1; }
        /// Second planned field.
        field second: codec(CapacitySecond) { position: 2; }
        /// Keeps this scenario on the dynamic builder path.
        field dynamic: prefix(TwoBytePrefix) { position: 3; }
    }

    /// A layout whose declaration and commit orders differ.
    pub layout CommitOrder {
        /// Planned first, physically second.
        field first: codec(First) { position: 2; }
        /// Planned second, physically first.
        field second: codec(Second) { position: 1; }
        /// Keeps this scenario on the dynamic builder path.
        field dynamic: prefix(TwoBytePrefix) { position: 3; }
    }

    /// A builder with only a region input.
    pub layout RegionOnly {
        /// The auto-derived length.
        field length: U8 { position: 1; }
        /// The sole user input.
        field body: region(length) { position: 2; }
    }
}

#[test]
fn stem_builder_commits_the_mixed_dynamic_layout_atomically() {
    let mut output = [
        0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x99, 0x88, 0x77, 0x66, 0x55,
    ];
    let (mut view, suffix) = StemBuilder::new()
        .tail(0x1234)
        .tag(0xa1)
        .prefix(0x55)
        .body(&[0xaa, 0xbb])
        .build_into(&mut output)
        .unwrap();
    assert_eq!(
        view.as_bytes(),
        &[2, 0xa1, 0xf0, 0x55, 0xaa, 0xbb, 0x99, 0x88, 0x12, 0x34]
    );
    assert_eq!(view.length(), 2);
    assert_eq!(view.tag(), 0xa1);
    assert_eq!(view.prefix_encoded(), &[0xf0, 0x55]);
    assert_eq!(view.prefix(), 0x55);
    assert_eq!(view.body(), &[0xaa, 0xbb]);
    assert_eq!(view.tail(), 0x1234);
    view.set_tag(0xa2).unwrap();
    assert_eq!(
        view.as_bytes(),
        &[2, 0xa2, 0xf0, 0x55, 0xaa, 0xbb, 0x99, 0x88, 0x12, 0x34]
    );
    assert_eq!(suffix, &[0x55]);
}

#[test]
fn prefix_length_source_derives_zero_length_regions() {
    let mut output = [0xcc, 0xdd];
    let (view, suffix) = PrefixLengthBuilder::new()
        .body(&[])
        .build_into(&mut output)
        .unwrap();
    assert_eq!(view.as_bytes(), &[0x80]);
    assert_eq!(view.length_encoded(), &[0x80]);
    assert_eq!(view.length(), 0);
    assert_eq!(view.body(), &[]);
    assert_eq!(suffix, &[0xdd]);
}

#[test]
fn shared_regions_plan_once_or_reject_before_planning() {
    SHARED_SOURCE_PLANS.store(0, Ordering::Relaxed);
    let mut output = [0; 7];
    let (view, suffix) = SharedRegionsBuilder::new()
        .first(&[1, 2])
        .second(&[3, 4])
        .build_into(&mut output)
        .unwrap();
    assert_eq!(SHARED_SOURCE_PLANS.load(Ordering::Relaxed), 1);
    assert_eq!(view.as_bytes(), &[2, 1, 2, 3, 4]);
    assert_eq!(suffix, &[0, 0]);

    SHARED_SOURCE_PLANS.store(0, Ordering::Relaxed);
    let initial = [0xa5; 7];
    let mut output = initial;
    assert!(matches!(
        SharedRegionsBuilder::new()
            .first(&[1])
            .second(&[2, 3])
            .build_into(&mut output),
        Err(SharedRegionsWriteError::ConflictingRegionLengths {
            source_position: 1,
            first_region_position: 2,
            conflicting_region_position: 3,
            expected: 1,
            actual: 2,
        })
    ));
    assert_eq!(SHARED_SOURCE_PLANS.load(Ordering::Relaxed), 0);
    assert_eq!(output, initial);
}

#[test]
fn shared_source_conflicts_follow_region_declaration_order() {
    let initial = [0x3c; 10];
    let mut output = initial;
    assert!(matches!(
        SharedConflictOrderBuilder::new()
            .b_first(&[1])
            .a_first(&[2])
            .b_second(&[3, 4])
            .a_second(&[5, 6, 7])
            .build_into(&mut output),
        Err(SharedConflictOrderWriteError::ConflictingRegionLengths {
            source_position: 2,
            first_region_position: 3,
            conflicting_region_position: 5,
            expected: 1,
            actual: 2,
        })
    ));
    assert_eq!(output, initial);
}

#[test]
fn missing_inputs_follow_declaration_order_without_planning() {
    MISSING_PLANS.store(0, Ordering::Relaxed);
    let initial = [0x5a; 4];
    let mut output = initial;
    assert!(matches!(
        MissingOrderBuilder::new().build_into(&mut output),
        Err(MissingOrderWriteError::MissingField { field: "later" })
    ));
    assert_eq!(MISSING_PLANS.load(Ordering::Relaxed), 0);
    assert_eq!(output, initial);
}

#[test]
fn zero_width_precedes_missing_inputs_and_planning() {
    ZERO_WIDTH_PLANS.store(0, Ordering::Relaxed);
    let initial = [0xa5; 2];
    let mut output = initial;
    assert!(matches!(
        ZeroWidthBeforeInputsBuilder::new().build_into(&mut output),
        Err(ZeroWidthBeforeInputsWriteError::InvalidCodecWidth { position: 1 })
    ));
    assert_eq!(ZERO_WIDTH_PLANS.load(Ordering::Relaxed), 0);
    assert_eq!(output, initial);
}

#[test]
fn unrepresentable_derived_region_length_is_atomic() {
    REVERSE_SOURCE_PLANS.store(0, Ordering::Relaxed);
    let initial = [0x6c; 257];
    let mut output = initial;
    assert!(matches!(
        ReverseFailureBuilder::new()
            .body(&[0; 256])
            .build_into(&mut output),
        Err(ReverseFailureWriteError::InvalidRegionLength {
            position: 2,
            source_position: 1,
            length: 256,
        })
    ));
    assert_eq!(REVERSE_SOURCE_PLANS.load(Ordering::Relaxed), 0);
    assert_eq!(output, initial);
}

#[test]
fn planning_failures_and_plan_lengths_leave_output_unchanged() {
    let initial = [0x44; 2];
    let mut output = initial;
    assert!(matches!(
        OrdinaryPlanningFailureBuilder::new()
            .value(1)
            .dynamic(0)
            .build_into(&mut output),
        Err(OrdinaryPlanningFailureWriteError::FieldValue(
            PlanError::Rejected
        ))
    ));
    assert_eq!(output, initial);
    assert!(matches!(
        SourcePlanningFailureBuilder::new()
            .body(&[1])
            .build_into(&mut output),
        Err(SourcePlanningFailureWriteError::FieldLength(
            PlanError::Rejected
        ))
    ));
    assert_eq!(output, initial);
    assert!(matches!(
        WrongFixedPlanningBuilder::new()
            .value(1)
            .dynamic(0)
            .build_into(&mut output),
        Err(WrongFixedPlanningWriteError::InvalidPlanLength {
            field: "value",
            expected: 2,
            actual: 1,
        })
    ));
    assert_eq!(output, initial);
    assert!(matches!(
        EmptyPrefixPlanningBuilder::new()
            .value(())
            .build_into(&mut output),
        Err(EmptyPrefixPlanningWriteError::InvalidPrefixPlanLength { field: "value" })
    ));
    assert_eq!(output, initial);
}

#[test]
fn law_violating_prefix_plan_cannot_overflow_layout_extent() {
    let initial = [0x9c; 1];
    let mut output = initial;
    assert!(matches!(
        OverflowAfterPrefixBuilder::new()
            .prefix(())
            .tail(1)
            .build_into(&mut output),
        Err(OverflowAfterPrefixWriteError::InvalidLayoutExtent {
            position: 2,
            offset: usize::MAX,
            advance: 1,
        })
    ));
    assert_eq!(output, initial);
}

#[test]
fn capacity_failure_happens_after_each_plan_and_before_every_write() {
    CAPACITY_FIRST_PLANS.store(0, Ordering::Relaxed);
    CAPACITY_SECOND_PLANS.store(0, Ordering::Relaxed);
    CAPACITY_WRITES.store(0, Ordering::Relaxed);
    let initial = [0x77; 1];
    let mut output = initial;
    assert!(matches!(
        CapacityCheckBuilder::new()
            .first(1)
            .second(2)
            .dynamic(0)
            .build_into(&mut output),
        Err(CapacityCheckWriteError::OutputTooShort {
            expected: 4,
            actual: 1
        })
    ));
    assert_eq!(CAPACITY_FIRST_PLANS.load(Ordering::Relaxed), 1);
    assert_eq!(CAPACITY_SECOND_PLANS.load(Ordering::Relaxed), 1);
    assert_eq!(CAPACITY_WRITES.load(Ordering::Relaxed), 0);
    assert_eq!(output, initial);
}

#[test]
fn plans_follow_declarations_and_writes_follow_physical_order() {
    ORDER_SEQUENCE.store(0, Ordering::Relaxed);
    FIRST_PLAN_ORDER.store(usize::MAX, Ordering::Relaxed);
    SECOND_PLAN_ORDER.store(usize::MAX, Ordering::Relaxed);
    FIRST_WRITE_ORDER.store(usize::MAX, Ordering::Relaxed);
    SECOND_WRITE_ORDER.store(usize::MAX, Ordering::Relaxed);
    let mut output = [0; 4];
    let (view, suffix) = CommitOrderBuilder::new()
        .first(())
        .second(())
        .dynamic(0x33)
        .build_into(&mut output)
        .unwrap();
    assert_eq!(FIRST_PLAN_ORDER.load(Ordering::Relaxed), 0);
    assert_eq!(SECOND_PLAN_ORDER.load(Ordering::Relaxed), 1);
    assert_eq!(SECOND_WRITE_ORDER.load(Ordering::Relaxed), 2);
    assert_eq!(FIRST_WRITE_ORDER.load(Ordering::Relaxed), 3);
    assert_eq!(view.as_bytes(), &[2, 1, 0xf0, 0x33]);
    assert!(suffix.is_empty());
}

#[test]
fn region_only_builder_omits_its_auto_source_input() {
    let mut output = [0; 4];
    let (view, suffix) = RegionOnlyBuilder::new()
        .body(&[7, 8, 9])
        .build_into(&mut output)
        .unwrap();
    assert_eq!(view.as_bytes(), &[3, 7, 8, 9]);
    assert_eq!(view.length(), 3);
    assert_eq!(view.body(), &[7, 8, 9]);
    assert!(suffix.is_empty());
}