rigless 0.3.0

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 CPU core of its own that translates the firmware's instructions to host code
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The board's edge: what crosses it, and the trait a board with a world implements.
//!
//! A firmware reaches the world through pins and chips. On the way out it drives outputs, and on the way
//! in the world reaches its transducers. Both halves are the board's own types, because what one board
//! drives and measures is not what another does: a flight controller's outputs are pulses to speed
//! controllers and a pump controller's may be a valve and a relay. [`Edge::Outputs`] is what the firmware
//! drives, read off the pins by [`Edge::drive`], and [`Edge::Signals`] is what the world does to the
//! transducers, which [`Edge::sense`] hands to the chips. Whatever steps a plant reads the one and writes
//! the other between rounds of the session, when every target stands at one instant. The runtime steps
//! no plant and names none: the session and the command line reach a board's edge only as bytes, through
//! [`Coupled`], and only a host that holds the board as its own type reads and senses it typed.
//!
//! Every quantity a board declares is an integer in the unit its chips take, so a value crosses the seam
//! and lands in a register without a rounding of its own on the way. The chips keep only the setters
//! their datasheets name, each on the chip's own axes, and the board, which is the one thing that knows
//! how each package is mounted and what each pin drives, is what turns its signals into those calls and
//! its pins into its outputs. A timer's pin carries a [`Pulse`].
//!
//! A board can also be what's wrong. [`Edge::Conditions`] is the board's own list of what can fail on
//! it, apart from the world: a chip that stops answering, or one that senses a stuck, biased or noisy
//! value while the chip beside it senses the truth. Every condition rests at zero, the board as built,
//! and the chips never learn of one. A silent chip is a [`crate::chip::Place`] its controller skips,
//! and a wrong reading is the board handing the chip another value through a [`Sensed`]. The board
//! names its chips in [`Edge::CHIPS`] and hands out each one's place, which counts the transactions
//! a trigger waits on and takes a flipped word or a lost transaction once.
//!
//! Anything random on a board comes from [`draw`], a function of the run's seed, the name of what it's
//! for and an index, and nothing else. No generator holds state, so setting one condition never moves
//! another's noise, and a seed gives the same run on any host.

use std::borrow::Cow;

use crate::chip::Placed;
use crate::link::{LARGEST_FRAME, Wire, WireError, checked_width};
use crate::machine::Board;
use crate::time::VirtualNanos;

/// A board with a world: what its firmware drives, what its transducers sense, and how both cross the
/// link.
///
/// The types are the board's because the quantities are: a board declares what its firmware drives and
/// what its transducers measure, in the units its chips take and on the axes its description names, and a
/// plant for that board takes the one and answers the other. A board with nothing to drive or sense has
/// no edge. Nothing here needs the board itself, so a plant's own tests can declare an edge on a
/// stand-in that runs no firmware.
pub trait Edge {
    /// What the world does to this board's transducers from one step to the next.
    type Signals;

    /// What the firmware drives, as the board reads it off its pins.
    type Outputs;

    /// What can be wrong with the board itself rather than the world it senses. Every one of its
    /// fields rests at zero, the board as built.
    type Conditions;

    /// The signals' fields in the order their bytes cross the link, each with its unit and width, so an
    /// engine that doesn't share this crate can check what it sends against what the board takes.
    const FIELDS: &'static [Field];

    /// The outputs' fields in the order their bytes cross the link, each with its unit and width.
    /// [`Edge::Outputs`] reads all-zero bytes back, which is how a session measures it against them.
    const OUTPUT_FIELDS: &'static [Field];

    /// The conditions' fields in the order their bytes cross the link, each with its unit and width.
    /// Each rests at zero. None by default, for a board with `type Conditions = ()`.
    const CONDITIONS: &'static [Field] = &[];

    /// The signals the board is built sensing, before anything changes them. The board's constructor
    /// senses them, since nothing else does: an engine sends only what changes from them.
    const REST: Self::Signals;

    /// The chips on the board a trigger can count and a one-shot fault can reach, by the names a
    /// condition gives them, in the order [`Edge::place`] takes.
    // ceiling: the board's chips, on the one MCU a process runs; upgrade when a board with two MCUs
    // has chips on each, with the list kept per target
    const CHIPS: &'static [&'static str] = &[];

    /// The place of the chip at `chip` in [`Edge::CHIPS`], or `None` past its end. What a trigger
    /// counts there is what the chip's controller marks on its [`Place`](crate::chip::Place): a
    /// transaction from [`Place::begin`](crate::chip::Place::begin) to
    /// [`Place::release`](crate::chip::Place::release), and a word it answers through
    /// [`Place::answered`](crate::chip::Place::answered) or
    /// [`Place::sent`](crate::chip::Place::sent). A controller that marks neither has chips no
    /// trigger counts and no flip reaches. None by default, for a board that names no chips. A board
    /// that names chips and leaves this out is refused when its session opens.
    fn place(&mut self, chip: usize) -> Option<&mut dyn Placed> {
        let _ = chip;
        None
    }

    /// What the world does to the board from now on. The board hands each chip its share on the chip's
    /// own axes.
    fn sense(&mut self, signals: &Self::Signals);

    /// What's wrong with the board from now on. It takes effect at once, on the signals the board last
    /// sensed, which the board keeps for that.
    fn condition(&mut self, conditions: &Self::Conditions);

    /// Draws what's random on the board for the step about to run, under the run's `seed`, and holds
    /// it for the step. `index` counts the steps before this one, from 0. A board with nothing random
    /// does nothing.
    fn draw(&mut self, _seed: u64, _index: u64) {}

    /// What the firmware drives as it stands, read off the board's pins.
    fn drive(&mut self) -> Self::Outputs;
}

/// A board's edge reached without its types: what the command line hands to the engine's link, which
/// carries the outputs, the signals and the conditions as bytes and never names their types.
///
/// Every [`Edge`] whose outputs, signals and conditions cross the wire is one, and nothing implements
/// it by hand.
pub trait Coupled: Board {
    /// [`Edge::FIELDS`].
    fn fields(&self) -> &'static [Field];

    /// [`Edge::OUTPUT_FIELDS`].
    fn output_fields(&self) -> &'static [Field];

    /// [`Edge::REST`], as the wire carries it.
    fn rest_wire(&self) -> Vec<u8>;

    /// [`Edge::sense`], from the signals as the wire carries them.
    fn sense_wire(&mut self, bytes: &[u8]) -> Result<(), WireError>;

    /// [`Edge::CONDITIONS`].
    fn conditions(&self) -> &'static [Field];

    /// [`Edge::condition`], from the conditions as the wire carries them.
    fn condition_wire(&mut self, bytes: &[u8]) -> Result<(), WireError>;

    /// [`Edge::draw`].
    fn draw(&mut self, seed: u64, index: u64);

    /// [`Edge::drive`], as the wire carries it.
    fn drive_wire(&mut self) -> Vec<u8>;

    /// [`Edge::CHIPS`].
    fn chips(&self) -> &'static [&'static str];

    /// [`Edge::place`].
    fn place(&mut self, chip: usize) -> Option<&mut dyn Placed>;

    /// That every field in [`Edge::FIELDS`], [`Edge::OUTPUT_FIELDS`] and [`Edge::CONDITIONS`] is 1,
    /// 2, 4 or 8 bytes wide, that each list adds up to the bytes its type takes on the wire, and that
    /// [`Edge::place`] has a place for every chip in [`Edge::CHIPS`]. A session checks it before
    /// anything runs, so a declaration that doesn't match the board is named there rather than read as
    /// a short frame later. The outputs' and the conditions' types are measured by reading all-zero
    /// bytes back.
    fn check(&mut self) -> Result<(), Mismatch>;
}

/// Which of a board's lists of fields a [`Mismatch`] is about. It prints as the constant's name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Declaration {
    /// [`Edge::FIELDS`], which [`Edge::Signals`] carries.
    Fields,
    /// [`Edge::OUTPUT_FIELDS`], which [`Edge::Outputs`] carries.
    OutputFields,
    /// [`Edge::CONDITIONS`], which [`Edge::Conditions`] carries.
    Conditions,
}

impl Declaration {
    /// The type that carries the list: `Signals`, `Outputs` or `Conditions`.
    #[must_use]
    pub fn carrier(self) -> &'static str {
        match self {
            Self::Fields => "Signals",
            Self::OutputFields => "Outputs",
            Self::Conditions => "Conditions",
        }
    }
}

impl std::fmt::Display for Declaration {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Fields => "FIELDS",
            Self::OutputFields => "OUTPUT_FIELDS",
            Self::Conditions => "CONDITIONS",
        })
    }
}

/// A board whose edge declares what the board doesn't carry, found before its first step.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Mismatch {
    /// A field is a width no field can have.
    #[error("{machine}'s {declaration} give {field} {width} bytes, and a field takes 1, 2, 4 or 8")]
    Width {
        /// The board.
        machine: &'static str,
        /// The list the field is in.
        declaration: Declaration,
        /// The field, by its name.
        field: Cow<'static, str>,
        /// The width it was given.
        width: u8,
    },
    /// The fields add up to one number of bytes, and the type takes another.
    #[error(
        "{machine}'s {declaration} add up to {declared} bytes, and its {} type takes {carried} on the wire",
        .declaration.carrier()
    )]
    Total {
        /// The board.
        machine: &'static str,
        /// The list that doesn't add up.
        declaration: Declaration,
        /// What the fields add up to.
        declared: usize,
        /// What the type takes.
        carried: usize,
    },
    /// The type doesn't read zero bytes back, though every field it carries is an integer.
    #[error(
        "{machine}'s {} type doesn't read zero bytes back: {why}",
        .declaration.carrier()
    )]
    Unread {
        /// The board.
        machine: &'static str,
        /// The list whose type doesn't read zeros: the outputs' or the conditions'.
        declaration: Declaration,
        /// Why.
        why: WireError,
    },
    /// A chip the board names has no place.
    #[error("{machine}'s CHIPS name {chip}, and its `place` gives none for it")]
    Unplaced {
        /// The board.
        machine: &'static str,
        /// The chip, as `CHIPS` names it.
        chip: &'static str,
    },
}

/// The bytes `fields` add up to.
fn declared(fields: &[Field]) -> usize {
    fields.iter().map(|field| usize::from(field.width)).sum()
}

/// The bytes `T` takes on the wire, read from zeros, which every integer field reads back. A value
/// reads no further than a frame can reach.
fn carried<T: Wire>() -> Result<usize, WireError> {
    let zeros = vec![0; LARGEST_FRAME];
    let mut rest = zeros.as_slice();
    T::decode(&mut rest)?;
    Ok(zeros.len() - rest.len())
}

impl<B: Edge + Board> Coupled for B
where
    B::Signals: Wire,
    B::Outputs: Wire,
    B::Conditions: Wire,
{
    fn fields(&self) -> &'static [Field] {
        B::FIELDS
    }

    fn output_fields(&self) -> &'static [Field] {
        B::OUTPUT_FIELDS
    }

    fn rest_wire(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        B::REST.encode(&mut bytes);
        bytes
    }

    fn sense_wire(&mut self, bytes: &[u8]) -> Result<(), WireError> {
        let signals = B::Signals::decode(&mut &*bytes)?;
        self.sense(&signals);
        Ok(())
    }

    fn conditions(&self) -> &'static [Field] {
        B::CONDITIONS
    }

    fn condition_wire(&mut self, bytes: &[u8]) -> Result<(), WireError> {
        let conditions = B::Conditions::decode(&mut &*bytes)?;
        self.condition(&conditions);
        Ok(())
    }

    fn draw(&mut self, seed: u64, index: u64) {
        Edge::draw(self, seed, index);
    }

    fn drive_wire(&mut self) -> Vec<u8> {
        let mut bytes = Vec::new();
        self.drive().encode(&mut bytes);
        bytes
    }

    fn chips(&self) -> &'static [&'static str] {
        B::CHIPS
    }

    fn place(&mut self, chip: usize) -> Option<&mut dyn Placed> {
        Edge::place(self, chip)
    }

    fn check(&mut self) -> Result<(), Mismatch> {
        let machine = self.name();
        let declarations = [
            (Declaration::Fields, B::FIELDS),
            (Declaration::OutputFields, B::OUTPUT_FIELDS),
            (Declaration::Conditions, B::CONDITIONS),
        ];
        for (declaration, fields) in declarations {
            if let Some(field) = fields
                .iter()
                .find(|field| checked_width(field.width).is_err())
            {
                return Err(Mismatch::Width {
                    machine,
                    declaration,
                    field: field.name.clone(),
                    width: field.width,
                });
            }
        }
        let unread = |declaration| {
            move |why| Mismatch::Unread {
                machine,
                declaration,
                why,
            }
        };
        let carried = [
            self.rest_wire().len(),
            carried::<B::Outputs>().map_err(unread(Declaration::OutputFields))?,
            carried::<B::Conditions>().map_err(unread(Declaration::Conditions))?,
        ];
        for ((declaration, fields), carried) in declarations.into_iter().zip(carried) {
            let declared = declared(fields);
            if declared != carried {
                return Err(Mismatch::Total {
                    machine,
                    declaration,
                    declared,
                    carried,
                });
            }
        }
        match (0..B::CHIPS.len()).find(|&chip| Edge::place(self, chip).is_none()) {
            Some(chip) => Err(Mismatch::Unplaced {
                machine,
                chip: B::CHIPS[chip],
            }),
            None => Ok(()),
        }
    }
}

/// One field of a board's outputs or signals as it crosses the link: its name, its unit, how many bytes
/// it takes and whether it's signed. Every field is a little-endian integer.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Field {
    /// The name, with a dot before an axis or a part, like `angular_rate.x`.
    pub name: Cow<'static, str>,
    /// The unit the integer counts in, like `mdeg/s`.
    pub unit: Cow<'static, str>,
    /// How many bytes it takes: 1, 2, 4 or 8.
    pub width: u8,
    /// Whether it's signed.
    pub signed: bool,
}

impl Field {
    /// A field as a board declares it.
    #[must_use]
    pub const fn new(name: &'static str, unit: &'static str, width: u8, signed: bool) -> Self {
        Self {
            name: Cow::Borrowed(name),
            unit: Cow::Borrowed(unit),
            width,
            signed,
        }
    }
}

/// A pulse a pin repeats: how long it is high, and how long until it is high again.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Pulse {
    /// The high time.
    pub width: VirtualNanos,
    /// The period.
    pub period: VirtualNanos,
}

/// What's wrong with one quantity a chip senses: whether it's stuck, how far above the board's value
/// it reads on each axis, and how noisy each axis is. It crosses the link as the flag, then each
/// axis's bias, then each axis's noise.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Condition<const N: usize> {
    /// Whether the chip keeps sensing what it was handed when this rose.
    pub stuck: bool,
    /// What the chip reads above the board's value on each axis, in the quantity's own unit.
    // ceiling: a bias is an i32 in the quantity's unit; upgrade when a quantity needs a bias past it
    #[serde(with = "crate::snapshot::array")]
    pub bias: [i32; N],
    /// The standard deviation of the noise on each axis, in the quantity's own unit. It's drawn once a
    /// step, so a chip that samples faster reads the same noise until the next. One smaller than the
    /// chip's count mostly vanishes when the chip converts.
    // ceiling: noise changes once a step; upgrade when a case needs a sensor's noise at its sample rate
    #[serde(with = "crate::snapshot::array")]
    pub noise: [u32; N],
}

impl<const N: usize> Default for Condition<N> {
    fn default() -> Self {
        Self {
            stuck: false,
            bias: [0; N],
            noise: [0; N],
        }
    }
}

crate::wire!(Condition<const N: usize> {
    stuck with flag,
    bias,
    noise
});

/// A condition's flag off the wire. Its field is a whole byte, so every value the field holds is one
/// the board takes, and any but zero sets it.
pub(crate) fn flag(bytes: &mut &[u8]) -> Result<bool, WireError> {
    Ok(u8::decode(bytes)? != 0)
}

/// The type a chip's setter takes a quantity in, which a bias saturates at the ends of.
// ceiling: no u64, which has no lossless i64; upgrade when a setter takes one
pub trait Reading: Copy + Default + Into<i64> + TryFrom<i64> {
    /// The least it holds.
    const MIN: Self;
    /// The most it holds.
    const MAX: Self;
}

macro_rules! reading {
    ($($int:ty),*) => {$(
        impl Reading for $int {
            const MIN: Self = <$int>::MIN;
            const MAX: Self = <$int>::MAX;
        }
    )*};
}

reading!(i8, i16, i32, i64, u8, u16, u32);

/// What one chip was last handed of one quantity, so a stuck one keeps sensing it, and the noise
/// drawn for it this step. A board keeps one for each quantity a condition can reach, draws its noise
/// with [`Sensed::draw`] each step, and hands the chip what [`Sensed::hand`] answers, in the type the
/// chip's setter takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(bound(
    serialize = "T: serde::Serialize",
    deserialize = "T: serde::Deserialize<'de>"
))]
pub struct Sensed<T, const N: usize> {
    #[serde(with = "crate::snapshot::array")]
    held: [T; N],
    #[serde(with = "crate::snapshot::array")]
    drawn: [i64; N],
}

impl<T: Reading, const N: usize> Default for Sensed<T, N> {
    fn default() -> Self {
        Self {
            held: [T::default(); N],
            drawn: [0; N],
        }
    }
}

impl<T: Reading, const N: usize> Sensed<T, N> {
    /// What the chip senses of the board's `value` under `condition`: what it was last handed while
    /// it's stuck, and otherwise `value` with the bias and this step's noise added, held at the ends
    /// of `T` rather than wrapping into the wrong sign.
    pub fn hand(&mut self, value: [T; N], condition: &Condition<N>) -> [T; N] {
        if !condition.stuck {
            self.held = std::array::from_fn(|axis| {
                let sum = value[axis]
                    .into()
                    .saturating_add(i64::from(condition.bias[axis]))
                    .saturating_add(self.drawn[axis]);
                T::try_from(sum).unwrap_or(if sum < 0 { T::MIN } else { T::MAX })
            });
        }
        self.held
    }

    /// Draws the noise `condition` puts on each axis for step `index` under `seed`, each axis's draws
    /// keyed by its condition's name in `names`, and holds it until the next. Answers whether any
    /// axis's noise moved, so a board senses again only when one did.
    pub fn draw(
        &mut self,
        condition: &Condition<N>,
        names: &[&str; N],
        seed: u64,
        index: u64,
    ) -> bool {
        let drawn = std::array::from_fn(|axis| match condition.noise[axis] {
            0 => 0,
            deviation => normal(seed, names[axis], index, deviation),
        });
        std::mem::replace(&mut self.drawn, drawn) != drawn
    }
}

/// SplitMix64's step between two draws, the golden ratio as a fraction of 2⁶⁴.
const GOLDEN_GAMMA: u64 = 0x9E37_79B9_7F4A_7C15;
/// The 64-bit FNV-1a hash's offset basis and prime.
const FNV_OFFSET_BASIS: u64 = 0xCBF2_9CE4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01B3;
/// Draws a normal takes, each two 32-bit uniforms.
const DRAWS_PER_NORMAL: u64 = 6;
const UNIFORM_BITS: u32 = 32;
const LOW_HALF: u64 = 0xFFFF_FFFF;
/// What twelve uniforms of 32 bits are centered on, `6 × 2³²`.
const IRWIN_HALL_CENTER: i128 = 6 << UNIFORM_BITS;

/// SplitMix64's finalizer: every bit of the answer depends on every bit of `z`.
const fn mixed(z: u64) -> u64 {
    let z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    let z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// A draw of 64 bits: a function of the run's `seed`, the `name` of what it's for and its `index`, and
/// nothing else.
///
/// It's SplitMix64. A name's draws start from SplitMix64's finalizer over `seed ^ fnv1a(name)`, where
/// `fnv1a` is the 64-bit FNV-1a hash of the name's bytes, and `index` is how far along the sequence
/// from there, the first draw at 0: the finalizer over the start plus `index + 1` times
/// `0x9E37_79B9_7F4A_7C15`, every sum and product wrapping. A result records the seed it ran with, so
/// this never changes.
#[must_use]
pub fn draw(seed: u64, name: &str, index: u64) -> u64 {
    let hash = name.bytes().fold(FNV_OFFSET_BASIS, |hash, byte| {
        (hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME)
    });
    let start = mixed(seed ^ hash);
    mixed(start.wrapping_add(index.wrapping_add(1).wrapping_mul(GOLDEN_GAMMA)))
}

/// A draw from a normal with a standard deviation of `deviation`, rounded to a whole one of its
/// unit, for step `index` of `name` under `seed`.
///
/// It's Irwin and Hall's: the twelve 32-bit halves of the name's draws `6 × index` to
/// `6 × index + 5`, high half first, summed, less `6 × 2³²`. That's a standard normal to within
/// their approximation, with a standard deviation of 2³², and it stops at six deviations either
/// side. It's scaled by `deviation` in 128 bits and rounded back to the nearest, half up, with no
/// floating point, so every host draws the same.
#[must_use]
pub fn normal(seed: u64, name: &str, index: u64, deviation: u32) -> i64 {
    let first = index.wrapping_mul(DRAWS_PER_NORMAL);
    let sum: i128 = (0..DRAWS_PER_NORMAL)
        .map(|offset| draw(seed, name, first.wrapping_add(offset)))
        .map(|drawn| i128::from(drawn >> UNIFORM_BITS) + i128::from(drawn & LOW_HALF))
        .sum();
    let scaled = (sum - IRWIN_HALL_CENTER) * i128::from(deviation);
    let rounded = (scaled + (1 << (UNIFORM_BITS - 1))) >> UNIFORM_BITS;
    i64::try_from(rounded).expect("six deviations of a u32 fit an i64")
}

#[cfg(test)]
mod tests {
    use std::marker::PhantomData;

    use super::*;

    /// A board with no MCU whose edge is wrong in the one way its parameters make it: its outputs
    /// are `O`, and it names `N` chips and has a place for none.
    #[derive(Debug)]
    struct Wrong<O, const N: usize>(PhantomData<O>);

    impl<O, const N: usize> crate::snapshot::Store for Wrong<O, N> {}

    impl<O: Wire + Default + Send + std::fmt::Debug, const N: usize> Board for Wrong<O, N> {
        fn name(&self) -> &'static str {
            "wrong"
        }

        fn targets(&mut self) -> Vec<crate::machine::Target<'_>> {
            Vec::new()
        }

        fn target_names(&self) -> Vec<&'static str> {
            Vec::new()
        }

        fn mcu(&mut self, _target: usize) -> Option<&mut dyn crate::mcu::Mcu> {
            None
        }
    }

    impl<O: Wire + Default + Send + std::fmt::Debug, const N: usize> Edge for Wrong<O, N> {
        type Signals = ();
        type Outputs = O;
        type Conditions = ();
        const FIELDS: &'static [Field] = &[];
        const OUTPUT_FIELDS: &'static [Field] = &[Field::new("lamp", "flag", 1, false)];
        const REST: () = ();
        const CHIPS: &'static [&'static str] = &["gauge"; N];

        fn sense(&mut self, _signals: &()) {}

        fn condition(&mut self, _conditions: &()) {}

        fn drive(&mut self) -> O {
            O::default()
        }
    }

    /// A one-byte output that only reads back a 1, as an enum with no zero would.
    #[derive(Debug, Default)]
    struct Lit;

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

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

    #[test]
    fn a_board_that_names_a_chip_it_has_no_place_for_is_refused() {
        assert_eq!(Wrong::<u8, 0>(PhantomData).check(), Ok(()), "no chips");
        assert_eq!(
            Wrong::<u8, 1>(PhantomData).check().unwrap_err().to_string(),
            "wrong's CHIPS name gauge, and its `place` gives none for it"
        );
    }

    #[test]
    fn outputs_that_do_not_read_zeros_back_are_refused_with_why() {
        assert_eq!(
            Wrong::<Lit, 0>(PhantomData)
                .check()
                .unwrap_err()
                .to_string(),
            "wrong's Outputs type doesn't read zero bytes back: 0 is no lit flag"
        );
    }

    #[test]
    fn a_reading_carries_its_bias_until_it_sticks_and_then_holds() {
        let mut sensed = Sensed::default();
        let biased = Condition {
            bias: [0, 5, -5],
            ..Condition::default()
        };
        assert_eq!(sensed.hand([1, 2, 3], &biased), [1, 7, -2]);
        let stuck = Condition {
            stuck: true,
            bias: [100; 3],
            ..Condition::default()
        };
        assert_eq!(
            sensed.hand([40, 50, 60], &stuck),
            [1, 7, -2],
            "stuck at what it had, and deaf to a new bias"
        );
        assert_eq!(
            sensed.hand([40, 50, 60], &Condition::default()),
            [40, 50, 60]
        );
    }

    #[test]
    fn a_bias_past_the_end_of_its_type_saturates_rather_than_wraps() {
        let condition = Condition {
            bias: [1, -1],
            ..Condition::default()
        };
        assert_eq!(
            Sensed::default().hand([i32::MAX, i32::MIN], &condition),
            [i32::MAX, i32::MIN]
        );
        assert_eq!(
            Sensed::default().hand([u32::MAX, 0], &condition),
            [u32::MAX, 0]
        );
        assert_eq!(
            Sensed::default().hand([3_000_000_000_u32], &Condition::default()),
            [3_000_000_000],
            "a value past an i32 crosses whole"
        );
        assert_eq!(
            Sensed::default().hand([u8::MAX, 0], &condition),
            [u8::MAX, 0]
        );
        assert_eq!(
            Sensed::default().hand([i16::MAX, i16::MIN], &condition),
            [i16::MAX, i16::MIN]
        );
    }

    #[test]
    fn a_draw_is_splitmix64_from_the_seed_and_the_names_hash_and_never_moves() {
        assert_eq!(
            mixed(GOLDEN_GAMMA),
            0xE220_A839_7B1D_CDAF,
            "SplitMix64's first draw from a state of nothing"
        );
        assert_eq!(draw(0, "", 0), 0xE587_D3DF_F9E9_2ED0);
        assert_eq!(draw(0, "a", 0), 0x538A_21EC_5E49_5B1A);
        assert_eq!(draw(1, "chip.rate.noise.x", 0), 0xC2A3_85B3_2629_CC2D);
        assert_eq!(draw(1, "chip.rate.noise.x", 1), 0x1149_FEDC_A1A2_5114);
        assert_eq!(draw(42, "line.noise_errors", 7), 0xD0B3_686D_9D99_13E4);
        assert_eq!(
            draw(u64::MAX, "chip.rate.noise.y", u64::MAX),
            0x2515_FCB1_4983_6BE6,
            "every sum and product wraps"
        );
    }

    #[test]
    fn a_normal_is_irwin_and_halls_in_integers_and_never_moves() {
        assert_eq!(normal(0, "chip.rate.noise.x", 0, 1000), -251);
        assert_eq!(normal(0, "chip.rate.noise.x", 1, 1000), -653);
        assert_eq!(
            normal(7, "chip.pressure.noise", 3, u32::MAX),
            -2_298_779_098
        );
        assert_eq!(normal(7, "chip.pressure.noise", 3, 0), 0);
    }

    #[test]
    #[cfg_attr(miri, ignore = "a million normals is beyond Miri")]
    fn a_million_normals_have_the_deviation_asked_for_about_no_mean_and_stop_at_six() {
        const DRAWS: i32 = 1_000_000;
        let deviation = 1_000_000;
        let (mut sum, mut squares, mut widest) = (0_i128, 0_i128, 0_i64);
        for index in 0..u64::try_from(DRAWS).unwrap() {
            let drawn = normal(5, "chip.rate.noise.z", index, deviation);
            sum += i128::from(drawn);
            squares += i128::from(drawn) * i128::from(drawn);
            widest = widest.max(drawn.abs());
        }
        let mean = sum / i128::from(DRAWS);
        let variance = squares / i128::from(DRAWS) - mean * mean;
        // The mean's standard error is the deviation over a thousand, and the deviation's is
        // under a thousandth of it.
        assert!(mean.abs() < 5_000, "a mean of {mean}");
        let spread = i128::from(deviation) * i128::from(deviation);
        assert!(
            (variance - spread).abs() < spread / 100,
            "a variance of {variance}"
        );
        assert!(widest <= 6 * i64::from(deviation), "{widest}");
    }

    #[test]
    fn noise_rides_on_the_bias_holds_for_the_step_and_a_stuck_chip_hears_none() {
        let names = ["chip.rate.noise.x", "chip.rate.noise.y"];
        let noisy = Condition {
            bias: [10, 0],
            noise: [1000, 0],
            ..Condition::default()
        };
        let mut sensed = Sensed::default();
        assert!(sensed.draw(&noisy, &names, 0, 0), "the first draw moves it");
        assert_eq!(sensed.hand([100, 100], &noisy), [100 + 10 - 251, 100]);
        assert_eq!(
            sensed.hand([200, 200], &noisy),
            [200 + 10 - 251, 200],
            "the same noise until the next step"
        );
        assert!(sensed.draw(&noisy, &names, 0, 1));
        assert_eq!(sensed.hand([100, 100], &noisy), [100 + 10 - 653, 100]);
        let stuck = Condition {
            stuck: true,
            ..noisy
        };
        assert!(sensed.draw(&stuck, &names, 0, 0));
        assert_eq!(
            sensed.hand([0, 0], &stuck),
            [100 + 10 - 653, 100],
            "stuck at what it had"
        );
        let quiet = Condition::default();
        assert!(sensed.draw(&quiet, &names, 0, 2));
        assert!(
            !sensed.draw(&quiet, &names, 0, 3),
            "no noise, and none to take away"
        );
        assert_eq!(sensed.hand([7, 8], &quiet), [7, 8]);
    }

    #[test]
    fn a_condition_crosses_as_the_flag_then_each_bias_then_each_noise() {
        let condition = Condition {
            stuck: true,
            bias: [-1, 2],
            noise: [3, 4],
        };
        let mut bytes = Vec::new();
        condition.encode(&mut bytes);
        assert_eq!(
            bytes,
            [
                vec![1],
                (-1_i32).to_le_bytes().to_vec(),
                2_i32.to_le_bytes().to_vec(),
                3_u32.to_le_bytes().to_vec(),
                4_u32.to_le_bytes().to_vec()
            ]
            .concat()
        );
        assert_eq!(Condition::<2>::decode(&mut &bytes[..]).unwrap(), condition);
    }

    #[test]
    fn any_flag_byte_but_zero_sets_it() {
        assert!(!flag(&mut &[0][..]).unwrap());
        assert!(flag(&mut &[1][..]).unwrap());
        assert!(
            flag(&mut &[2][..]).unwrap(),
            "the field holds it, so the board takes it"
        );
        assert!(flag(&mut &[][..]).is_err());
    }
}