rigless 0.0.6

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a fork of QEMU built in to execute the instructions
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The link between an engine and a target: one process steps a plant, the other runs a firmware,
//! and they meet once per plant step.
//!
//! The engine spawns the target, `rigless run --link`, with the target's stdin and stdout as the two
//! halves of the link. The engine speaks first, [`Frame::Open`], naming the protocol [`VERSION`] it
//! speaks. The target answers [`Frame::Manifest`]: its own version, the machine, the runtime's version, and
//! the board's edge as fields. Its inputs are the board's signals, each [`Field`] with its unit and width,
//! with the value each rests at. Its outputs are what the board's firmware drives, each a [`Field`] the
//! same way, and its ports are the serial lines whose far end is the engine. An engine built from other code holds its own declarations
//! against that and refuses to go on when they differ. Then the engine asks and the target answers.
//! [`Frame::Advance`] asks the target to reach an instant, carrying the inputs that change and the
//! bytes to deliver on each port. [`Frame::Reached`] answers with where the run stopped, every output's
//! value, what the firmware sent on each port, every reset since the last answer and every [`Gap`] the
//! run met for the first time. [`Frame::Shutdown`] ends the run and is answered with [`Frame::Report`].
//! After `Manifest`, one frame is in flight at a time, so there are no sequence numbers.
//!
//! `Open`'s kind and its one field are frozen for every version, and so is `Manifest`'s first field, so a
//! target of any version reads the engine's and answers with its own before anything else can go wrong.
//! A target that doesn't know `Open` at all closes the link, which is how an engine finds a version-one
//! target instead of waiting on it.
//!
//! A frame is a length, a kind and the fields, little-endian integers with nothing padded and nothing
//! aligned, decoded by a reader that refuses a short frame, an unknown kind, an invalid value and a
//! trailing byte alike, never a panic. A port on the link has no socket: its bytes cross in the frames,
//! at instants the engine chose, so nothing outside the run reaches the firmware.
//!
//! [`Target`] is the engine's side, and [`Served`] is the target's.

use std::ffi::OsStr;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, ChildStdout, Command, ExitStatus, Stdio};

use crate::edge::Field;
use crate::emulator::{Stop, StopReason};
use crate::time::VirtualNanos;

mod serve;

pub use serve::{EnginePort, Gaps, attach_engine_ports, deliver, report, sent};

/// The protocol's version. `Manifest` carries it, and an engine speaking another refuses the target.
pub const VERSION: u16 = 2;

// ceiling: the largest frame either side reads; upgrade when a step's port bytes outgrow it.
const LARGEST_FRAME: usize = 1 << 20;

const KIND_ADVANCE: u8 = 1;
const KIND_REACHED: u8 = 2;
const KIND_SHUTDOWN: u8 = 3;
const KIND_REPORT: u8 = 4;
const KIND_MANIFEST: u8 = 5;
const KIND_OPEN: u8 = 6;

/// A value that crosses the link as bytes.
pub trait Wire: Sized {
    /// Appends the value's bytes.
    fn encode(&self, out: &mut Vec<u8>);

    /// Takes the value's bytes from the front of `bytes`.
    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError>;
}

/// Why bytes are not a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum WireError {
    /// The frame ends before the value does.
    #[error("the frame ends after {have} of the {need} bytes a value needs")]
    Short {
        /// What is left.
        have: usize,
        /// What the value needs.
        need: usize,
    },
    /// A byte or a word names nothing.
    #[error("{value} is no {what}")]
    Invalid {
        /// What it should have been.
        what: &'static str,
        /// What it was.
        value: u64,
    },
    /// Bytes follow the last value of the frame.
    #[error("{0} bytes follow the last value of the frame")]
    Trailing(usize),
}

fn take<'a>(bytes: &mut &'a [u8], need: usize) -> Result<&'a [u8], WireError> {
    if bytes.len() < need {
        return Err(WireError::Short {
            have: bytes.len(),
            need,
        });
    }
    let (taken, rest) = bytes.split_at(need);
    *bytes = rest;
    Ok(taken)
}

macro_rules! integer_wire {
    ($($int:ty),*) => {$(
        impl Wire for $int {
            fn encode(&self, out: &mut Vec<u8>) {
                out.extend_from_slice(&self.to_le_bytes());
            }

            fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
                let taken = take(bytes, size_of::<$int>())?;
                Ok(<$int>::from_le_bytes(taken.try_into().expect("taken that many")))
            }
        }
    )*};
}

integer_wire!(u8, u16, u32, u64, i32, i64);

impl Wire for bool {
    fn encode(&self, out: &mut Vec<u8>) {
        u8::from(*self).encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        match u8::decode(bytes)? {
            0 => Ok(false),
            1 => Ok(true),
            value => Err(WireError::Invalid {
                what: "bool",
                value: u64::from(value),
            }),
        }
    }
}

impl Wire for VirtualNanos {
    fn encode(&self, out: &mut Vec<u8>) {
        self.0.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        u64::decode(bytes).map(Self)
    }
}

impl<T: Wire, const N: usize> Wire for [T; N] {
    fn encode(&self, out: &mut Vec<u8>) {
        for value in self {
            value.encode(out);
        }
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let mut values = Vec::with_capacity(N);
        for _ in 0..N {
            values.push(T::decode(bytes)?);
        }
        Ok(values
            .try_into()
            .unwrap_or_else(|_| unreachable!("decoded N values")))
    }
}

impl<T: Wire> Wire for Option<T> {
    fn encode(&self, out: &mut Vec<u8>) {
        match self {
            None => false.encode(out),
            Some(value) => {
                true.encode(out);
                value.encode(out);
            }
        }
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        if bool::decode(bytes)? {
            T::decode(bytes).map(Some)
        } else {
            Ok(None)
        }
    }
}

impl<T: Wire> Wire for Vec<T> {
    fn encode(&self, out: &mut Vec<u8>) {
        u32::try_from(self.len())
            .expect("fewer values than a word counts")
            .encode(out);
        for value in self {
            value.encode(out);
        }
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let count = u32::decode(bytes)?;
        let mut values = Vec::new();
        for _ in 0..count {
            values.push(T::decode(bytes)?);
        }
        Ok(values)
    }
}

impl Wire for String {
    fn encode(&self, out: &mut Vec<u8>) {
        self.as_bytes().to_vec().encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Self::from_utf8(Vec::<u8>::decode(bytes)?).map_err(|error| WireError::Invalid {
            what: "text valid past this byte",
            value: error.utf8_error().valid_up_to() as u64,
        })
    }
}

impl Wire for Field {
    fn encode(&self, out: &mut Vec<u8>) {
        self.name.to_string().encode(out);
        self.unit.to_string().encode(out);
        self.width.encode(out);
        self.signed.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let name = String::decode(bytes)?.into();
        let unit = String::decode(bytes)?.into();
        let width = checked_width(u8::decode(bytes)?)?;
        Ok(Self {
            name,
            unit,
            width,
            signed: Wire::decode(bytes)?,
        })
    }
}

/// A field's width, if it's one a field can have.
fn checked_width(width: u8) -> Result<u8, WireError> {
    match width {
        1 | 2 | 4 | 8 => Ok(width),
        _ => Err(WireError::Invalid {
            what: "field width",
            value: u64::from(width),
        }),
    }
}

impl Wire for StopReason {
    fn encode(&self, out: &mut Vec<u8>) {
        let code: u8 = match self {
            Self::Deadline => 0,
            Self::Idle => 1,
            Self::Reset => 2,
        };
        code.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let code = u8::decode(bytes)?;
        Self::from_code(u32::from(code)).ok_or(WireError::Invalid {
            what: "stop reason",
            value: u64::from(code),
        })
    }
}

impl Wire for Stop {
    fn encode(&self, out: &mut Vec<u8>) {
        self.at.encode(out);
        self.instruction_count.encode(out);
        self.reason.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            at: Wire::decode(bytes)?,
            instruction_count: Wire::decode(bytes)?,
            reason: Wire::decode(bytes)?,
        })
    }
}

/// What a run recorded, as the target reports it when it is shut down.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Report {
    /// The instants the part restarted, in order.
    pub resets: Vec<VirtualNanos>,
    /// How many addresses the bus refused because no register covers the address, or the access runs
    /// past the register that does.
    pub unmapped: u64,
    /// How many accesses the bus refused for a reason other than a shut gate: the refused gaps. A shut
    /// gate is the part saying no, so it's counted nowhere.
    pub refused: u64,
    /// How many registers were answered with no model behind them.
    pub unimplemented: u64,
    /// How many interrupts had no line.
    pub unrouted: u64,
}

impl Wire for Report {
    fn encode(&self, out: &mut Vec<u8>) {
        self.resets.encode(out);
        self.unmapped.encode(out);
        self.refused.encode(out);
        self.unimplemented.encode(out);
        self.unrouted.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            resets: Wire::decode(bytes)?,
            unmapped: Wire::decode(bytes)?,
            refused: Wire::decode(bytes)?,
            unimplemented: Wire::decode(bytes)?,
            unrouted: Wire::decode(bytes)?,
        })
    }
}

/// The values of `fields` as `bytes` carries them, in order, each widened to an `i64`.
pub fn values_of(fields: &[Field], bytes: &[u8]) -> Result<Vec<i64>, WireError> {
    let mut rest = bytes;
    let mut values = Vec::with_capacity(fields.len());
    for field in fields {
        let width = checked_width(field.width)?;
        let raw = take(&mut rest, usize::from(width))?;
        let mut word = [0_u8; 8];
        word[..raw.len()].copy_from_slice(raw);
        let shift = 64 - 8 * u32::from(width);
        let value = u64::from_le_bytes(word).cast_signed();
        if !field.signed && value < 0 {
            return Err(WireError::Invalid {
                what: "unsigned value an i64 holds",
                value: value.cast_unsigned(),
            });
        }
        values.push(if field.signed {
            (value << shift) >> shift
        } else {
            value
        });
    }
    if !rest.is_empty() {
        return Err(WireError::Trailing(rest.len()));
    }
    Ok(values)
}

/// Whether `value` fits `field`'s width and sign. Every value crosses as an `i64`, so an unsigned
/// eight-byte field holds 0 to `i64::MAX`.
fn fits(field: &Field, value: i64) -> Result<bool, WireError> {
    let bits = 8 * u32::from(checked_width(field.width)?);
    Ok(match (bits, field.signed) {
        (64, true) => true,
        (64, false) => value >= 0,
        (bits, true) => (-(1_i64 << (bits - 1))..(1_i64 << (bits - 1))).contains(&value),
        (bits, false) => (0..(1_i64 << bits)).contains(&value),
    })
}

/// `values` as `fields` lay them out, one value to a field, or the first one its field can't hold.
pub fn bytes_of(fields: &[Field], values: &[i64]) -> Result<Vec<u8>, LinkError> {
    if fields.len() != values.len() {
        return Err(LinkError::Misfit(format!(
            "has {} values for {} fields",
            values.len(),
            fields.len()
        )));
    }
    let mut bytes = Vec::new();
    for (field, &value) in fields.iter().zip(values) {
        let width = checked_width(field.width)?;
        if !fits(field, value)? {
            return Err(LinkError::Misfit(format!(
                "puts {value} in {}, which is {} bytes {}",
                field.name,
                width,
                if field.signed { "signed" } else { "unsigned" }
            )));
        }
        bytes.extend_from_slice(&value.to_le_bytes()[..usize::from(width)]);
    }
    Ok(bytes)
}

/// The engine's first word: which version it speaks. Its kind and this field are frozen for good.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Open {
    /// The protocol's version on the engine's side.
    pub version: u16,
}

/// The target's first word: who it is and what it carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Manifest {
    /// The protocol's version on the target's side. Frozen as `Manifest`'s first field.
    pub version: u16,
    /// The machine the target runs, by the name `rigless run` takes.
    pub machine: String,
    /// The runtime's version.
    pub runtime: String,
    /// What the engine can set, field by field.
    pub inputs: Vec<Field>,
    /// What each input rests at before the engine sets it, in `inputs`' order.
    pub rest: Vec<i64>,
    /// What the target reports every step, field by field.
    pub outputs: Vec<Field>,
    /// The ports whose far end is the engine, in the order `Advance` and `Reached` carry them.
    pub ports: Vec<String>,
}

impl Wire for Manifest {
    fn encode(&self, out: &mut Vec<u8>) {
        self.version.encode(out);
        self.machine.encode(out);
        self.runtime.encode(out);
        self.inputs.encode(out);
        self.rest.encode(out);
        self.outputs.encode(out);
        self.ports.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            version: Wire::decode(bytes)?,
            machine: Wire::decode(bytes)?,
            runtime: Wire::decode(bytes)?,
            inputs: Wire::decode(bytes)?,
            rest: Wire::decode(bytes)?,
            outputs: Wire::decode(bytes)?,
            ports: Wire::decode(bytes)?,
        })
        .and_then(|manifest: Self| {
            if manifest.rest.len() != manifest.inputs.len() {
                return Err(WireError::Invalid {
                    what: "count of rest values for the inputs",
                    value: manifest.rest.len() as u64,
                });
            }
            for (index, (input, &rest)) in manifest.inputs.iter().zip(&manifest.rest).enumerate() {
                if !fits(input, rest)? {
                    return Err(WireError::Invalid {
                        what: "input whose rest value fits it",
                        value: index as u64,
                    });
                }
            }
            Ok(manifest)
        })
    }
}

/// A gap between the models and the part: something the run met that no model answers as the part
/// would, so a result from there on may not be the part's. Each is reported in the first `Reached`
/// after the run met it.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Gap {
    /// An address the bus refused because no register covers the address, or the access runs past
    /// the register that does, and the program counter of the first access to it.
    Unmapped {
        /// The address.
        address: u64,
        /// The program counter.
        program_counter: u64,
    },
    /// An access the bus refused for a reason other than a shut gate, and why: a model's access where no
    /// register is, or one that runs past its register. A shut gate is the part saying no, so it's the
    /// model answering and not a gap.
    Refused {
        /// The address.
        address: u64,
        /// Why, as the fault says it.
        why: String,
    },
    /// A register the part has and no model implements, answered from the register file.
    Unimplemented {
        /// The instance, as the part names it.
        instance: String,
        /// The register, as the part names it.
        register: String,
        /// The address.
        address: u64,
        /// The program counter of the first access.
        program_counter: u64,
    },
    /// An interrupt raised with no line to the core.
    Unrouted {
        /// The instance that raised it.
        instance: String,
        /// Its number on the part, from the instance's table.
        line: u16,
    },
}

impl Wire for Gap {
    fn encode(&self, out: &mut Vec<u8>) {
        match self {
            Self::Unmapped {
                address,
                program_counter,
            } => {
                0_u8.encode(out);
                address.encode(out);
                program_counter.encode(out);
            }
            Self::Refused { address, why } => {
                1_u8.encode(out);
                address.encode(out);
                why.encode(out);
            }
            Self::Unimplemented {
                instance,
                register,
                address,
                program_counter,
            } => {
                2_u8.encode(out);
                instance.encode(out);
                register.encode(out);
                address.encode(out);
                program_counter.encode(out);
            }
            Self::Unrouted { instance, line } => {
                3_u8.encode(out);
                instance.encode(out);
                line.encode(out);
            }
        }
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        match u8::decode(bytes)? {
            0 => Ok(Self::Unmapped {
                address: Wire::decode(bytes)?,
                program_counter: Wire::decode(bytes)?,
            }),
            1 => Ok(Self::Refused {
                address: Wire::decode(bytes)?,
                why: Wire::decode(bytes)?,
            }),
            2 => Ok(Self::Unimplemented {
                instance: Wire::decode(bytes)?,
                register: Wire::decode(bytes)?,
                address: Wire::decode(bytes)?,
                program_counter: Wire::decode(bytes)?,
            }),
            3 => Ok(Self::Unrouted {
                instance: Wire::decode(bytes)?,
                line: Wire::decode(bytes)?,
            }),
            code => Err(WireError::Invalid {
                what: "gap",
                value: u64::from(code),
            }),
        }
    }
}

/// One input the engine sets: its index in `Manifest`'s inputs and its new value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Set {
    /// The input's index.
    pub input: u16,
    /// Its value from now on.
    pub value: i64,
}

impl Wire for Set {
    fn encode(&self, out: &mut Vec<u8>) {
        self.input.encode(out);
        self.value.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            input: Wire::decode(bytes)?,
            value: Wire::decode(bytes)?,
        })
    }
}

/// Engine to target: reach an instant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Advance {
    /// The instant to reach.
    pub until: VirtualNanos,
    /// The inputs that change from now on. Every other input keeps its value.
    pub inputs: Vec<Set>,
    /// The bytes to deliver on each port from now on, one string per port in `Manifest`'s order.
    pub ports: Vec<Vec<u8>>,
}

impl Wire for Advance {
    fn encode(&self, out: &mut Vec<u8>) {
        self.until.encode(out);
        self.inputs.encode(out);
        self.ports.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            until: Wire::decode(bytes)?,
            inputs: Wire::decode(bytes)?,
            ports: Wire::decode(bytes)?,
        })
    }
}

/// Target to engine: the run reached the instant it was asked to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reached {
    /// Where and why it stopped.
    pub stop: Stop,
    /// Every output's value as it stands, in `Manifest`'s order.
    pub outputs: Vec<i64>,
    /// What the firmware sent on each port since the last answer, one string per port in `Manifest`'s order.
    pub ports: Vec<Vec<u8>>,
    /// The instants the part restarted since the last answer.
    pub resets: Vec<VirtualNanos>,
    /// What the run met for the first time since the last answer.
    pub gaps: Vec<Gap>,
}

impl Wire for Reached {
    fn encode(&self, out: &mut Vec<u8>) {
        self.stop.encode(out);
        self.outputs.encode(out);
        self.ports.encode(out);
        self.resets.encode(out);
        self.gaps.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            stop: Wire::decode(bytes)?,
            outputs: Wire::decode(bytes)?,
            ports: Wire::decode(bytes)?,
            resets: Wire::decode(bytes)?,
            gaps: Wire::decode(bytes)?,
        })
    }
}

/// One frame of the link.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Frame {
    /// Engine to target, first: the version it speaks.
    Open(Open),
    /// Target to engine, in answer: who it is and what it carries.
    Manifest(Manifest),
    /// Engine to target: reach an instant.
    Advance(Advance),
    /// Target to engine: the run reached it.
    Reached(Reached),
    /// Engine to target: end the run.
    Shutdown,
    /// Target to engine: what the run recorded, and the last thing it says.
    Report(Report),
}

impl Frame {
    fn kind(&self) -> &'static str {
        match self {
            Self::Open(_) => "Open",
            Self::Manifest(_) => "Manifest",
            Self::Advance(_) => "Advance",
            Self::Reached(_) => "Reached",
            Self::Shutdown => "Shutdown",
            Self::Report(_) => "Report",
        }
    }

    /// Writes the frame whole: its length, its kind, and its fields.
    pub fn write_to(&self, output: &mut impl Write) -> io::Result<()> {
        let mut body = Vec::new();
        match self {
            Self::Open(open) => {
                KIND_OPEN.encode(&mut body);
                open.version.encode(&mut body);
            }
            Self::Manifest(manifest) => {
                KIND_MANIFEST.encode(&mut body);
                manifest.encode(&mut body);
            }
            Self::Advance(advance) => {
                KIND_ADVANCE.encode(&mut body);
                advance.encode(&mut body);
            }
            Self::Reached(reached) => {
                KIND_REACHED.encode(&mut body);
                reached.encode(&mut body);
            }
            Self::Shutdown => KIND_SHUTDOWN.encode(&mut body),
            Self::Report(report) => {
                KIND_REPORT.encode(&mut body);
                report.encode(&mut body);
            }
        }
        let length = u32::try_from(body.len()).expect("a frame is shorter than a word counts");
        output.write_all(&length.to_le_bytes())?;
        output.write_all(&body)?;
        output.flush()
    }

    /// Reads one frame, or says why the bytes are not one. A `Manifest` from another version is refused
    /// by its first field, before the rest of it is read.
    pub fn read_from(input: &mut impl Read) -> Result<Self, LinkError> {
        let mut length = [0; 4];
        match input.read_exact(&mut length) {
            Ok(()) => {}
            Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => {
                return Err(LinkError::Closed);
            }
            Err(error) => return Err(LinkError::Io(error)),
        }
        let length = usize::try_from(u32::from_le_bytes(length)).expect("a word fits");
        if length > LARGEST_FRAME {
            return Err(LinkError::Wire(WireError::Invalid {
                what: "frame length",
                value: length as u64,
            }));
        }
        let mut body = vec![0; length];
        input.read_exact(&mut body)?;
        let mut bytes = &body[..];
        let frame = match u8::decode(&mut bytes)? {
            KIND_OPEN => Self::Open(Open {
                version: Wire::decode(&mut bytes)?,
            }),
            KIND_MANIFEST => {
                let mut peek = bytes;
                let version = u16::decode(&mut peek)?;
                if version != VERSION {
                    return Err(LinkError::Version { theirs: version });
                }
                Self::Manifest(Wire::decode(&mut bytes)?)
            }
            KIND_ADVANCE => Self::Advance(Wire::decode(&mut bytes)?),
            KIND_REACHED => Self::Reached(Wire::decode(&mut bytes)?),
            KIND_SHUTDOWN => Self::Shutdown,
            KIND_REPORT => Self::Report(Wire::decode(&mut bytes)?),
            kind => {
                return Err(LinkError::Wire(WireError::Invalid {
                    what: "frame kind",
                    value: u64::from(kind),
                }));
            }
        };
        if !bytes.is_empty() {
            return Err(LinkError::Wire(WireError::Trailing(bytes.len())));
        }
        Ok(frame)
    }
}

/// What can go wrong on the link.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LinkError {
    /// The other side went away.
    #[error("the other side of the link closed it")]
    Closed,
    /// The pipe failed.
    #[error(transparent)]
    Io(#[from] io::Error),
    /// The bytes are not a frame.
    #[error(transparent)]
    Wire(#[from] WireError),
    /// A frame the protocol does not allow here.
    #[error("the link carried {got} where {wanted} was expected")]
    Unexpected {
        /// What came.
        got: &'static str,
        /// What the protocol allows.
        wanted: &'static str,
    },
    /// The other side speaks another version of the protocol.
    #[error(
        "the other side speaks the step protocol version {theirs} and this side speaks {VERSION}"
    )]
    Version {
        /// The version the other side named.
        theirs: u16,
    },
    /// An `Advance` that doesn't fit the board the target said it has, or asks for an instant the run
    /// can't reach.
    #[error("the engine {0}")]
    Misfit(String),
    /// A board that can't be a target as it's built: a port it won't take, or won't hand back.
    #[error("the board {0}")]
    Board(String),
    /// The target could not be started.
    #[error("starting {binary}: {source}", binary = binary.display())]
    Spawn {
        /// The binary.
        binary: PathBuf,
        /// Why.
        #[source]
        source: io::Error,
    },
    /// The target ended, and not well.
    #[error("the target exited with {0}")]
    Exited(ExitStatus),
}

/// The engine's side of the link: a target it spawned and speaks to.
#[derive(Debug)]
pub struct Target {
    child: Child,
    input: ChildStdout,
    output: ChildStdin,
    manifest: Manifest,
}

impl Target {
    /// Spawns `binary` as `run --link --machine <machine> <arguments...> <firmware>`, its stdin and
    /// stdout as the link and its stderr inherited, so what it says about itself reaches the terminal.
    /// Opens the link and takes the target's `Manifest`, refusing a target of another version.
    pub fn spawn(
        binary: &Path,
        machine: &str,
        firmware: &Path,
        arguments: &[impl AsRef<OsStr>],
    ) -> Result<Self, LinkError> {
        let mut child = Command::new(binary)
            .args(["run", "--link", "--machine", machine])
            .args(arguments)
            .arg(firmware)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .map_err(|source| LinkError::Spawn {
                binary: binary.to_path_buf(),
                source,
            })?;
        let mut output = child.stdin.take().expect("piped");
        let mut input = child.stdout.take().expect("piped");
        let opened = Frame::Open(Open { version: VERSION })
            .write_to(&mut output)
            .map_err(LinkError::from)
            .and_then(|()| match Frame::read_from(&mut input)? {
                Frame::Manifest(manifest) => Ok(manifest),
                other => Err(LinkError::Unexpected {
                    got: other.kind(),
                    wanted: "Manifest",
                }),
            });
        let manifest = match opened {
            Ok(manifest) => manifest,
            Err(error) => {
                child.kill().ok();
                child.wait().ok();
                return Err(error);
            }
        };
        Ok(Self {
            child,
            input,
            output,
            manifest,
        })
    }

    /// What the target said it is.
    #[must_use]
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// Asks the target to reach `until` with `inputs` changed and `ports` delivered, and answers what it
    /// reached. `ports` has one string per port the target named, empty for nothing to send.
    pub fn advance(
        &mut self,
        until: VirtualNanos,
        inputs: Vec<Set>,
        ports: Vec<Vec<u8>>,
    ) -> Result<Reached, LinkError> {
        Frame::Advance(Advance {
            until,
            inputs,
            ports,
        })
        .write_to(&mut self.output)?;
        match Frame::read_from(&mut self.input)? {
            Frame::Reached(reached) => Ok(reached),
            other => Err(LinkError::Unexpected {
                got: other.kind(),
                wanted: "Reached",
            }),
        }
    }

    /// Ends the run and takes its report. The target exits after.
    pub fn shutdown(mut self) -> Result<Report, LinkError> {
        Frame::Shutdown.write_to(&mut self.output)?;
        let report = match Frame::read_from(&mut self.input)? {
            Frame::Report(report) => report,
            other => {
                return Err(LinkError::Unexpected {
                    got: other.kind(),
                    wanted: "Report",
                });
            }
        };
        let status = self.child.wait()?;
        if !status.success() {
            return Err(LinkError::Exited(status));
        }
        Ok(report)
    }
}

impl Drop for Target {
    fn drop(&mut self) {
        // A target whose link closes ends itself. This is for one that didn't get the chance.
        if matches!(self.child.try_wait(), Ok(None)) {
            self.child.kill().ok();
            self.child.wait().ok();
        }
    }
}

/// The target's side of the link: the engine on its stdin and stdout.
#[derive(Debug)]
pub struct Served<R: Read, W: Write> {
    input: R,
    output: W,
}

impl Served<io::Stdin, io::Stdout> {
    /// The link on this process's own stdin and stdout.
    #[must_use]
    pub fn stdio() -> Self {
        Self {
            input: io::stdin(),
            output: io::stdout(),
        }
    }
}

impl<R: Read, W: Write> Served<R, W> {
    /// The link over any two streams.
    pub fn over(input: R, output: W) -> Self {
        Self { input, output }
    }

    /// Takes the engine's `Open`, answers with `manifest` whatever version the engine speaks, and says
    /// whether the two agree.
    pub fn open(&mut self, manifest: &Manifest) -> Result<(), LinkError> {
        let open = match Frame::read_from(&mut self.input)? {
            Frame::Open(open) => open,
            other => {
                return Err(LinkError::Unexpected {
                    got: other.kind(),
                    wanted: "Open",
                });
            }
        };
        Frame::Manifest(manifest.clone()).write_to(&mut self.output)?;
        if open.version == VERSION {
            Ok(())
        } else {
            Err(LinkError::Version {
                theirs: open.version,
            })
        }
    }

    /// The engine's next word: where to reach and with what, or that the run is over.
    pub fn receive(&mut self) -> Result<Frame, LinkError> {
        match Frame::read_from(&mut self.input)? {
            frame @ (Frame::Advance(_) | Frame::Shutdown) => Ok(frame),
            other => Err(LinkError::Unexpected {
                got: other.kind(),
                wanted: "Advance or Shutdown",
            }),
        }
    }

    /// Tells the engine the run reached the instant it asked for.
    pub fn reached(&mut self, reached: Reached) -> Result<(), LinkError> {
        Ok(Frame::Reached(reached).write_to(&mut self.output)?)
    }

    /// The last word: what the run recorded.
    pub fn report(&mut self, report: Report) -> Result<(), LinkError> {
        Ok(Frame::Report(report).write_to(&mut self.output)?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn round_trip(frame: &Frame) -> Frame {
        let mut bytes = Vec::new();
        frame.write_to(&mut bytes).unwrap();
        Frame::read_from(&mut &bytes[..]).unwrap()
    }

    #[test]
    fn every_frame_reads_back_as_it_was_written() {
        let stop = Stop {
            at: VirtualNanos(5_000_000),
            instruction_count: 1234,
            reason: StopReason::Idle,
        };
        let frames = [
            Frame::Open(Open { version: VERSION }),
            Frame::Manifest(Manifest {
                version: VERSION,
                machine: "bench".to_owned(),
                runtime: "0.0.6".to_owned(),
                inputs: vec![
                    Field::new("rate.x", "mdeg/s", 4, true),
                    Field::new("pressure", "Pa", 4, false),
                ],
                rest: vec![0, 101_325],
                outputs: vec![
                    Field::new("valve", "", 1, false),
                    Field::new("heater.duty", "1e-3", 2, false),
                ],
                ports: vec!["wire1".to_owned()],
            }),
            Frame::Advance(Advance {
                until: VirtualNanos(5_000_000),
                inputs: Vec::new(),
                ports: vec![Vec::new()],
            }),
            Frame::Advance(Advance {
                until: VirtualNanos(10_000_000),
                inputs: vec![Set {
                    input: 1,
                    value: 90_000,
                }],
                ports: vec![b"hello".to_vec()],
            }),
            Frame::Reached(Reached {
                stop,
                outputs: vec![1_500_000, 2_500_000, 500],
                ports: vec![vec![0xfd, 0x09]],
                resets: vec![VirtualNanos(4_000_000)],
                gaps: vec![
                    Gap::Unmapped {
                        address: 0x1000,
                        program_counter: 0x20,
                    },
                    Gap::Refused {
                        address: 0x2000,
                        why: "gated".to_owned(),
                    },
                    Gap::Unimplemented {
                        instance: "TIMER".to_owned(),
                        register: "CONTROL".to_owned(),
                        address: 0x3000,
                        program_counter: 0x30,
                    },
                    Gap::Unrouted {
                        instance: "TIMER".to_owned(),
                        line: 7,
                    },
                ],
            }),
            Frame::Shutdown,
            Frame::Report(Report {
                resets: vec![VirtualNanos(7)],
                unmapped: 1,
                refused: 2,
                unimplemented: 3,
                unrouted: 4,
            }),
        ];
        for frame in &frames {
            assert_eq!(&round_trip(frame), frame);
        }
    }

    #[test]
    fn a_short_frame_an_unknown_kind_and_a_trailing_byte_are_refused_and_a_closed_link_is_named() {
        assert!(matches!(
            Frame::read_from(&mut &[][..]),
            Err(LinkError::Closed)
        ));
        let short = [3u8, 0, 0, 0, KIND_ADVANCE, 1, 2];
        assert!(matches!(
            Frame::read_from(&mut &short[..]),
            Err(LinkError::Wire(WireError::Short { .. }))
        ));
        let unknown = [1u8, 0, 0, 0, 9];
        assert!(matches!(
            Frame::read_from(&mut &unknown[..]),
            Err(LinkError::Wire(WireError::Invalid {
                what: "frame kind",
                value: 9
            }))
        ));
        let trailing = [2u8, 0, 0, 0, KIND_SHUTDOWN, 0];
        assert!(matches!(
            Frame::read_from(&mut &trailing[..]),
            Err(LinkError::Wire(WireError::Trailing(1)))
        ));
    }

    #[test]
    fn open_is_kind_six_and_its_version_and_the_manifest_starts_with_its_version() {
        let mut bytes = Vec::new();
        Frame::Open(Open { version: 0x0102 })
            .write_to(&mut bytes)
            .unwrap();
        assert_eq!(
            bytes,
            [3, 0, 0, 0, 6, 0x02, 0x01],
            "frozen for every version"
        );
        let mut manifest = Vec::new();
        Frame::Manifest(Manifest {
            version: VERSION,
            machine: String::new(),
            runtime: String::new(),
            inputs: Vec::new(),
            rest: Vec::new(),
            outputs: Vec::new(),
            ports: Vec::new(),
        })
        .write_to(&mut manifest)
        .unwrap();
        assert_eq!(manifest[4], KIND_MANIFEST);
        assert_eq!(
            &manifest[5..7],
            VERSION.to_le_bytes(),
            "frozen as the first field"
        );
    }

    #[test]
    fn the_target_answers_an_engine_of_another_version_with_its_manifest_and_then_refuses() {
        let mut from_engine = Vec::new();
        Frame::Open(Open {
            version: VERSION + 1,
        })
        .write_to(&mut from_engine)
        .unwrap();
        let manifest = Manifest {
            version: VERSION,
            machine: "bench".to_owned(),
            runtime: "0.0.6".to_owned(),
            inputs: Vec::new(),
            rest: Vec::new(),
            outputs: Vec::new(),
            ports: Vec::new(),
        };
        let mut served = Served::over(&from_engine[..], Vec::new());
        assert!(matches!(
            served.open(&manifest),
            Err(LinkError::Version { theirs }) if theirs == VERSION + 1
        ));
        assert_eq!(
            Frame::read_from(&mut &served.output[..]).unwrap(),
            Frame::Manifest(manifest),
            "the engine learns which version the target speaks"
        );
    }

    #[test]
    fn a_manifest_whose_rest_values_do_not_match_its_inputs_is_refused() {
        let manifest = Manifest {
            version: VERSION,
            machine: String::new(),
            runtime: String::new(),
            inputs: vec![Field::new("a", "", 4, true)],
            rest: Vec::new(),
            outputs: Vec::new(),
            ports: Vec::new(),
        };
        let mut bytes = Vec::new();
        manifest.encode(&mut bytes);
        assert!(Manifest::decode(&mut &bytes[..]).is_err());
    }

    #[test]
    fn a_manifest_from_another_version_is_refused_by_its_first_field() {
        let mut body = vec![KIND_MANIFEST];
        (VERSION + 1).encode(&mut body);
        body.extend_from_slice(&[0xff; 3]);
        let mut bytes = u32::try_from(body.len()).unwrap().to_le_bytes().to_vec();
        bytes.extend_from_slice(&body);
        assert!(matches!(
            Frame::read_from(&mut &bytes[..]),
            Err(LinkError::Version { theirs }) if theirs == VERSION + 1
        ));
    }

    #[test]
    fn values_cross_as_their_fields_lay_them_out_and_one_that_does_not_fit_is_refused() {
        let fields = [
            Field::new("a", "", 1, true),
            Field::new("b", "", 2, false),
            Field::new("c", "", 4, true),
            Field::new("d", "", 8, false),
        ];
        let values = [-3, 65_535, -2_000_000_000, 1 << 40];
        let bytes = bytes_of(&fields, &values).unwrap();
        assert_eq!(bytes.len(), 15);
        assert_eq!(values_of(&fields, &bytes).unwrap(), values);
        assert!(bytes_of(&fields[..1], &[128]).is_err(), "past an i8");
        assert!(bytes_of(&fields[1..2], &[-1]).is_err(), "below a u16");
        assert!(bytes_of(&fields[3..], &[-1]).is_err(), "below a u64");
        assert!(
            bytes_of(&fields, &[1]).is_err(),
            "one value for four fields"
        );
        assert!(matches!(
            values_of(&fields[..1], &[1, 2]),
            Err(WireError::Trailing(1))
        ));
    }

    #[test]
    fn text_that_is_not_utf8_and_a_gap_that_names_nothing_are_refused() {
        let mut bytes = Vec::new();
        vec![0xff_u8, 0xfe].encode(&mut bytes);
        assert!(matches!(
            String::decode(&mut &bytes[..]),
            Err(WireError::Invalid {
                what: "text valid past this byte",
                value: 0
            })
        ));
        assert!(matches!(
            Gap::decode(&mut &[9_u8][..]),
            Err(WireError::Invalid {
                what: "gap",
                value: 9
            })
        ));
        let mut wide = Vec::new();
        Field::new("a", "", 3, false).encode(&mut wide);
        assert!(matches!(
            Field::decode(&mut &wide[..]),
            Err(WireError::Invalid {
                what: "field width",
                value: 3
            })
        ));
    }

    /// Bytes spelled the way `STEP_PROTOCOL.md`'s table spells them, apart from the code under test: a
    /// little-endian integer of `bytes` bytes, and text as a `u32` length and its UTF-8.
    fn le(value: u64, bytes: usize) -> Vec<u8> {
        value.to_le_bytes()[..bytes].to_vec()
    }

    fn text(value: &str) -> Vec<u8> {
        [le(value.len() as u64, 4), value.as_bytes().to_vec()].concat()
    }

    fn framed(body: &[Vec<u8>]) -> Vec<u8> {
        let body = body.concat();
        [le(body.len() as u64, 4), body].concat()
    }

    /// The engine reads these frames with code of its own, so a field that moves on this side is a link
    /// that no longer works. Each frame is written out from the table, and the codec has to write
    /// exactly those bytes and read them back.
    fn is_written_as(frame: &Frame, bytes: &[u8]) {
        let mut written = Vec::new();
        frame.write_to(&mut written).unwrap();
        assert_eq!(written, bytes, "{frame:?} as it's written");
        assert_eq!(
            &Frame::read_from(&mut &bytes[..]).unwrap(),
            frame,
            "{frame:?} as it's read"
        );
    }

    #[test]
    fn the_manifest_and_report_are_the_bytes_the_protocol_names() {
        let manifest = Frame::Manifest(Manifest {
            version: 2,
            machine: "m".to_owned(),
            runtime: "r".to_owned(),
            inputs: vec![Field::new("a", "u", 2, true)],
            rest: vec![-1],
            outputs: vec![Field::new("b", "", 1, false)],
            ports: vec!["p".to_owned()],
        });
        is_written_as(
            &manifest,
            &framed(&[
                le(5, 1),
                le(2, 2),
                text("m"),
                text("r"),
                le(1, 4),
                text("a"),
                text("u"),
                le(2, 1),
                le(1, 1),
                le(1, 4),
                le(u64::MAX, 8),
                le(1, 4),
                text("b"),
                text(""),
                le(1, 1),
                le(0, 1),
                le(1, 4),
                text("p"),
            ]),
        );
        let report = Frame::Report(Report {
            resets: vec![VirtualNanos(5)],
            unmapped: 1,
            refused: 2,
            unimplemented: 3,
            unrouted: 4,
        });
        is_written_as(
            &report,
            &framed(&[
                le(4, 1),
                le(1, 4),
                le(5, 8),
                le(1, 8),
                le(2, 8),
                le(3, 8),
                le(4, 8),
            ]),
        );
    }

    #[test]
    fn open_advance_and_shutdown_are_the_bytes_the_protocol_names() {
        is_written_as(
            &Frame::Open(Open { version: 0x0201 }),
            &framed(&[le(6, 1), le(0x0201, 2)]),
        );
        let advance = Frame::Advance(Advance {
            until: VirtualNanos(0x1122_3344_5566_7788),
            inputs: vec![Set {
                input: 0x0201,
                value: -2,
            }],
            ports: vec![b"ab".to_vec()],
        });
        is_written_as(
            &advance,
            &framed(&[
                le(1, 1),
                le(0x1122_3344_5566_7788, 8),
                le(1, 4),
                le(0x0201, 2),
                le((-2_i64).cast_unsigned(), 8),
                le(1, 4),
                le(2, 4),
                b"ab".to_vec(),
            ]),
        );
        is_written_as(&Frame::Shutdown, &framed(&[le(3, 1)]));
    }

    #[test]
    fn reached_and_each_gap_tag_are_the_bytes_the_protocol_names() {
        let reached = Frame::Reached(Reached {
            stop: Stop {
                at: VirtualNanos(10),
                instruction_count: 11,
                reason: StopReason::Reset,
            },
            outputs: vec![-1],
            ports: vec![b"z".to_vec()],
            resets: vec![VirtualNanos(7)],
            gaps: vec![
                Gap::Unmapped {
                    address: 0x1000,
                    program_counter: 0x20,
                },
                Gap::Refused {
                    address: 0x2000,
                    why: "g".to_owned(),
                },
                Gap::Unimplemented {
                    instance: "T".to_owned(),
                    register: "R".to_owned(),
                    address: 0x3000,
                    program_counter: 0x30,
                },
                Gap::Unrouted {
                    instance: "T".to_owned(),
                    line: 7,
                },
            ],
        });
        let stop = [le(10, 8), le(11, 8), le(2, 1)].concat();
        let gaps = [
            [le(0, 1), le(0x1000, 8), le(0x20, 8)].concat(),
            [le(1, 1), le(0x2000, 8), text("g")].concat(),
            [le(2, 1), text("T"), text("R"), le(0x3000, 8), le(0x30, 8)].concat(),
            [le(3, 1), text("T"), le(7, 2)].concat(),
        ]
        .concat();
        is_written_as(
            &reached,
            &framed(&[
                le(2, 1),
                stop,
                le(1, 4),
                le(u64::MAX, 8),
                le(1, 4),
                le(1, 4),
                b"z".to_vec(),
                le(1, 4),
                le(7, 8),
                le(4, 4),
                gaps,
            ]),
        );
    }

    #[test]
    fn a_frame_longer_than_a_mebibyte_is_refused_before_its_body_is_read() {
        let length = u32::try_from(LARGEST_FRAME + 1).unwrap().to_le_bytes();
        assert!(matches!(
            Frame::read_from(&mut &length[..]),
            Err(LinkError::Wire(WireError::Invalid {
                what: "frame length",
                ..
            }))
        ));
    }

    #[test]
    fn a_manifest_whose_rest_value_does_not_fit_its_input_is_refused() {
        let manifest = Manifest {
            version: VERSION,
            machine: String::new(),
            runtime: String::new(),
            inputs: vec![Field::new("a", "", 1, false)],
            rest: vec![300],
            outputs: Vec::new(),
            ports: Vec::new(),
        };
        let mut bytes = Vec::new();
        manifest.encode(&mut bytes);
        assert!(matches!(
            Manifest::decode(&mut &bytes[..]),
            Err(WireError::Invalid {
                what: "input whose rest value fits it",
                value: 0
            })
        ));
    }

    #[test]
    fn an_unsigned_eight_byte_value_past_what_an_i64_holds_is_refused_rather_than_turned_negative()
    {
        let field = [Field::new("wide", "", 8, false)];
        assert!(matches!(
            values_of(&field, &u64::MAX.to_le_bytes()),
            Err(WireError::Invalid {
                what: "unsigned value an i64 holds",
                ..
            })
        ));
        assert_eq!(
            values_of(&field, &i64::MAX.to_le_bytes()).unwrap(),
            [i64::MAX]
        );
    }

    #[test]
    fn the_served_side_takes_only_what_the_engine_may_send() {
        let mut bytes = Vec::new();
        Frame::Report(Report::default())
            .write_to(&mut bytes)
            .unwrap();
        let mut served = Served::over(&bytes[..], Vec::new());
        assert!(matches!(
            served.receive(),
            Err(LinkError::Unexpected { got: "Report", .. })
        ));
    }
}