nord-format 0.6.0

Read and write Nord keyboard files from Rust, byte for byte
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
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
//! Typed values shared across models.
//!
//! A component owns its encoding, its validation and its `Display`, and knows nothing
//! about which panel or offset holds it — so the same impl serves every `#[bits(...)]`
//! placement of that value.
//!
//! Only what more than one model uses belongs here. A component with a single consumer
//! lives beside that consumer, in the panel module that names it.

use std::fmt::{self, Debug, Display, Formatter};

use crate::bits::{bits_for, Packed};
use crate::error::ParseError;
use crate::fields::{ControlKind, Library, PackedOrder, Unit};
use crate::types::RangedI8;

/// Octave shift. The range and the storage bias are the model's business, so each
/// names its own alias.
pub type OctaveShift<const OFFSET: u8, const MIN: i8, const MAX: i8> = RangedI8<OFFSET, MIN, MAX>;

/// Half-step transposition. As with [`OctaveShift`], the model fixes the parameters.
pub type Transpose<const OFFSET: u8, const MIN: i8, const MAX: i8> = RangedI8<OFFSET, MIN, MAX>;

/// A continuous control on the panel's own `0..10` — level, compression, gain, tone.
///
/// `FULL` is the stored value the panel reads as 10, and so also fixes the slot's width.
/// Use the [`Level`] and [`Level6`] aliases rather than naming it — nearly every one of
/// these is the seven-bit `0..=127`, and the Stage 4 puts a few of the same knobs in six
/// bits.
///
/// ⚠️ **A `0..=127` slot is not automatically one of these.** An envelope stage reads in
/// milliseconds, a filter cutoff in hertz, an equalizer band in decibels either side of a
/// centre — see [`Time`], [`Frequency`], [`Rate`] and [`Bipolar`]. Typing one of those as a
/// `Level` makes the panel reading wrong rather than merely absent.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LevelOf<const FULL: u8> {
    inner: u8,
}

impl<const FULL: u8> LevelOf<FULL> {
    const VALID: () = assert!(FULL > 0, "a level needs a nonzero full-scale value");

    pub const MAX: u8 = {
        let () = Self::VALID;
        FULL
    };

    pub fn new(value: u8) -> Result<Self, ParseError> {
        value.try_into()
    }

    /// The stored value, `0..=FULL`.
    pub fn as_u8(&self) -> u8 {
        let () = Self::VALID;
        self.inner
    }

    /// The panel's 0..10 reading.
    ///
    /// Confirmed on hardware. Reverb wet reads `43` in the file and the panel shows
    /// 3.4, and `43 / 127 * 10 = 3.39`.
    pub fn as_panel(&self) -> f32 {
        let () = Self::VALID;
        f32::from(self.inner) / f32::from(FULL) * 10.0
    }
}

impl<const FULL: u8> Default for LevelOf<FULL> {
    fn default() -> Self {
        let () = Self::VALID;
        Self { inner: 0 }
    }
}

impl<const FULL: u8> TryFrom<u8> for LevelOf<FULL> {
    type Error = ParseError;

    fn try_from(value: u8) -> Result<Self, ParseError> {
        let () = Self::VALID;
        if value > FULL {
            return Err(ParseError::OutOfBounds {
                value: format!("{value}"),
                bound: format!("0..={FULL}"),
            });
        }
        Ok(LevelOf { inner: value })
    }
}

impl<const FULL: u8> Packed for LevelOf<FULL> {
    const MAX_BITS: u32 = {
        let () = Self::VALID;
        bits_for(FULL as u64)
    };
    const DECODE_BITS: u32 = u8::BITS;
    const CONTROL: ControlKind = ControlKind::Knob(Unit::Panel10);
    type Error = ParseError;

    fn from_bits(bits: u64) -> Result<Self, ParseError> {
        (bits as u8).try_into()
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

impl<const FULL: u8> Display for LevelOf<FULL> {
    /// Stored byte and panel reading: `96 (7.6)`.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({:.1})", self.inner, self.as_panel())
    }
}

impl<const FULL: u8> Debug for LevelOf<FULL> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl<const FULL: u8> PartialEq<u8> for LevelOf<FULL> {
    fn eq(&self, other: &u8) -> bool {
        self.inner == *other
    }
}

/// The seven-bit panel knob, which is nearly every one of them.
pub type Level = LevelOf<127>;

/// The same knob in a six-bit slot, as a few Stage 4 parameters store it.
pub type Level6 = LevelOf<63>;

/// Declare a 0..=127 knob whose panel reading is in `$unit` over a curve no manual
/// publishes.
///
/// [`Level`] is the same slot on the panel's own `0..10`, where the transform *is* known.
/// These are the ones where it is not: an envelope stage reads in milliseconds and a
/// filter cutoff in hertz, but no published table converts the stored byte, so the byte
/// is what they print. The unit is still worth carrying — it is what lets an interface
/// label the control and pick a taper without a table of field names beside it.
macro_rules! knob {
    ($(#[$meta:meta])* $name:ident, $unit:expr) => {
        knob!($(#[$meta])* $name, 127, 7, ControlKind::Knob($unit));
    };
    ($(#[$meta:meta])* $name:ident, $max:expr, $bits:expr, $control:expr) => {
        $(#[$meta])*
        #[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name {
            inner: u8,
        }

        impl $name {
            pub const MAX: u8 = $max;

            pub fn new(value: u8) -> Result<Self, ParseError> {
                value.try_into()
            }

            #[doc = concat!("The stored value, 0..=", stringify!($max), ".")]
            pub fn as_u8(&self) -> u8 {
                self.inner
            }
        }

        impl TryFrom<u8> for $name {
            type Error = ParseError;

            fn try_from(value: u8) -> Result<Self, ParseError> {
                if value > Self::MAX {
                    return Err(ParseError::OutOfBounds {
                        value: format!("{value}"),
                        bound: format!("0..={}", Self::MAX),
                    });
                }
                Ok($name { inner: value })
            }
        }

        impl Packed for $name {
            const MAX_BITS: u32 = $bits;
            const DECODE_BITS: u32 = u8::BITS;
            const CONTROL: ControlKind = $control;
            type Error = ParseError;

            fn from_bits(bits: u64) -> Result<Self, ParseError> {
                (bits as u8).try_into()
            }

            fn to_bits(&self) -> u64 {
                self.inner as u64
            }
        }

        /// The stored byte. There is no published transform to the unit, so printing one
        /// would invent precision the file does not carry.
        impl Debug for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.inner)
            }
        }

        impl Display for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.inner)
            }
        }

        impl PartialEq<u8> for $name {
            fn eq(&self, other: &u8) -> bool {
                self.inner == *other
            }
        }
    };
}

knob!(
    /// An envelope stage or a delay time. The panel reads it in milliseconds through
    /// seconds, over a curve no manual publishes.
    Time,
    Unit::Milliseconds
);

knob!(
    /// A filter cutoff or an equalizer sweep. The panel reads it in hertz — the Stage
    /// manuals give the endpoints of the mid sweep (200 Hz to 8 kHz) but not the taper.
    Frequency,
    Unit::Hertz
);

knob!(
    /// A modulation or LFO rate, read in hertz.
    ///
    /// ⚠️ Under a live master clock the same slot reads as a subdivision instead — see
    /// [`ClockDivision`]. The flag that switches it is a sibling field, so neither field
    /// answers alone.
    Rate,
    Unit::Hertz
);

knob!(
    /// A stereo position in a six-bit slot.
    ///
    /// ⚠️ The mapping is not established: over the Stage 4 factory programs the slot's
    /// mode is 0 rather than the mid-scale 32 a centre-encoded pan would show, so this
    /// makes no claim about where centre sits and prints the stored value. It carries
    /// only that the control is a pan. Inferred from specimens; not confirmed on
    /// hardware.
    Pan,
    63,
    6,
    ControlKind::Knob(Unit::Pan)
);

knob!(
    /// A pitch offset in semitones.
    ///
    /// The Stage 4's coarse oscillator pitch holds 0, 7, 12, 24 and 40 — unison, a
    /// fifth, an octave, two octaves — which is what makes the unit readable. Inferred
    /// from specimens; not confirmed on hardware. The Stage 3 manual gives the same
    /// control as "semitone steps, ranging from 0 to 48".
    Interval,
    63,
    6,
    ControlKind::Shift(Unit::Semitones)
);

/// A 0..=127 slot whose musical zero is its centre, reading `±LIMIT` of the unit
/// `UNIT` codes either side.
///
/// The Stage equalizer bands are the clearest case: the manuals give "the boost/cut range
/// is +/- 15 dB" for all three models, and rendering those on [`Level`]'s `0..10` reads a
/// cut as a small boost.
///
/// ⚠️ The unit is the declaration's, not the shape's: a `±10` modulation amount is not
/// decibels because an equalizer band is. Name it through [`EqBand`] or [`Bipolar`]
/// rather than writing the code out.
///
/// ⚠️ The centre is taken as 64 — the midpoint of the slot. Inferred from specimens; not
/// confirmed on hardware. The corpus does not distinguish 63 from 64, and no manual
/// states it. A reading is therefore accurate at the endpoints and approximate in
/// between.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BipolarOf<const LIMIT: i16, const UNIT: u8> {
    inner: u8,
}

impl<const LIMIT: i16, const UNIT: u8> BipolarOf<LIMIT, UNIT> {
    pub const MAX: u8 = 127;
    /// The stored value that reads as zero.
    pub const CENTER: u8 = 64;
    /// What the reading is in.
    pub const UNIT: Unit = Unit::expect_code(UNIT);

    pub fn new(value: u8) -> Result<Self, ParseError> {
        value.try_into()
    }

    /// The stored value, 0..=127.
    pub fn as_u8(&self) -> u8 {
        self.inner
    }

    /// The panel's signed reading, `-LIMIT..=+LIMIT`.
    pub fn reading(&self) -> f32 {
        let from_center = f32::from(self.inner) - f32::from(Self::CENTER);
        let span = if from_center < 0.0 {
            f32::from(Self::CENTER)
        } else {
            f32::from(Self::MAX - Self::CENTER)
        };
        from_center / span * f32::from(LIMIT)
    }
}

impl<const LIMIT: i16, const UNIT: u8> TryFrom<u8> for BipolarOf<LIMIT, UNIT> {
    type Error = ParseError;

    fn try_from(value: u8) -> Result<Self, ParseError> {
        if value > Self::MAX {
            return Err(ParseError::OutOfBounds {
                value: format!("{value}"),
                bound: format!("0..={}", Self::MAX),
            });
        }
        Ok(BipolarOf { inner: value })
    }
}

impl<const LIMIT: i16, const UNIT: u8> Packed for BipolarOf<LIMIT, UNIT> {
    const MAX_BITS: u32 = 7;
    const DECODE_BITS: u32 = u8::BITS;
    const CONTROL: ControlKind = ControlKind::Bipolar(Unit::expect_code(UNIT));
    type Error = ParseError;

    fn from_bits(bits: u64) -> Result<Self, ParseError> {
        (bits as u8).try_into()
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

/// The stored byte, so a retype from a plain integer leaves the field dumps alone.
impl<const LIMIT: i16, const UNIT: u8> Debug for BipolarOf<LIMIT, UNIT> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl<const LIMIT: i16, const UNIT: u8> Display for BipolarOf<LIMIT, UNIT> {
    /// Stored byte and signed reading: `96 (+7.5)`.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({:+.1})", self.inner, self.reading())
    }
}

impl<const LIMIT: i16, const UNIT: u8> PartialEq<u8> for BipolarOf<LIMIT, UNIT> {
    fn eq(&self, other: &u8) -> bool {
        self.inner == *other
    }
}

/// An equalizer band, `±15 dB` — the range all three Stage manuals give.
pub type EqBand = BipolarOf<15, { Unit::Decibels.code() }>;

/// A bipolar amount with no unit: a modulation depth the panel reads as a bare
/// `±LIMIT`, such as the Stage 2's filter modulation.
pub type Bipolar<const LIMIT: i16> = BipolarOf<LIMIT, { Unit::None.code() }>;

/// The value a performance control morphs its parent parameter *to*.
///
/// Every morphable parameter has three of these beside it — `_wheel`, `_aftertouch` and
/// `_ctrl_pedal` — and together they are half of every Stage body's field count. They are
/// not controls of their own: an interface shows them **on the parent's knob**, as a
/// second handle, which is what [`ControlKind::Morph`] tells it to do.
///
/// `BITS` is the slot's width, which tracks the parent's: eight beside a `0..=127` knob,
/// five beside a drawbar, three beside a switch.
///
/// ⚠️ **The encoding is not established.** Stage 4 specimens use the whole byte,
/// with 127 predominant. It may be a signed delta biased by 127 or a destination at
/// twice the parent's resolution. Inferred from specimens; not confirmed on hardware.
/// [`Self::is_neutral`] is the only interpretation exposed.
///
/// The experiment that settles it: assign one morph at a known depth, store, and diff the
/// slot against its parent's value.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MorphOf<const BITS: u32> {
    inner: u8,
}

impl<const BITS: u32> MorphOf<BITS> {
    const VALID: () = assert!(BITS > 0 && BITS <= 8, "a morph must fit in a byte");

    /// The slot's midpoint. Only the eight-bit value is confirmed by specimens.
    pub const NEUTRAL: u8 = {
        let () = Self::VALID;
        ((1u16 << BITS) / 2 - 1) as u8
    };

    pub fn as_u8(&self) -> u8 {
        let () = Self::VALID;
        self.inner
    }

    /// Whether the slot holds [`NEUTRAL`](Self::NEUTRAL).
    pub fn is_neutral(&self) -> bool {
        self.inner == Self::NEUTRAL
    }
}

impl<const BITS: u32> Default for MorphOf<BITS> {
    fn default() -> Self {
        let () = Self::VALID;
        Self { inner: 0 }
    }
}

impl<const BITS: u32> Packed for MorphOf<BITS> {
    const MAX_BITS: u32 = {
        let () = Self::VALID;
        BITS
    };
    const DECODE_BITS: u32 = u8::BITS;
    /// The parent is the declaration site's business, not the type's — every morph slot
    /// shares this type and each names a different parameter — so `#[bitbody]` fills it
    /// in from the field's name.
    const CONTROL: ControlKind = ControlKind::Morph { of: None };
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        let () = Self::VALID;
        Ok(MorphOf { inner: bits as u8 })
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

/// The stored value — the encoding is unconfirmed, so this prints what is there.
impl<const BITS: u32> Debug for MorphOf<BITS> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl<const BITS: u32> Display for MorphOf<BITS> {
    /// A neutral slot as `—`, anything else as the stored value.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if self.is_neutral() {
            f.write_str("")
        } else {
            write!(f, "{}", self.inner)
        }
    }
}

impl<const BITS: u32> PartialEq<u8> for MorphOf<BITS> {
    fn eq(&self, other: &u8) -> bool {
        self.inner == *other
    }
}

/// The morph slot beside a `0..=127` knob.
pub type MorphTarget = MorphOf<8>;

/// The morph slot beside a drawbar.
pub type DrawbarMorph = MorphOf<5>;

/// The morph slot beside a three-position switch — the Stage 3's rotary speed.
pub type SwitchMorph = MorphOf<3>;

/// A [`Selector`] over a list too long for a byte — a waveform, a sample slot.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WideSelector<const BITS: u32> {
    inner: u16,
}

impl<const BITS: u32> WideSelector<BITS> {
    const VALID: () = assert!(BITS > 0 && BITS <= 16, "a wide selector must fit in a u16");

    /// The stored index.
    pub fn raw(&self) -> u16 {
        let () = Self::VALID;
        self.inner
    }
}

impl<const BITS: u32> Default for WideSelector<BITS> {
    fn default() -> Self {
        let () = Self::VALID;
        Self { inner: 0 }
    }
}

impl<const BITS: u32> Packed for WideSelector<BITS> {
    const MAX_BITS: u32 = {
        let () = Self::VALID;
        BITS
    };
    const DECODE_BITS: u32 = u16::BITS;
    const CONTROL: ControlKind = ControlKind::Selector;
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        let () = Self::VALID;
        Ok(WideSelector { inner: bits as u16 })
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

impl<const BITS: u32> Debug for WideSelector<BITS> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl<const BITS: u32> Display for WideSelector<BITS> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl<const BITS: u32> PartialEq<u16> for WideSelector<BITS> {
    fn eq(&self, other: &u16) -> bool {
        self.inner == *other
    }
}

/// One drawbar, in the four-bit slot the Stage models give it.
///
/// Positions are physical, `0..=8`. The slot holds four bits, so decoding is total: a
/// nibble above 8 is preserved and reported by [`Self::position`] as `None` rather than
/// refused, on the same rule as [`crate::types::RangedU8`] — the bound is the slot's, not
/// the instrument's.
///
/// ⚠️ The two constructors therefore disagree on purpose. [`Self::new`] takes a
/// *position* and refuses 9 and above; `from_bits` — and so `set_field`, which goes
/// through the type's own parse — takes a *nibble* and accepts all sixteen, because a
/// file holding one has to round-trip. A caller offering a bar to a player wants the
/// former.
///
/// ⚠️ On the Stage 2's Farfisa the register is a *tab*, and the file stores a bit rather
/// than a nibble, so those fields are `bool` and not this type.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Drawbar {
    inner: u8,
}

impl Drawbar {
    /// The highest position a drawbar can be pulled to.
    pub const MAX: u8 = 8;

    /// A bar at `position`, `0..=8`. A higher one is refused — this takes a position,
    /// where decoding takes a nibble.
    pub fn new(position: u8) -> Result<Self, ParseError> {
        if position > Self::MAX {
            return Err(ParseError::OutOfBounds {
                value: format!("{position}"),
                bound: format!("0..={}", Self::MAX),
            });
        }
        Ok(Drawbar { inner: position })
    }

    /// The stored nibble, whatever it holds.
    pub fn raw(&self) -> u8 {
        self.inner
    }

    /// The position, or `None` for a nibble past the drawbar's travel.
    pub fn position(&self) -> Option<u8> {
        (self.inner <= Self::MAX).then_some(self.inner)
    }
}

impl Packed for Drawbar {
    const MAX_BITS: u32 = 4;
    const DECODE_BITS: u32 = u8::BITS;
    /// Which bar of the register this is comes from the declaration site — every bar
    /// shares this type — so `#[bitbody]` fills the rank in from a `…_N` field name.
    const CONTROL: ControlKind = ControlKind::Drawbar {
        bars: 1,
        rank: None,
        bits_per_bar: Self::MAX_BITS as u8,
        // One bar: there is no second value for the order to place.
        order: PackedOrder::HighFirst,
    };
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        Ok(Drawbar { inner: bits as u8 })
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

impl Debug for Drawbar {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl Display for Drawbar {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl PartialEq<u8> for Drawbar {
    fn eq(&self, other: &u8) -> bool {
        self.inner == *other
    }
}

/// A four-bit octave shift stored in two's complement, as the Stage 4 stores it.
///
/// Inferred from specimens; not confirmed on hardware. Over the Stage 4 factory programs
/// the slot holds only 0, 1, 2, 14 and 15 — a distribution centred on zero with the
/// negative side wrapping, where the Stage 2 and 3 instead centre on a stored 7 and 6.
/// Those two are [`OctaveShift`] aliases; this is the third encoding.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OctaveShiftNibble {
    /// The signed reading, -8..=7.
    inner: i8,
}

impl OctaveShiftNibble {
    /// The shift in octaves, `-8..=7`.
    pub fn octaves(&self) -> i8 {
        self.inner
    }
}

impl Packed for OctaveShiftNibble {
    const MAX_BITS: u32 = 4;
    const DECODE_BITS: u32 = 4;
    const CONTROL: ControlKind = ControlKind::Shift(Unit::Octaves);
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        let nibble = (bits & 0xf) as i8;
        Ok(OctaveShiftNibble {
            inner: if nibble >= 8 { nibble - 16 } else { nibble },
        })
    }

    fn to_bits(&self) -> u64 {
        (self.inner as u8 & 0xf) as u64
    }
}

impl Debug for OctaveShiftNibble {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl Display for OctaveShiftNibble {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:+}", self.inner)
    }
}

impl PartialEq<i8> for OctaveShiftNibble {
    fn eq(&self, other: &i8) -> bool {
        self.inner == *other
    }
}

/// A selector whose positions are known to be a fixed set, but whose table is not.
///
/// This preserves the control shape without inventing labels for positions that are not
/// yet identified. Use `sparse_enum!` once the value table is known.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Selector<const BITS: u32> {
    inner: u8,
}

impl<const BITS: u32> Selector<BITS> {
    const VALID: () = assert!(BITS > 0 && BITS <= 8, "a selector must fit in a byte");

    /// The stored index.
    pub fn raw(&self) -> u8 {
        let () = Self::VALID;
        self.inner
    }
}

impl<const BITS: u32> Default for Selector<BITS> {
    fn default() -> Self {
        let () = Self::VALID;
        Self { inner: 0 }
    }
}

impl<const BITS: u32> Packed for Selector<BITS> {
    const MAX_BITS: u32 = {
        let () = Self::VALID;
        BITS
    };
    const DECODE_BITS: u32 = u8::BITS;
    const CONTROL: ControlKind = ControlKind::Selector;
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        let () = Self::VALID;
        Ok(Selector { inner: bits as u8 })
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

/// The stored index — this type exists precisely because there is no name to print.
impl<const BITS: u32> Debug for Selector<BITS> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl<const BITS: u32> Display for Selector<BITS> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl<const BITS: u32> PartialEq<u8> for Selector<BITS> {
    fn eq(&self, other: &u8) -> bool {
        self.inner == *other
    }
}

/// A subdivision of the master clock, as a rate slot reads when its clock flag is set.
///
/// The manuals give the vocabulary — "subdivisions of the Master Clock tempo, ranging
/// from 1/2 to 1/32 notes. Apart from straight subdivisions there are also swing (S),
/// triplet (T) and dotted (D) options" — which is sixteen readings for a four-bit slot.
///
/// ⚠️ Which index carries which subdivision is not established, so this names none of
/// them. The experiment that settles it: store one specimen per detent of a clocked rate
/// knob.
pub type ClockDivision = Selector<4>;

/// The balance between a split's lower and upper parts, as a 0..=127 crossfade.
///
/// ⚠️ Each side is clamped at 50, so the pair does not sum to 100 — a stored 16 reads
/// as `50.0/12.6`.
#[derive(Copy, Default, Clone, PartialEq, Eq)]
pub struct PartMix {
    inner: u8,
}

impl PartMix {
    pub fn inner(&self) -> u8 {
        self.inner
    }

    pub fn lower(&self) -> f32 {
        let lower = 100_f32 - ((self.inner() as f32) / 127.0) * 100_f32;

        if lower > 50_f32 {
            50_f32
        } else {
            lower
        }
    }

    pub fn upper(&self) -> f32 {
        let upper = ((self.inner() as f32) / 127.0) * 100_f32;

        if upper > 50_f32 {
            50_f32
        } else {
            upper
        }
    }
}

impl Display for PartMix {
    /// The two sides as the panel reads them: `50.0/12.6`.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:.1}/{:.1}", self.lower(), self.upper())
    }
}

impl Debug for PartMix {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl Packed for PartMix {
    const MAX_BITS: u32 = 7;
    const DECODE_BITS: u32 = u8::BITS;
    const CONTROL: ControlKind = ControlKind::Bipolar(Unit::None);
    type Error = ParseError;

    fn from_bits(bits: u64) -> Result<Self, ParseError> {
        (bits as u8).try_into()
    }

    fn to_bits(&self) -> u64 {
        self.inner() as u64
    }
}

impl TryFrom<u8> for PartMix {
    type Error = ParseError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        if value > 127 {
            return Err(ParseError::OutOfBounds {
                value: format!("{value}"),
                bound: "0..=127".to_string(),
            });
        }

        Ok(PartMix { inner: value })
    }
}

/// Percussion decay speed. How it is stored is per-model; the Electro 5's B3 does not
/// store it in this order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PercSpeed {
    Off,
    Soft,
    Fast,
    Both,
}

/// A keyboard split point as the 73-key models store it: one of six keys, or
/// the whole keyboard as Upper / Lower.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
pub enum SplitPoint73 {
    #[default]
    C3,
    F3,
    C4,
    F4,
    C5,
    F5,
    Upper,
    Lower,
}

impl TryFrom<u8> for SplitPoint73 {
    type Error = ParseError;

    fn try_from(value: u8) -> Result<SplitPoint73, ParseError> {
        match value {
            0 => Ok(SplitPoint73::C3),
            1 => Ok(SplitPoint73::F3),
            2 => Ok(SplitPoint73::C4),
            3 => Ok(SplitPoint73::F4),
            4 => Ok(SplitPoint73::C5),
            5 => Ok(SplitPoint73::F5),
            6 => Ok(SplitPoint73::Upper),
            7 => Ok(SplitPoint73::Lower),
            _ => Err(ParseError::OutOfBounds {
                value: format!("{value}"),
                bound: "0..=7 (SplitPoint73)".to_string(),
            }),
        }
    }
}

impl Packed for SplitPoint73 {
    const MAX_BITS: u32 = 3;
    const DECODE_BITS: u32 = u8::BITS;
    const CONTROL: ControlKind = ControlKind::Selector;
    type Error = ParseError;

    fn from_bits(bits: u64) -> Result<Self, ParseError> {
        (bits as u8).try_into()
    }

    fn to_bits(&self) -> u64 {
        *self as u64
    }
}

/// A vibrato (`V`) or chorus (`C`) organ modulation at one of three depths.
///
/// Which subset an organ offers is the model's business, and so is the index each sits
/// at — see the per-model tables beside the organ panel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VibChorus {
    V1,
    C1,
    V2,
    C2,
    V3,
    C3,
}

/// A Stage program's transpose slot: stored `0..=12`, biased by 6, reading
/// `-6..=+6` semitones.
///
/// ⚠️ Not a [`RangedI8`]: the Stage 2 EX factory live
/// buffers hold 15 in this slot — an untouched buffer stores an out-of-table
/// pattern — so the unknown patterns are preserved rather than refused.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StageTranspose {
    raw: u8,
}

impl StageTranspose {
    /// The stored 4-bit pattern.
    pub fn raw(&self) -> u8 {
        self.raw
    }

    /// The semitone reading, or `None` for a pattern past the panel's `+6`.
    pub fn semitones(&self) -> Option<i8> {
        (self.raw <= 12).then(|| self.raw as i8 - 6)
    }
}

impl Packed for StageTranspose {
    const MAX_BITS: u32 = 4;
    const DECODE_BITS: u32 = u8::BITS;
    const CONTROL: ControlKind = ControlKind::Shift(Unit::Semitones);
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        Ok(StageTranspose { raw: bits as u8 })
    }

    fn to_bits(&self) -> u64 {
        self.raw as u64
    }
}

impl Debug for StageTranspose {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self.semitones() {
            Some(s) => write!(f, "{s}"),
            None => write!(f, "unknown ({})", self.raw),
        }
    }
}

/// The master clock rate the Stage 2 and 3 store in a program: `stored + 30` BPM.
///
/// Reported by public documentation; not confirmed on hardware.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MasterTempo {
    inner: u8,
}

impl MasterTempo {
    /// The stored byte.
    pub fn as_u8(&self) -> u8 {
        self.inner
    }

    /// The panel's BPM reading.
    pub fn bpm(&self) -> u16 {
        self.inner as u16 + 30
    }
}

impl Packed for MasterTempo {
    const MAX_BITS: u32 = 8;
    const DECODE_BITS: u32 = u8::BITS;
    const CONTROL: ControlKind = ControlKind::Knob(Unit::Bpm);
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        Ok(MasterTempo { inner: bits as u8 })
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

impl Debug for MasterTempo {
    /// The BPM reading — the stored byte is recoverable as `bpm - 30`.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.bpm())
    }
}

/// Declare a sparse enumeration: known values, plus `Unknown` for the rest of the slot.
///
/// The slot is wider than the set of values we have names for, so anything unrecognized
/// decodes to `Unknown`, round-trips byte-exactly, and displays as `unknown (9)` — never
/// coerced to the nearest label. Match on it, or call `is_unknown()`, to find them.
macro_rules! sparse_enum {
    (
        $(#[$meta:meta])*
        $name:ident, $bits:expr, { $($value:expr => $variant:ident, $label:expr;)+ }
    ) => {
        $(#[$meta])*
        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub enum $name {
            $($variant,)+
            /// A stored value with no known meaning.
            Unknown(u8),
        }

        /// Named variants as their names; an unknown as `unknown (raw)`. ⚠️ The corpus
        /// tripwires match the lowercase spelling — a derived `Unknown(raw)` slips past
        /// them.
        impl ::core::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                match self {
                    $($name::$variant => f.write_str(stringify!($variant)),)+
                    $name::Unknown(raw) => write!(f, "unknown ({raw})"),
                }
            }
        }

        impl $name {
            /// The label, or `None` for a value with no known meaning.
            pub fn label(&self) -> Option<&'static str> {
                match self {
                    $($name::$variant => Some($label),)+
                    $name::Unknown(_) => None,
                }
            }

            /// Whether the stored value has no known meaning.
            pub fn is_unknown(&self) -> bool {
                matches!(self, $name::Unknown(_))
            }

            /// The stored value, named or not.
            pub fn raw(&self) -> u8 {
                <Self as $crate::bits::Packed>::to_bits(self) as u8
            }
        }

        impl Default for $name {
            fn default() -> Self {
                match <Self as $crate::bits::Packed>::from_bits(0) {
                    Ok(v) => v,
                    Err(never) => match never {},
                }
            }
        }

        impl $crate::bits::Packed for $name {
            const MAX_BITS: u32 = $bits;
            const DECODE_BITS: u32 = u8::BITS;
            const CONTROL: $crate::fields::ControlKind = $crate::fields::ControlKind::Selector;
            type Error = ::core::convert::Infallible;

            fn from_bits(bits: u64) -> Result<Self, Self::Error> {
                Ok(match bits as u8 {
                    $($value => $name::$variant,)+
                    other => $name::Unknown(other),
                })
            }

            fn to_bits(&self) -> u64 {
                match self {
                    $($name::$variant => $value as u64,)+
                    $name::Unknown(raw) => *raw as u64,
                }
            }
        }

        impl ::core::fmt::Display for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                match self.label() {
                    Some(label) => f.write_str(label),
                    None => write!(f, "unknown ({})", self.raw()),
                }
            }
        }
    };
}

pub(crate) use sparse_enum;

/// Declare a one-bit field whose two states have names.
///
/// A `bool` is the right shape for on/off, and the wrong one for a switch between two
/// *named* positions: `false` is not a reading anyone can act on when the panel says
/// Normal and Analog. This keeps the single bit and gives both states their word.
macro_rules! switch {
    (
        $(#[$meta:meta])*
        $name:ident, $clear:ident = $clear_label:expr, $set:ident = $set_label:expr
    ) => {
        $(#[$meta])*
        #[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub enum $name {
            /// The state stored as a clear bit.
            #[default]
            $clear,
            /// The state stored as a set bit.
            $set,
        }

        impl $name {
            /// The panel's word for this state.
            pub fn label(&self) -> &'static str {
                match self {
                    $name::$clear => $clear_label,
                    $name::$set => $set_label,
                }
            }

            /// Whether the bit is set.
            pub fn is_set(&self) -> bool {
                matches!(self, $name::$set)
            }
        }

        impl $crate::bits::Packed for $name {
            const MAX_BITS: u32 = 1;
            const DECODE_BITS: u32 = 1;
            const CONTROL: $crate::fields::ControlKind = $crate::fields::ControlKind::Toggle;
            type Error = ::core::convert::Infallible;

            fn from_bits(bits: u64) -> Result<Self, Self::Error> {
                Ok(if bits != 0 { $name::$set } else { $name::$clear })
            }

            fn to_bits(&self) -> u64 {
                self.is_set() as u64
            }
        }

        /// The variant name, which is what `--set` takes. ⚠️ Not [`Display`], which is
        /// the panel's own word for the state and may differ.
        impl ::core::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                match self {
                    $name::$clear => f.write_str(stringify!($clear)),
                    $name::$set => f.write_str(stringify!($set)),
                }
            }
        }

        impl ::core::fmt::Display for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                f.write_str(self.label())
            }
        }
    };
}

/// Sixteen pattern steps, two bits each — the Stage 4 arpeggiator's accent, gate and pan
/// rows.
///
/// The panel edits these as a grid: the manual's Pattern Edit page moves a cursor with a
/// Position dial and sets the step under it, and the Pattern Pan page moves a step
/// "between Left, Center and Right". Three values per step is exactly two bits, and a
/// pattern runs to sixteen steps, which is exactly the 32-bit slot.
///
/// ⚠️ **Step order is inferred, not established.** Read low-bits-first the corpus values
/// fall out as music — `0x01010101` is an accent every fourth step, `0x55aa5500` is four
/// left then four right then four left — but correlating the highest non-zero step
/// against the sibling `arp_pattern_length` fails in both directions, so either the word
/// keeps all sixteen steps regardless of the active length or that field is not a step
/// count. Inferred from specimens; not confirmed on hardware.
///
/// The slot is wider than [`crate::fields::ENUMERABLE_BITS`], so `--set` spells it by its
/// stored bits — `0x55aa5500` is the readable form for a pattern anyway.
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
pub struct ArpPattern {
    inner: u32,
}

impl ArpPattern {
    /// Steps a pattern can hold.
    pub const STEPS: usize = 16;

    /// The stored word.
    pub fn raw(&self) -> u32 {
        self.inner
    }

    /// The sixteen steps, `0..=3` each, lowest bits first.
    pub fn steps(&self) -> [u8; Self::STEPS] {
        std::array::from_fn(|n| ((self.inner >> (2 * n)) & 0b11) as u8)
    }

    /// Whether every step is zero — an unset row.
    pub fn is_empty(&self) -> bool {
        self.inner == 0
    }
}

impl Packed for ArpPattern {
    const MAX_BITS: u32 = 32;
    const DECODE_BITS: u32 = u32::BITS;
    const CONTROL: ControlKind = ControlKind::Pattern {
        steps: Self::STEPS as u8,
        // The slot divided by its steps, so the two cannot drift apart.
        bits_per_step: (Self::MAX_BITS / Self::STEPS as u32) as u8,
        order: PackedOrder::LowFirst,
    };
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        Ok(ArpPattern { inner: bits as u32 })
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

impl Debug for ArpPattern {
    /// The stored word in hex, which is what `--set` takes back.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:#010x}", self.inner)
    }
}

impl Display for ArpPattern {
    /// The steps as a row: `1010 1010 ....` — a dot for a zero step.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        for (n, step) in self.steps().into_iter().enumerate() {
            if n > 0 && n % 4 == 0 {
                f.write_str(" ")?;
            }
            match step {
                0 => f.write_str(".")?,
                s => write!(f, "{s}")?,
            }
        }
        Ok(())
    }
}

impl PartialEq<u32> for ArpPattern {
    fn eq(&self, other: &u32) -> bool {
        self.inner == *other
    }
}

/// An opaque id into one of the instrument's libraries — a piano model, a sample.
///
/// The id is only meaningful against the library that holds it, so the type names which:
/// `LIBRARY` is a [`Library`] code, and the aliases below are the spellings to use.
/// The file carries the reference and nothing else, which is what
/// [`ControlKind::Reference`] tells a caller.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LibraryRefOf<const LIBRARY: u8> {
    inner: u32,
}

impl<const LIBRARY: u8> LibraryRefOf<LIBRARY> {
    /// Which catalogue resolves this id.
    pub const LIBRARY: Library = Library::expect_code(LIBRARY);

    /// The stored id. Zero is "nothing referenced" on every model in the corpus.
    pub fn id(&self) -> u32 {
        self.inner
    }

    pub fn is_none(&self) -> bool {
        self.inner == 0
    }
}

impl<const LIBRARY: u8> Packed for LibraryRefOf<LIBRARY> {
    const MAX_BITS: u32 = 32;
    const DECODE_BITS: u32 = u32::BITS;
    const CONTROL: ControlKind = ControlKind::Reference(Library::expect_code(LIBRARY));
    type Error = ::core::convert::Infallible;

    fn from_bits(bits: u64) -> Result<Self, Self::Error> {
        Ok(LibraryRefOf { inner: bits as u32 })
    }

    fn to_bits(&self) -> u64 {
        self.inner as u64
    }
}

impl<const LIBRARY: u8> Debug for LibraryRefOf<LIBRARY> {
    /// Hex, matching how `nord program deps` reports the same id.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:#010x}", self.inner)
    }
}

impl<const LIBRARY: u8> Display for LibraryRefOf<LIBRARY> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if self.is_none() {
            f.write_str("none")
        } else {
            write!(f, "{:#010x}", self.inner)
        }
    }
}

impl<const LIBRARY: u8> PartialEq<u32> for LibraryRefOf<LIBRARY> {
    fn eq(&self, other: &u32) -> bool {
        self.inner == *other
    }
}

/// An id into the piano library (`.npno`).
pub type PianoRef = LibraryRefOf<{ Library::Piano.code() }>;

/// An id into the sample library (`.nsmp`).
pub type SampleRef = LibraryRefOf<{ Library::Sample.code() }>;

switch!(
    /// Which of the two delay lines is running.
    ///
    /// Both Stage manuals give the pair by name: "There are two different delay modes, the
    /// normal ('non-analog') mode, and the Analog Mode … In Analog Mode the pitch of any
    /// sounding repeats is altered if the tempo is changed."
    DelayCharacter, Normal = "normal", Analog = "analog"
);

switch!(
    /// How quickly the compressor recovers. Manual: "The FAST mode … makes the Compressor
    /// recover quicker after being triggered."
    CompressorResponse, Normal = "normal", Fast = "fast"
);

switch!(
    /// The rotary speaker's rotor speed. Manual: "Switch between fast and slow rotor
    /// speeds."
    ///
    /// ⚠️ Stopped is not one of these — it is a separate flag, so neither field answers
    /// on its own.
    RotorSpeed, Slow = "slow", Fast = "fast"
);

sparse_enum!(
    /// Which of the four keyboard zones a section occupies, as the Stage 3 and 4 store it.
    ///
    /// The Stage 3 byte-map docs give the table as an occupancy picture — `o---` is the
    /// leftmost zone alone, `oooo` the whole keyboard. The Stage 3's piano and synth
    /// zone slots hold only values inside this table, with `oooo` dominating, so all
    /// three sections share it. Inferred from specimens; not confirmed on hardware.
    ///
    /// Unexplained: Stage 4 specimens reach stored value 10. It decodes as `Unknown(10)`
    /// and survives verbatim.
    KbZone4, 4, {
        0 => V0, "o---";
        1 => V1, "-o--";
        2 => V2, "--o-";
        3 => V3, "---o";
        4 => V4, "oo--";
        5 => V5, "-oo-";
        6 => V6, "--oo";
        7 => V7, "ooo-";
        8 => V8, "-ooo";
        9 => V9, "oooo";
    }
);

sparse_enum!(
    /// Which of the three keyboard zones a section occupies, as the Stage 2 stores it.
    ///
    /// The Stage 2 splits into two or three zones rather than four, and its panel spells
    /// them in words. From the `ns2-*-kb-zone` tables in the Stage byte-map docs.
    KbZone3, 3, {
        0 => Lo, "LO";
        1 => LoUp, "LO UP";
        2 => Up, "UP";
        3 => UpHi, "UP HI";
        4 => Hi, "HI";
        5 => LoUpHi, "LO UP HI";
    }
);

sparse_enum!(
    /// A Stage split boundary, one of the ten notes the panel offers.
    ///
    /// The Stage 2 and 3 store the same ten-note table. Reported by public
    /// documentation; not confirmed on hardware.
    SplitNote, 4, {
        0 => F2, "F2";
        1 => C3, "C3";
        2 => F3, "F3";
        3 => C4, "C4";
        4 => F4, "F4";
        5 => C5, "C5";
        6 => F5, "F5";
        7 => C6, "C6";
        8 => F6, "F6";
        9 => C7, "C7";
    }
);

sparse_enum!(
    /// A Stage 3 split crossfade width, in semitones.
    ///
    /// Reported by public documentation; not confirmed on hardware.
    SplitWidth, 2, {
        0 => One, "1";
        1 => Six, "6";
        2 => Twelve, "12";
    }
);

sparse_enum!(
    /// The program category byte the Stage 2 and 3 keep in the header's `aux` word.
    ///
    /// Reported by public documentation; not confirmed on hardware.
    /// The gaps are real: no name is known for the values between these.
    ProgramCategory, 8, {
        0x00 => Acoustic, "Acoustic";
        0x01 => Bass, "Bass";
        0x02 => Wind, "Wind";
        0x04 => Fantasy, "Fantasy";
        0x05 => Fx, "FX";
        0x06 => Lead, "Lead";
        0x07 => Organ, "Organ";
        0x08 => Pad, "Pad";
        0x0a => Pluck, "Pluck";
        0x0b => String, "String";
        0x0c => Synth, "Synth";
        0x0d => Vocal, "Vocal";
        0x0e => User, "User";
        0x11 => None_, "None";
        0x15 => Grand, "Grand";
        0x16 => Upright, "Upright";
        0x17 => EPiano1, "EPiano1";
        0x18 => EPiano2, "EPiano2";
        0x1b => Clavinet, "Clavinet";
        0x1c => Harpsi, "Harpsi";
        0x1e => Arpeggio, "Arpeggio";
        0xff => Undefined, "Undefined";
    }
);

impl ProgramCategory {
    /// The category a Stage 2 or 3 header names, or `None` where the `aux` word carries
    /// no category id at all or one too wide for this byte-sized table.
    ///
    /// The whole id is examined: a value above `0xff` names no category here rather than
    /// being truncated into one.
    pub fn of(header: &crate::cbin::Header) -> Option<ProgramCategory> {
        let id = u8::try_from(header.category()?).ok()?;
        match Self::from_bits(id as u64) {
            Ok(category) => Some(category),
            Err(never) => match never {},
        }
    }
}

sparse_enum!(
    /// From the `ns2-effect-1-type` table in the Stage byte-map docs.
    Effect1Type, 3, {
        0 => APan, "A-Pan";
        1 => Trem, "Trem";
        2 => Rm, "RM";
        3 => WaWa, "WA-WA";
        4 => AWa1, "A-WA1";
        5 => AWa2, "A-WA2";
    }
);

sparse_enum!(
    /// From the `ns2-effect-2-type` table in the Stage byte-map docs.
    Effect2Type, 3, {
        0 => Phas1, "PHAS1";
        1 => Phas2, "PHAS2";
        2 => Flang, "FLANG";
        3 => Vibe, "VIBE";
        4 => Chor1, "CHOR1";
        5 => Chor2, "CHOR2";
    }
);

sparse_enum!(
    /// From the `ns2-reverb-type` table in the Stage byte-map docs.
    ReverbType, 3, {
        0 => Room1, "Room 1";
        1 => Room2, "Room 2";
        2 => Stage1, "Stage 1";
        3 => Stage2, "Stage 2";
        4 => Hall1, "Hall 1";
        5 => Hall2, "Hall 2";
    }
);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fields::{ControlKind, Library, PackedOrder, Unit};

    /// The whole point of the vocabulary: a field gets its control kind by choosing a
    /// type, so an interface never needs a table of field names of its own.
    #[test]
    fn a_type_says_what_kind_of_control_it_is() {
        assert_eq!(<Level as Packed>::CONTROL, ControlKind::Knob(Unit::Panel10));
        assert_eq!(
            <Time as Packed>::CONTROL,
            ControlKind::Knob(Unit::Milliseconds)
        );
        assert_eq!(
            <EqBand as Packed>::CONTROL,
            ControlKind::Bipolar(Unit::Decibels)
        );
        // The shape a caller needs to draw the control is on the kind: how many bars,
        // how many steps, which catalogue. What the *type* cannot know — which bar of
        // the register, which parameter a morph slot belongs to — is left open here and
        // filled in by `#[bitbody]` from the field's name.
        assert_eq!(
            <MorphTarget as Packed>::CONTROL,
            ControlKind::Morph { of: None }
        );
        assert_eq!(
            <Drawbar as Packed>::CONTROL,
            ControlKind::Drawbar {
                bars: 1,
                rank: None,
                bits_per_bar: 4,
                order: PackedOrder::HighFirst,
            }
        );
        // ⚠️ The two multi-value kinds pack from opposite ends, which is why each says
        // so: a pattern's first step is in the lowest bits and an Electro 5 register's
        // first bar is in the highest.
        assert_eq!(
            <ArpPattern as Packed>::CONTROL,
            ControlKind::Pattern {
                steps: 16,
                bits_per_step: 2,
                order: PackedOrder::LowFirst,
            }
        );
        assert_eq!(
            <PianoRef as Packed>::CONTROL,
            ControlKind::Reference(Library::Piano)
        );
        assert_eq!(
            <SampleRef as Packed>::CONTROL,
            ControlKind::Reference(Library::Sample)
        );
        assert_eq!(<KbZone4 as Packed>::CONTROL, ControlKind::Selector);
        assert_eq!(<bool as Packed>::CONTROL, ControlKind::Toggle);
        assert_eq!(
            <OctaveShiftNibble as Packed>::CONTROL,
            ControlKind::Shift(Unit::Octaves)
        );
        // The default, and the standing invitation to give a field a better type.
        assert_eq!(<u8 as Packed>::CONTROL, ControlKind::Number);
    }

    /// A unit is a label, not a promise. Printing a millisecond reading off a curve no
    /// manual publishes would be inventing precision the file does not carry.
    #[test]
    fn a_unit_says_whether_it_can_be_computed() {
        assert!(Unit::Panel10.describes_a_known_transform());
        assert!(Unit::Decibels.describes_a_known_transform());
        assert!(!Unit::Milliseconds.describes_a_known_transform());
        assert!(!Unit::Hertz.describes_a_known_transform());
        // So the type prints the stored byte rather than a converted one.
        assert_eq!(Time::new(96).unwrap().to_string(), "96");
        assert_eq!(Level::new(96).unwrap().to_string(), "96 (7.6)");
    }

    /// Stage 4 octave shift is two's complement; Stage 2 and 3 use biased values.
    #[test]
    fn the_stage4_octave_shift_wraps_where_the_others_bias() {
        let read = |bits| OctaveShiftNibble::from_bits(bits).unwrap().octaves();
        assert_eq!(read(0), 0);
        assert_eq!(read(1), 1);
        assert_eq!(read(2), 2);
        assert_eq!(read(15), -1);
        assert_eq!(read(14), -2);
        // Every pattern round-trips, so an unreached value rides through a re-encode.
        for bits in 0..16u64 {
            assert_eq!(OctaveShiftNibble::from_bits(bits).unwrap().to_bits(), bits);
        }
    }

    /// Every pattern survives; the specimen mode at 127 is displayed as neutral.
    #[test]
    fn a_morph_slot_names_its_neutral_and_keeps_the_rest() {
        assert_eq!(MorphTarget::NEUTRAL, 127);
        let neutral = MorphTarget::from_bits(127).unwrap();
        assert!(neutral.is_neutral());
        assert_eq!(neutral.to_string(), "");
        assert_eq!(format!("{neutral:?}"), "127");

        let moved = MorphTarget::from_bits(254).unwrap();
        assert!(!moved.is_neutral());
        assert_eq!(moved.to_string(), "254");
        // The whole byte is in use, so nothing may be refused or clamped.
        for bits in 0..256u64 {
            assert_eq!(MorphTarget::from_bits(bits).unwrap().to_bits(), bits);
        }
    }

    /// Sixteen two-bit steps decode lowest bits first.
    #[test]
    fn an_arp_pattern_reads_as_steps() {
        // Accent on every fourth step.
        let accent = ArpPattern::from_bits(0x0101_0101).unwrap();
        assert_eq!(
            accent.steps(),
            [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]
        );
        assert_eq!(accent.to_string(), "1... 1... 1... 1...");

        // Four left, four right, four left — a pan row.
        let pan = ArpPattern::from_bits(0x55aa_5500).unwrap();
        assert_eq!(&pan.steps()[4..12], &[1, 1, 1, 1, 2, 2, 2, 2]);

        assert!(ArpPattern::default().is_empty());
        // The slot is wider than the enumerable ceiling, so `--set` spells it in hex.
        assert_eq!(format!("{pan:?}"), "0x55aa5500");
    }

    /// An equalizer band reads +/- 15 dB either side of the slot's centre.
    #[test]
    fn a_bipolar_band_reads_signed() {
        assert_eq!(EqBand::new(64).unwrap().reading(), 0.0);
        assert_eq!(EqBand::new(0).unwrap().to_string(), "0 (-15.0)");
        assert_eq!(EqBand::new(127).unwrap().to_string(), "127 (+15.0)");
        // `Debug` is the stored byte, so retyping a plain integer leaves field dumps alone.
        assert_eq!(format!("{:?}", EqBand::new(96).unwrap()), "96");
    }

    /// The unit comes from the declaration, so a bipolar slot that is not a decibel
    /// reading does not claim to be one.
    #[test]
    fn a_bipolar_slot_carries_the_unit_it_was_declared_with() {
        assert_eq!(
            <EqBand as Packed>::CONTROL,
            ControlKind::Bipolar(Unit::Decibels)
        );
        assert_eq!(
            <Bipolar<10> as Packed>::CONTROL,
            ControlKind::Bipolar(Unit::None)
        );
        // ±10 of nothing is still ±10.
        assert_eq!(Bipolar::<10>::new(127).unwrap().reading(), 10.0);
    }

    /// The code is only a way to carry a unit through a const generic, so it has to come
    /// back as the unit it went in as.
    #[test]
    fn a_unit_survives_the_code_that_carries_it() {
        for unit in [
            Unit::Panel10,
            Unit::Decibels,
            Unit::Milliseconds,
            Unit::Hertz,
            Unit::Bpm,
            Unit::ClockDivision,
            Unit::Semitones,
            Unit::Octaves,
            Unit::Pan,
            Unit::None,
        ] {
            assert_eq!(Unit::expect_code(unit.code()), unit, "{unit:?}");
        }
    }

    /// A switch keeps its single bit and gives both states a word. `Debug` is the
    /// variant, which is what `--set` takes; `Display` is the panel's own wording.
    #[test]
    fn a_switch_names_both_of_its_states() {
        let normal = DelayCharacter::from_bits(0).unwrap();
        let analog = DelayCharacter::from_bits(1).unwrap();
        assert_eq!(format!("{normal:?}"), "Normal");
        assert_eq!(analog.to_string(), "analog");
        assert_eq!(analog.to_bits(), 1);
        assert!(analog.is_set());
        assert_eq!(<DelayCharacter as Packed>::MAX_BITS, 1);
    }

    /// A drawbar is total over its nibble: a position past the bar's travel is preserved
    /// and reported as unnamed rather than refused.
    #[test]
    fn a_drawbar_keeps_a_nibble_past_its_travel() {
        assert_eq!(Drawbar::from_bits(8).unwrap().position(), Some(8));
        assert_eq!(Drawbar::from_bits(9).unwrap().position(), None);
        assert_eq!(Drawbar::from_bits(9).unwrap().raw(), 9);
        for bits in 0..16u64 {
            assert_eq!(Drawbar::from_bits(bits).unwrap().to_bits(), bits);
        }
    }

    #[test]
    fn a_level_carries_the_panel_transform() {
        assert_eq!(Level::new(0).unwrap().to_string(), "0 (0.0)");
        assert_eq!(Level::new(127).unwrap().to_string(), "127 (10.0)");
        assert_eq!(Level::new(96).unwrap().to_string(), "96 (7.6)");
        assert!(Level::new(128).is_err(), "128 does not fit seven bits");
    }
}