led-strip 0.4.1

no_std driver for WS2812/SK6812/WS2811/WS2816 single-wire addressable LED strips
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
use core::marker::PhantomData;

use embedded_hal::spi::SpiBus;
use heapless::Vec;

use crate::{
    LedPixel, LedStripError, LedStripResult, SingleWireProtocol, TransportBackend, WireCodec,
};

/// SPI clock frequency, bit patterns, and symbol width for encoding a
/// single-wire LED protocol over an SPI bus.
///
/// Each protocol bit is encoded as `bits_per_symbol` SPI bits (typically 3 or 4).
/// For example, WS2812B uses 3-bit symbols: `0b100` for logical 0, `0b110` for logical 1.
///
/// Use the predefined constructors ([`ws2812_3bit`](Self::ws2812_3bit),
/// [`sk6812_4bit`](Self::sk6812_4bit), [`ws2811_8bit`](Self::ws2811_8bit),
/// [`ws2816_5bit`](Self::ws2816_5bit)) or build a custom plan with
/// [`new`](Self::new).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpiEncodingPlan {
    /// SPI clock frequency in Hz.
    spi_hz: u32,
    /// SPI bit pattern for a logical 0 (MSB-first within the symbol window).
    zero_pattern: u8,
    /// SPI bit pattern for a logical 1 (MSB-first within the symbol window).
    one_pattern: u8,
    /// Number of SPI bits used to encode one protocol bit (e.g. 3 for 0b100/0b110 WS281x).
    bits_per_symbol: u8,
    /// Additional reset extension beyond `Proto::RESET_NS`.
    /// Actual reset = Proto::RESET_NS + extra_reset_ns. Use when the peripheral
    /// (inverter, level shifter) needs extra settling time.
    extra_reset_ns: u32,
}

impl SpiEncodingPlan {
    /// Creates a new encoding plan. Use [`SpiCodec::for_protocol`] to validate
    /// that the plan fits a target protocol's timing tolerances.
    #[must_use]
    pub const fn new(spi_hz: u32, zero_pattern: u8, one_pattern: u8, bits_per_symbol: u8) -> Self {
        Self {
            spi_hz,
            zero_pattern,
            one_pattern,
            bits_per_symbol,
            extra_reset_ns: 0,
        }
    }

    /// 3-bit SPI plan at 2.4 MHz for WS2812 / WS2812B.
    ///
    /// Derived timing (spi_bit ~ 416.667 ns, tolerance +/-150 ns per WS2812B datasheet V1):
    /// - T0H ~ 416.667 ns (expected 400 ns, delta ~ 16.667 ns OK)
    /// - T0L ~ 833.333 ns (expected 850 ns, delta ~ 16.667 ns OK)
    /// - T1H ~ 833.333 ns (expected 800 ns, delta ~ 33.333 ns OK)
    /// - T1L ~ 416.667 ns (expected 450 ns, delta ~ 33.333 ns OK)
    ///
    /// TX bytes per pixel: 3 ch × 8 bits × 3 SPI bits / 8 = 9 bytes.
    #[must_use]
    pub const fn ws2812_3bit() -> Self {
        Self::new(2_400_000, 0b100, 0b110, 3)
    }

    /// 4-bit SPI plan at 3.2 MHz for SK6812.
    ///
    /// Derived timing (spi_bit = 312.5 ns, tolerance +/-150 ns per SK6812 datasheet):
    /// - T0H = 312.5 ns (expected 300 ns, delta = 12.5 ns OK)
    /// - T0L = 937.5 ns (expected 900 ns, delta = 37.5 ns OK)
    /// - T1H ~ 625 ns (expected 600 ns, delta = 25 ns OK)
    /// - T1L ~ 625 ns (expected 600 ns, delta = 25 ns OK)
    ///
    /// TX bytes per pixel: 4 ch × 8 bits × 4 SPI bits / 8 = 16 bytes.
    /// Note: bits_per_symbol = 4; size TX_CAPACITY accordingly (larger than ws2812_3bit).
    #[must_use]
    pub const fn sk6812_4bit() -> Self {
        Self::new(3_200_000, 0b1000, 0b1100, 4)
    }

    /// 8-bit SPI plan at 3.2 MHz for WS2811 (400 kbps slow mode).
    ///
    /// Derived timing (spi_bit = 312.5 ns, tolerance +/-150 ns):
    /// - T0H = 625 ns (expected 500 ns, delta = 125 ns OK)
    /// - T0L = 1875 ns (expected 2000 ns, delta = 125 ns OK)
    /// - T1H = 1250 ns (expected 1200 ns, delta = 50 ns OK)
    /// - T1L = 1250 ns (expected 1300 ns, delta = 50 ns OK)
    ///
    /// TX bytes per pixel: 3 ch × 8 bits × 8 SPI bits / 8 = 24 bytes.
    #[must_use]
    pub const fn ws2811_8bit() -> Self {
        Self::new(3_200_000, 0b1100_0000, 0b1111_0000, 8)
    }

    /// 5-bit SPI plan at 4 MHz for the 48-bit WS2816B/WS2816C variants.
    ///
    /// T0H/T0L are 250/1000 ns and T1H/T1L are 750/500 ns. Each bit lasts
    /// 1250 ns, satisfying both the per-phase limits and the minimum bit period.
    /// TX bytes per pixel: 6 wire bytes × 5 = 30 bytes, plus reset.
    #[must_use]
    pub const fn ws2816_5bit() -> Self {
        Self::new(4_000_000, 0b10000, 0b11100, 5)
    }

    /// Appends extra reset time for external signal conditioning.
    #[must_use]
    pub const fn with_extra_reset_ns(mut self, extra_reset_ns: u32) -> Self {
        self.extra_reset_ns = extra_reset_ns;
        self
    }

    #[must_use]
    pub const fn spi_hz(&self) -> u32 {
        self.spi_hz
    }

    #[must_use]
    pub const fn zero_pattern(&self) -> u8 {
        self.zero_pattern
    }

    #[must_use]
    pub const fn one_pattern(&self) -> u8 {
        self.one_pattern
    }

    #[must_use]
    pub const fn bits_per_symbol(&self) -> u8 {
        self.bits_per_symbol
    }

    #[must_use]
    pub const fn extra_reset_ns(&self) -> u32 {
        self.extra_reset_ns
    }
}

/// Identifies one of the four timing edges in a single-wire protocol bit:
/// T0H (zero high), T0L (zero low), T1H (one high), T1L (one low).
///
/// Used by [`SpiCodecPlanError`] to report which edge failed validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimingEdge {
    /// Logical 0, high phase.
    ZeroHigh,
    /// Logical 0, low phase.
    ZeroLow,
    /// Logical 1, high phase.
    OneHigh,
    /// Logical 1, low phase.
    OneLow,
}

impl core::fmt::Display for TimingEdge {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let s = match self {
            Self::ZeroHigh => "T0H",
            Self::ZeroLow => "T0L",
            Self::OneHigh => "T1H",
            Self::OneLow => "T1L",
        };
        f.write_str(s)
    }
}

/// Errors returned when constructing a [`SpiCodec`] or validating an
/// [`SpiEncodingPlan`] against a protocol's timing limits and
/// reset-duration arithmetic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SpiCodecPlanError {
    ZeroClock,
    ZeroBitsPerSymbol,
    BitsPerSymbolTooWide {
        bits_per_symbol: u8,
    },
    PatternOutOfRange {
        pattern: u8,
        bits_per_symbol: u8,
    },
    InvalidSymbolWaveform {
        pattern: u8,
        bits_per_symbol: u8,
    },
    /// Logical 0 and 1 must produce different wire symbols.
    IdenticalSymbolPatterns {
        pattern: u8,
    },
    TimingOutOfTolerance {
        edge: TimingEdge,
        /// Rounded duration for diagnostics, saturated at `u32::MAX`.
        actual_ns: u32,
        expected_ns: u32,
        tolerance_ns: u32,
    },
    /// A phase violates explicit protocol timing limits.
    TimingOutOfRange {
        edge: TimingEdge,
        /// Rounded duration for diagnostics, saturated at `u32::MAX`.
        actual_ns: u32,
        minimum_ns: u32,
        maximum_ns: u32,
    },
    /// The complete high-plus-low symbol is shorter than the protocol permits.
    BitPeriodTooShort {
        /// Rounded duration for diagnostics, saturated at `u32::MAX`.
        actual_ns: u32,
        minimum_ns: u32,
    },
    /// Reset duration × SPI clock exceeds the `u64` fixed-point range used
    /// to compute reset byte counts.
    ResetDurationOverflow {
        /// Total requested reset duration in nanoseconds
        /// (`Proto::RESET_NS + extra_reset_ns`).
        total_reset_ns: u64,
        /// SPI clock frequency in Hz.
        spi_hz: u32,
    },
}

impl core::fmt::Display for SpiCodecPlanError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::ZeroClock => f.write_str("invalid SPI plan: spi_hz must be non-zero"),
            Self::ZeroBitsPerSymbol => {
                f.write_str("invalid SPI plan: bits_per_symbol must be non-zero")
            }
            Self::BitsPerSymbolTooWide { bits_per_symbol } => write!(
                f,
                "invalid SPI plan: bits_per_symbol={bits_per_symbol} exceeds 8"
            ),
            Self::PatternOutOfRange {
                pattern,
                bits_per_symbol,
            } => write!(
                f,
                "invalid SPI plan: pattern=0x{pattern:02X} out of range for bits_per_symbol={bits_per_symbol}"
            ),
            Self::InvalidSymbolWaveform {
                pattern,
                bits_per_symbol,
            } => write!(
                f,
                "invalid SPI plan: pattern=0x{pattern:02X} must be contiguous high then contiguous low within bits_per_symbol={bits_per_symbol}"
            ),
            Self::IdenticalSymbolPatterns { pattern } => write!(
                f,
                "invalid SPI plan: logical 0 and 1 use the same pattern=0x{pattern:02X}"
            ),
            Self::TimingOutOfTolerance {
                edge,
                actual_ns,
                expected_ns,
                tolerance_ns,
            } => write!(
                f,
                "timing out of tolerance: edge={edge} actual={actual_ns}ns expected={expected_ns}ns tolerance=\u{00B1}{tolerance_ns}ns"
            ),
            Self::TimingOutOfRange {
                edge,
                actual_ns,
                minimum_ns,
                maximum_ns,
            } => write!(
                f,
                "timing out of range: edge={edge} actual={actual_ns}ns permitted={minimum_ns}..={maximum_ns}ns"
            ),
            Self::BitPeriodTooShort {
                actual_ns,
                minimum_ns,
            } => write!(
                f,
                "bit period too short: actual={actual_ns}ns minimum={minimum_ns}ns"
            ),
            Self::ResetDurationOverflow {
                total_reset_ns,
                spi_hz,
            } => write!(
                f,
                "invalid SPI plan: reset duration overflow: total_reset_ns={total_reset_ns}ns \u{00D7} spi_hz={spi_hz}Hz exceeds the u64 fixed-point range"
            ),
        }
    }
}

impl core::error::Error for SpiCodecPlanError {}

/// Rare encode-time failures.
///
/// `SpiCodec::encode` validates required capacity up front. If
/// `InternalConsistency` appears, `encoded_len` and hot-path writes have
/// diverged —this indicates a logic bug in the codec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SpiEncodeError {
    InternalConsistency {
        stage: &'static str,
        required: usize,
        capacity: usize,
        attempted_len: usize,
    },
}

impl core::fmt::Display for SpiEncodeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InternalConsistency {
                stage,
                required,
                capacity,
                attempted_len,
            } => write!(
                f,
                "internal consistency error at {stage}: encoded_len={required}, capacity={capacity}, attempted_len={attempted_len}"
            ),
        }
    }
}

impl core::error::Error for SpiEncodeError {}

/// SPI-based wire codec that encodes LED pixel data into a byte stream
/// using configurable bit patterns (bit-banging over SPI MOSI).
///
/// Pre-computes inverted/normal patterns and reset fill bytes at construction
/// time so the hot encoding path is branch-free.
///
/// The type parameters `P` and `Proto` tie the codec to a specific
/// `<pixel, protocol>` pair at compile time —a codec built via
/// [`SpiCodec::<Rgb, Ws2812B>::for_protocol`](Self::for_protocol) cannot
/// be used with a [`LedStrip`](crate::LedStrip) parameterized on a different
/// protocol, even if both happen to implement the same [`WireCodec`](crate::WireCodec) trait.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpiCodec<P, Proto>
where
    P: LedPixel,
    Proto: SingleWireProtocol<P>,
{
    plan: SpiEncodingPlan,
    /// Zero-bit pattern, pre-inverted if `invert_output` was set at construction.
    zero_pattern: u8,
    /// One-bit pattern, pre-inverted if `invert_output` was set at construction.
    one_pattern: u8,
    /// Reset fill byte: 0x00 for normal, 0xFF for inverted output.
    reset_fill: u8,
    _marker: PhantomData<(P, Proto)>,
}

impl<P, Proto> SpiCodec<P, Proto>
where
    P: LedPixel,
    Proto: SingleWireProtocol<P>,
{
    /// Constructs a codec from a plan. Validates the plan's structural
    /// parameters (clock, symbol width, pattern range) and rejects reset
    /// durations whose fixed-point arithmetic would overflow, but does
    /// **not** check protocol timing. Use [`for_protocol`](Self::for_protocol)
    /// if timing validation is desired.
    /// Each symbol must be a distinct, contiguous high-then-low waveform.
    #[must_use = "SPI codec construction validates the plan; ignoring the result would silently drop errors"]
    pub fn new(plan: SpiEncodingPlan, invert_output: bool) -> Result<Self, SpiCodecPlanError> {
        validate_plan(plan)?;
        validate_reset_duration::<P, Proto>(&plan)?;
        Ok(Self::from_plan(plan, invert_output))
    }

    /// Constructs a codec with structural, protocol timing limits, and
    /// reset-duration overflow validation.
    ///
    /// Preferred over [`Self::new`] when the target protocol is known at construction time.
    /// Checks all four phases against `Proto::ZERO_MIN`/`ZERO_MAX` and
    /// `Proto::ONE_MIN`/`ONE_MAX`, plus `Proto::MIN_BIT_PERIOD_NS`, without
    /// rounding the durations. Error durations are rounded only for diagnostics.
    #[must_use = "returns Err on timing violations; use new() to skip timing validation"]
    pub fn for_protocol(
        plan: SpiEncodingPlan,
        invert_output: bool,
    ) -> Result<Self, SpiCodecPlanError> {
        validate_plan(plan)?;
        validate_timing::<P, Proto>(&plan)?;
        validate_reset_duration::<P, Proto>(&plan)?;
        Ok(Self::from_plan(plan, invert_output))
    }

    /// Pre-computes inverted/normal patterns and reset fill based on `invert_output`.
    ///
    /// When `invert_output` is true, each pattern bit is flipped within the
    /// `bits_per_symbol`-wide mask window (e.g. 0b100 —0b011 for 3-bit SPI).
    const fn from_plan(plan: SpiEncodingPlan, invert_output: bool) -> Self {
        if invert_output {
            let mask = pattern_mask(plan.bits_per_symbol());
            Self {
                zero_pattern: (!plan.zero_pattern()) & mask,
                one_pattern: (!plan.one_pattern()) & mask,
                reset_fill: u8::MAX,
                plan,
                _marker: PhantomData,
            }
        } else {
            Self {
                zero_pattern: plan.zero_pattern(),
                one_pattern: plan.one_pattern(),
                reset_fill: 0,
                plan,
                _marker: PhantomData,
            }
        }
    }

    #[must_use]
    pub const fn plan(&self) -> SpiEncodingPlan {
        self.plan
    }

    /// Computes how many SPI bytes of `reset_fill` are needed to satisfy
    /// `Proto::RESET_NS + extra_reset_ns` at the current SPI clock rate.
    ///
    /// Uses ceiling division: `ceil(ns * spi_hz / 1e9)`.
    ///
    /// Overflow is impossible here: `validate_reset_duration` rejects at
    /// construction time any plan whose fixed-point intermediate would
    /// exceed `u64::MAX`, so plain arithmetic is safe.
    fn reset_bytes(&self) -> usize
    where
        P: LedPixel,
        Proto: SingleWireProtocol<P>,
    {
        let total_reset_ns = u64::from(Proto::RESET_NS) + u64::from(self.plan.extra_reset_ns);

        // Fixed-point arithmetic: reset_ns × spi_hz gives scaled clock cycles
        // (in units of 10^9); dividing by 8 × 10^9 converts to SPI bytes in
        // one step (cycles → seconds → bytes). See `validate_reset_duration`
        // for the overflow guarantee covering the multiplication.
        let scaled_cycles = total_reset_ns * u64::from(self.plan.spi_hz);

        let total_bytes = scaled_cycles.div_ceil(8_000_000_000_u64);

        usize::try_from(total_bytes).unwrap_or(usize::MAX)
    }
}

impl<P, Proto> WireCodec<P, Proto, u8> for SpiCodec<P, Proto>
where
    P: LedPixel,
    Proto: SingleWireProtocol<P>,
{
    type EncodeError = SpiEncodeError;

    fn encoded_len(&self, pixel_count: usize) -> usize {
        // Saturating arithmetic: overflow (requiring billions of pixels)
        // saturates to a value that still fails the capacity check in `encode`,
        // so no explicit early-return branches are needed.
        let frame_bytes = pixel_count.saturating_mul(P::BYTES_PER_PIXEL);
        let payload_bits = frame_bytes
            .saturating_mul(8)
            .saturating_mul(usize::from(self.plan.bits_per_symbol));
        let payload_bytes = payload_bits.saturating_add(7) / 8;
        let total = payload_bytes.saturating_add(self.reset_bytes());

        debug_assert!(
            total < usize::MAX / 2,
            "encoded_len overflowed: frame too large for usize"
        );

        total
    }

    fn encode<const TX_CAPACITY: usize>(
        &self,
        color_order: P::Order,
        pixels: &[P],
        out: &mut Vec<u8, TX_CAPACITY>,
    ) -> LedStripResult<(), Self::EncodeError> {
        let required = self.encoded_len(pixels.len());
        if required > TX_CAPACITY {
            return Err(LedStripError::BufferTooSmall {
                required,
                capacity: TX_CAPACITY,
            });
        }

        out.clear();

        let mut current_byte = 0_u8;
        let mut used_bits = 0_u8;
        let mut raw = [0_u8; 6];
        for pixel in pixels.iter().copied() {
            pixel.encode(color_order, &mut raw[..P::BYTES_PER_PIXEL]);

            for byte in &raw[..P::BYTES_PER_PIXEL] {
                for bit_index in 0..8 {
                    let shift = bit_shift(bit_index);
                    let bit_is_set = ((*byte >> shift) & 1) != 0;
                    let pattern = if bit_is_set {
                        self.one_pattern
                    } else {
                        self.zero_pattern
                    };

                    append_pattern::<TX_CAPACITY>(
                        out,
                        pattern,
                        self.plan.bits_per_symbol(),
                        required,
                        &mut current_byte,
                        &mut used_bits,
                    )?;
                }
            }
        }

        // Invariant: the total encoded bit count is always a multiple of 8
        // (BYTES_PER_PIXEL × 8 × bits_per_symbol × pixel_count), so `used_bits`
        // is always 0 here. Any other value indicates a codec logic bug.
        debug_assert_eq!(used_bits, 0, "total encoded bits must be a multiple of 8");

        let reset_bytes = self.reset_bytes();
        let target_len = out.len().saturating_add(reset_bytes);
        out.resize(target_len, self.reset_fill).map_err(|_| {
            LedStripError::Operation(SpiEncodeError::InternalConsistency {
                stage: "reset_tail_resize",
                required,
                capacity: TX_CAPACITY,
                attempted_len: target_len,
            })
        })?;

        Ok(())
    }
}

/// SPI transport backend.
///
/// Wraps an [`embedded_hal::spi::SpiBus`] implementor. The codec handles all
/// protocol-level concerns (timing, bit patterns, reset); this backend only
/// pushes the resulting byte stream over MOSI.
#[derive(Debug)]
pub struct SpiBackend<SPI> {
    spi: SPI,
}

impl<SPI> SpiBackend<SPI> {
    /// Wraps an SPI peripheral.
    #[must_use]
    pub const fn new(spi: SPI) -> Self {
        Self { spi }
    }

    /// Consumes the backend, returning the underlying SPI peripheral.
    #[must_use]
    pub fn into_inner(self) -> SPI {
        self.spi
    }

    /// Returns a shared reference to the SPI peripheral.
    #[must_use]
    pub fn inner(&self) -> &SPI {
        &self.spi
    }

    /// Returns a mutable reference to the SPI peripheral.
    #[must_use]
    pub fn inner_mut(&mut self) -> &mut SPI {
        &mut self.spi
    }
}

impl<SPI> TransportBackend for SpiBackend<SPI>
where
    SPI: SpiBus<u8>,
{
    type Word = u8;
    type Error = SPI::Error;

    fn transmit(&mut self, words: &[Self::Word]) -> Result<(), Self::Error> {
        self.spi.write(words)?;
        self.spi.flush()
    }
}

/// Returns the bitmask covering `bits_per_symbol` low bits.
///
/// For `bits_per_symbol == 8` this is `0xFF`; otherwise `(1 << n) - 1`.
const fn pattern_mask(bits_per_symbol: u8) -> u8 {
    if bits_per_symbol == 8 {
        u8::MAX
    } else {
        (1_u8 << bits_per_symbol) - 1
    }
}

fn validate_plan(plan: SpiEncodingPlan) -> Result<(), SpiCodecPlanError> {
    if plan.spi_hz == 0 {
        return Err(SpiCodecPlanError::ZeroClock);
    }

    if plan.bits_per_symbol == 0 {
        return Err(SpiCodecPlanError::ZeroBitsPerSymbol);
    }

    if plan.bits_per_symbol > 8 {
        return Err(SpiCodecPlanError::BitsPerSymbolTooWide {
            bits_per_symbol: plan.bits_per_symbol,
        });
    }

    let limit = pattern_mask(plan.bits_per_symbol);

    if plan.zero_pattern > limit {
        return Err(SpiCodecPlanError::PatternOutOfRange {
            pattern: plan.zero_pattern,
            bits_per_symbol: plan.bits_per_symbol,
        });
    }

    if plan.one_pattern > limit {
        return Err(SpiCodecPlanError::PatternOutOfRange {
            pattern: plan.one_pattern,
            bits_per_symbol: plan.bits_per_symbol,
        });
    }

    simulate_symbol_phases(plan.zero_pattern, plan.bits_per_symbol)?;
    simulate_symbol_phases(plan.one_pattern, plan.bits_per_symbol)?;

    if plan.zero_pattern == plan.one_pattern {
        return Err(SpiCodecPlanError::IdenticalSymbolPatterns {
            pattern: plan.zero_pattern,
        });
    }

    Ok(())
}

/// Rejects plans whose reset-duration fixed-point arithmetic would overflow
/// `u64` in [`SpiCodec::reset_bytes`](crate::SpiCodec).
///
/// Must be called after `validate_plan`, which guarantees `spi_hz != 0`.
/// With this guarantee, `reset_bytes` can use plain arithmetic.
fn validate_reset_duration<P, Proto>(plan: &SpiEncodingPlan) -> Result<(), SpiCodecPlanError>
where
    P: LedPixel,
    Proto: SingleWireProtocol<P>,
{
    // RESET_NS and extra_reset_ns are both u32, so the sum cannot overflow u64.
    let total_reset_ns = u64::from(Proto::RESET_NS) + u64::from(plan.extra_reset_ns);

    // `div_ceil` in `reset_bytes` has no additive intermediate, so the
    // multiplication is the only step that can overflow.
    if total_reset_ns > u64::MAX / u64::from(plan.spi_hz) {
        return Err(SpiCodecPlanError::ResetDurationOverflow {
            total_reset_ns,
            spi_hz: plan.spi_hz,
        });
    }

    Ok(())
}

/// Returns the bit position within a pixel byte for the given logical bit index.
/// All supported protocols transmit the most significant bit first, so
/// bit 0 -> position 7, bit 1 -> position 6, and so on.
#[inline]
fn bit_shift(bit_index: u8) -> u8 {
    7 - bit_index
}

/// Stream-oriented SPI bit-packing kernel.
///
/// Appends `bits_per_symbol` bits of `pattern` (MSB-first within the pattern)
/// into the SPI output buffer. Bits are accumulated into `current_byte` from
/// MSB to LSB; when the byte is full it is pushed and a new byte starts.
///
/// The pattern should already be inverted if the output line uses an external
/// inverter (pre-computed by `SpiCodec::from_plan`).
///
/// This is the hot path during `refresh`. The capacity check was already
/// performed at the top of `encode()`, so push failures here indicate a
/// logic error in `encoded_len` —the error path is cold but provides a
/// safe panic-free fallback instead of UB.
#[inline]
fn append_pattern<const TX_CAPACITY: usize>(
    out: &mut Vec<u8, TX_CAPACITY>,
    pattern: u8,
    bits_per_symbol: u8,
    required: usize,
    current_byte: &mut u8,
    used_bits: &mut u8,
) -> LedStripResult<(), SpiEncodeError> {
    for shift in (0..bits_per_symbol).rev() {
        let bit = ((pattern >> shift) & 1) != 0;

        if bit {
            *current_byte |= 1_u8 << (7 - *used_bits);
        }

        *used_bits += 1;
        if *used_bits == 8 {
            out.push(*current_byte).map_err(|_| {
                LedStripError::Operation(SpiEncodeError::InternalConsistency {
                    stage: "append_pattern_push",
                    required,
                    capacity: TX_CAPACITY,
                    attempted_len: out.len().saturating_add(1),
                })
            })?;

            *current_byte = 0;
            *used_bits = 0;
        }
    }
    Ok(())
}

/// Simulates a symbol bit-by-bit and returns `(high_bits, low_bits)`.
///
/// Valid symbols are contiguous high followed by contiguous low with at least
/// one bit in each phase.
fn simulate_symbol_phases(pattern: u8, bits_per_symbol: u8) -> Result<(u8, u8), SpiCodecPlanError> {
    let mut high_bits = 0_u8;
    let mut low_bits = 0_u8;
    let mut in_low_phase = false;

    for shift in (0..bits_per_symbol).rev() {
        let bit_is_high = ((pattern >> shift) & 1) != 0;

        if !in_low_phase {
            if bit_is_high {
                high_bits += 1;
            } else if high_bits == 0 {
                return Err(SpiCodecPlanError::InvalidSymbolWaveform {
                    pattern,
                    bits_per_symbol,
                });
            } else {
                in_low_phase = true;
                low_bits = 1;
            }
        } else if bit_is_high {
            return Err(SpiCodecPlanError::InvalidSymbolWaveform {
                pattern,
                bits_per_symbol,
            });
        } else {
            low_bits += 1;
        }
    }

    if high_bits == 0 || low_bits == 0 {
        return Err(SpiCodecPlanError::InvalidSymbolWaveform {
            pattern,
            bits_per_symbol,
        });
    }

    Ok((high_bits, low_bits))
}

/// Checks exact phase durations against inclusive protocol bounds.
/// Cross multiplication avoids rounding an SPI cycle before scaling a phase.
fn validate_timing<P, Proto>(plan: &SpiEncodingPlan) -> Result<(), SpiCodecPlanError>
where
    P: LedPixel,
    Proto: SingleWireProtocol<P>,
{
    let tolerance = Proto::TIMING_TOLERANCE_NS;

    let (zero_high, zero_low) = simulate_symbol_phases(plan.zero_pattern, plan.bits_per_symbol)?;
    let (one_high, one_low) = simulate_symbol_phases(plan.one_pattern, plan.bits_per_symbol)?;

    check_timing(
        zero_high,
        plan.spi_hz,
        Proto::ZERO.high_ns,
        Proto::ZERO_MIN.high_ns,
        Proto::ZERO_MAX.high_ns,
        tolerance,
        TimingEdge::ZeroHigh,
    )?;
    check_timing(
        zero_low,
        plan.spi_hz,
        Proto::ZERO.low_ns,
        Proto::ZERO_MIN.low_ns,
        Proto::ZERO_MAX.low_ns,
        tolerance,
        TimingEdge::ZeroLow,
    )?;
    check_timing(
        one_high,
        plan.spi_hz,
        Proto::ONE.high_ns,
        Proto::ONE_MIN.high_ns,
        Proto::ONE_MAX.high_ns,
        tolerance,
        TimingEdge::OneHigh,
    )?;
    check_timing(
        one_low,
        plan.spi_hz,
        Proto::ONE.low_ns,
        Proto::ONE_MIN.low_ns,
        Proto::ONE_MAX.low_ns,
        tolerance,
        TimingEdge::OneLow,
    )?;

    // Both symbols have the same width, so their total bit periods are equal.
    if u64::from(plan.bits_per_symbol) * 1_000_000_000
        < u64::from(Proto::MIN_BIT_PERIOD_NS) * u64::from(plan.spi_hz)
    {
        return Err(SpiCodecPlanError::BitPeriodTooShort {
            actual_ns: rounded_duration_ns(plan.bits_per_symbol, plan.spi_hz),
            minimum_ns: Proto::MIN_BIT_PERIOD_NS,
        });
    }

    Ok(())
}

fn check_timing(
    phase_bits: u8,
    spi_hz: u32,
    expected_ns: u32,
    minimum_ns: u32,
    maximum_ns: u32,
    tolerance_ns: u32,
    edge: TimingEdge,
) -> Result<(), SpiCodecPlanError> {
    // A u32 nanosecond bound multiplied by a u32 frequency always fits u64.
    // Validated phase widths are at most 7 bits, even for a 1 Hz SPI clock.
    let scaled_duration = u64::from(phase_bits) * 1_000_000_000;
    if scaled_duration < u64::from(minimum_ns) * u64::from(spi_hz)
        || scaled_duration > u64::from(maximum_ns) * u64::from(spi_hz)
    {
        let actual_ns = rounded_duration_ns(phase_bits, spi_hz);
        // Keep the existing error variant for protocols using the legacy
        // symmetric tolerance, while reporting explicit limits accurately.
        if minimum_ns == expected_ns.saturating_sub(tolerance_ns)
            && maximum_ns == expected_ns.saturating_add(tolerance_ns)
        {
            return Err(SpiCodecPlanError::TimingOutOfTolerance {
                edge,
                actual_ns,
                expected_ns,
                tolerance_ns,
            });
        }
        return Err(SpiCodecPlanError::TimingOutOfRange {
            edge,
            actual_ns,
            minimum_ns,
            maximum_ns,
        });
    }
    Ok(())
}

/// Rounds the whole phase for diagnostics only. Validation uses exact ratios.
fn rounded_duration_ns(bits: u8, spi_hz: u32) -> u32 {
    let scaled_duration = u64::from(bits) * 1_000_000_000;
    let actual_ns = (scaled_duration + u64::from(spi_hz) / 2) / u64::from(spi_hz);
    u32::try_from(actual_ns).unwrap_or(u32::MAX)
}

#[cfg(test)]
mod tests {
    use crate::{
        Rgb, Rgb16, Rgbw, Sk6812, SpiBackend, TransportBackend, WireCodec, Ws2811, Ws2812B,
    };

    use super::{SpiCodec, SpiCodecPlanError, SpiEncodeError, SpiEncodingPlan, TimingEdge};

    #[test]
    fn ws2812_3bit_passes_ws2812b_timing() {
        SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
    }

    #[test]
    fn sk6812_4bit_passes_sk6812_timing() {
        SpiCodec::<Rgbw, Sk6812>::for_protocol(SpiEncodingPlan::sk6812_4bit(), false).unwrap();
    }

    #[test]
    fn ws2812_3bit_rejects_sk6812_timing() {
        // T1H: actual —832 ns, expected = 600 ns, Δ = 232 ns > 150 ns tolerance.
        let err = SpiCodec::<Rgbw, Sk6812>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false)
            .unwrap_err();
        assert!(matches!(
            err,
            SpiCodecPlanError::TimingOutOfTolerance {
                edge: TimingEdge::OneHigh,
                ..
            }
        ));
    }

    #[test]
    fn out_of_tolerance_plan_reports_first_failing_edge() {
        // 1 MHz 3-bit: spi_bit = 1000 ns, T0H = 1000 ns vs WS2812B T0H = 400 ns, Δ = 600 ns.
        let plan = SpiEncodingPlan::new(1_000_000, 0b100, 0b110, 3);
        let err = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap_err();
        assert_eq!(
            err,
            SpiCodecPlanError::TimingOutOfTolerance {
                edge: TimingEdge::ZeroHigh,
                actual_ns: 1000,
                expected_ns: 400,
                tolerance_ns: 150,
            }
        );
    }

    #[test]
    fn timing_edge_display_uses_protocol_labels() {
        assert_eq!(TimingEdge::ZeroHigh.to_string(), "T0H");
        assert_eq!(TimingEdge::ZeroLow.to_string(), "T0L");
        assert_eq!(TimingEdge::OneHigh.to_string(), "T1H");
        assert_eq!(TimingEdge::OneLow.to_string(), "T1L");
    }

    #[test]
    fn plan_error_display_zero_clock() {
        let s = SpiCodecPlanError::ZeroClock.to_string();
        assert!(s.contains("spi_hz"), "{s}");
    }

    #[test]
    fn plan_error_display_zero_bits_per_symbol() {
        let s = SpiCodecPlanError::ZeroBitsPerSymbol.to_string();
        assert!(s.contains("bits_per_symbol"), "{s}");
    }

    #[test]
    fn plan_error_display_bits_per_symbol_too_wide() {
        let s = SpiCodecPlanError::BitsPerSymbolTooWide { bits_per_symbol: 9 }.to_string();
        assert!(s.contains("bits_per_symbol=9"), "{s}");
    }

    #[test]
    fn plan_error_display_pattern_out_of_range() {
        let s = SpiCodecPlanError::PatternOutOfRange {
            pattern: 0xFF,
            bits_per_symbol: 3,
        }
        .to_string();
        assert!(s.contains("0xFF"), "{s}");
        assert!(s.contains("bits_per_symbol=3"), "{s}");
    }

    #[test]
    fn plan_error_display_invalid_symbol_waveform() {
        let s = SpiCodecPlanError::InvalidSymbolWaveform {
            pattern: 0b101,
            bits_per_symbol: 3,
        }
        .to_string();
        assert!(s.contains("0x05"), "{s}");
        assert!(s.contains("contiguous high then contiguous low"), "{s}");
    }

    #[test]
    fn plan_error_display_timing_out_of_tolerance_includes_all_fields() {
        let s = SpiCodecPlanError::TimingOutOfTolerance {
            edge: TimingEdge::OneHigh,
            actual_ns: 832,
            expected_ns: 600,
            tolerance_ns: 150,
        }
        .to_string();
        assert!(s.contains("T1H"), "{s}");
        assert!(s.contains("832"), "{s}");
        assert!(s.contains("600"), "{s}");
        assert!(s.contains("150"), "{s}");
    }

    #[test]
    fn plan_error_display_reset_duration_overflow() {
        let s = SpiCodecPlanError::ResetDurationOverflow {
            total_reset_ns: 4_295_017_295,
            spi_hz: u32::MAX,
        }
        .to_string();
        assert!(s.contains("reset duration overflow"), "{s}");
        assert!(s.contains("4295017295"), "{s}");
        assert!(s.contains("4294967295"), "{s}");
    }

    #[test]
    fn plan_error_is_core_error() {
        let _: &dyn core::error::Error = &SpiCodecPlanError::ZeroClock;
    }

    // ── Encode end-to-end tests ──────────────────────────────────────

    use crate::{LedStripError, RgbOrder};
    use heapless::Vec as HVec;

    #[test]
    fn encode_produces_nonempty_buffer() {
        let codec =
            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
        let pixels = [Rgb::new(0, 255, 0)];
        let mut out: HVec<u8, 64> = HVec::new();

        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();

        assert!(!out.is_empty(), "encoded output should not be empty");
        // ws2812_3bit: 3 ch × 8 bits × 3 spi_bits / 8 = 9 payload bytes + reset
        assert!(out.len() >= 9, "expected >=9 bytes, got {}", out.len());
    }

    #[test]
    fn encode_output_len_matches_encoded_len() {
        let codec =
            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
        let pixel_count = 3;
        let pixels = [
            Rgb::new(255, 0, 0),
            Rgb::new(0, 255, 0),
            Rgb::new(0, 0, 255),
        ];
        let mut out: HVec<u8, 256> = HVec::new();

        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();

        assert_eq!(
            out.len(),
            codec.encoded_len(pixel_count),
            "output len must match encoded_len prediction"
        );
    }

    #[test]
    fn encode_rejects_buffer_too_small() {
        let codec =
            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
        let pixels = [Rgb::new(0, 0, 0), Rgb::new(0, 0, 0)];
        // 2 pixels * 9 bytes = 18 + reset_bytes —need > 30, give only 5
        let mut out: HVec<u8, 5> = HVec::new();

        let err = codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap_err();
        assert!(matches!(err, LedStripError::BufferTooSmall { .. }));
    }

    // ── invert_output tests ──────────────────────────────────────────

    #[test]
    fn inverted_codec_precomputes_patterns_correctly() {
        let plan = SpiEncodingPlan::ws2812_3bit(); // 0b100, 0b110, 3 bits/symbol
        let codec = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, true).unwrap();

        // In 3-bit window (mask=0b111): !0b100 = 0b011, !0b110 = 0b001
        assert_eq!(codec.zero_pattern, 0b011);
        assert_eq!(codec.one_pattern, 0b001);
        assert_eq!(codec.reset_fill, 0xFF);
    }

    #[test]
    fn invert_output_produces_different_data_and_reset() {
        let plan = SpiEncodingPlan::ws2812_3bit();
        let codec_normal = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap();
        let codec_inverted = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, true).unwrap();
        let pixels = [Rgb::new(255, 0, 0)];
        let mut out_normal: HVec<u8, 128> = HVec::new();
        let mut out_inverted: HVec<u8, 128> = HVec::new();

        codec_normal
            .encode(RgbOrder::Grb, &pixels, &mut out_normal)
            .unwrap();
        codec_inverted
            .encode(RgbOrder::Grb, &pixels, &mut out_inverted)
            .unwrap();

        // Same length
        assert_eq!(out_normal.len(), out_inverted.len());
        // Different content (inverted data bits)
        assert_ne!(out_normal, out_inverted);
        // Reset fill bytes differ
        let last_normal = *out_normal.last().unwrap();
        let last_inverted = *out_inverted.last().unwrap();
        assert_eq!(last_normal, 0x00, "normal reset fill should be 0x00");
        assert_eq!(last_inverted, 0xFF, "inverted reset fill should be 0xFF");
    }

    // ── Golden output tests ─────────────────────────────────────────

    #[test]
    fn black_pixel_produces_all_zero_patterns() {
        // One BLACK pixel (Rgb=0,0,0) with ws2812_3bit: every payload byte
        // is 0x92, 0x49, 0x24 (3 bytes per channel, GRB order, repeated).
        let codec =
            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
        let pixels = [Rgb::BLACK];
        let mut out: HVec<u8, 128> = HVec::new();
        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();

        let payload_bytes = out.len() - codec.reset_bytes();
        // 3 channels * 3 bytes/channel = 9 payload bytes
        assert_eq!(payload_bytes, 9);
        let expected_cycle: [u8; 3] = [0x92, 0x49, 0x24];
        for (i, &b) in out[..payload_bytes].iter().enumerate() {
            assert_eq!(
                b,
                expected_cycle[i % 3],
                "black pixel byte {i}: expected 0x{:02X}, got 0x{b:02X}",
                expected_cycle[i % 3]
            );
        }
    }

    #[test]
    fn white_pixel_produces_all_one_patterns() {
        let codec =
            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
        let pixels = [Rgb::WHITE];
        let mut out: HVec<u8, 128> = HVec::new();
        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();

        let payload_bytes = out.len() - codec.reset_bytes();
        assert_eq!(payload_bytes, 9);
        let expected_cycle: [u8; 3] = [0xDB, 0x6D, 0xB6];
        for (i, &b) in out[..payload_bytes].iter().enumerate() {
            assert_eq!(
                b,
                expected_cycle[i % 3],
                "white pixel byte {i}: expected 0x{:02X}, got 0x{b:02X}",
                expected_cycle[i % 3]
            );
        }
    }

    #[test]
    fn green_pixel_produces_mixed_patterns_grb() {
        // Rgb(0,255,0) in GRB order: G=255 (ones), R=0 (zeros), B=0 (zeros)
        let codec =
            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
        let pixels = [Rgb::new(0, 255, 0)];
        let mut out: HVec<u8, 128> = HVec::new();
        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();

        let payload_bytes = out.len() - codec.reset_bytes();
        assert_eq!(payload_bytes, 9);
        // Channel 1 (G): ones pattern
        let ones: [u8; 3] = [0xDB, 0x6D, 0xB6];
        // Channel 2 (R): zeros pattern
        let zeros: [u8; 3] = [0x92, 0x49, 0x24];
        // Channel 3 (B): zeros pattern
        assert_eq!(&out[0..3], &ones, "G channel (first) should be all-ones");
        assert_eq!(&out[3..6], &zeros, "R channel (second) should be all-zeros");
        assert_eq!(&out[6..9], &zeros, "B channel (third) should be all-zeros");
    }

    // ── Timing validation boundary tests ─────────────────────────────

    #[test]
    fn validate_timing_reports_first_failing_edge() {
        // 4 MHz 3-bit: spi_bit=250 ns
        // T0H=250 ns (Δ=150, at tolerance —, T0L=500 ns (Δ=350, >150 —
        let plan = SpiEncodingPlan::new(4_000_000, 0b100, 0b110, 3);
        let err = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap_err();
        assert!(matches!(
            err,
            SpiCodecPlanError::TimingOutOfTolerance {
                edge: TimingEdge::ZeroLow,
                ..
            }
        ));
    }

    #[test]
    fn timing_exactly_at_tolerance_boundary_passes() {
        // T0H=400, T0L=1000, T1H=800, T1L=600 ns.
        // Both low phases are exactly at their +150 ns tolerance boundary.
        let plan = SpiEncodingPlan::new(5_000_000, 0b1100000, 0b1111000, 7);
        SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap();
    }

    // ── SpiEncodingPlan getters / extra_reset ───────────────────────

    #[test]
    fn plan_getters_return_construction_values() {
        let plan = SpiEncodingPlan::new(3_000_000, 0b1010, 0b1110, 4);
        assert_eq!(plan.spi_hz(), 3_000_000);
        assert_eq!(plan.zero_pattern(), 0b1010);
        assert_eq!(plan.one_pattern(), 0b1110);
        assert_eq!(plan.bits_per_symbol(), 4);
        assert_eq!(plan.extra_reset_ns(), 0);
    }

    #[test]
    fn plan_with_extra_reset_ns_stores_value() {
        let plan = SpiEncodingPlan::ws2812_3bit().with_extra_reset_ns(10_000);
        assert_eq!(plan.extra_reset_ns(), 10_000);
    }

    // ── SpiCodec::new (no timing, structural only) ──────────────────

    #[test]
    fn spi_codec_new_with_valid_plan_succeeds() {
        SpiCodec::<Rgb, Ws2812B>::new(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
    }

    #[test]
    fn spi_codec_new_with_inverted_output_succeeds() {
        SpiCodec::<Rgb, Ws2812B>::new(SpiEncodingPlan::ws2812_3bit(), true).unwrap();
    }

    #[test]
    fn spi_codec_new_rejects_zero_clock() {
        let plan = SpiEncodingPlan::new(0, 0b100, 0b110, 3);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert_eq!(err, SpiCodecPlanError::ZeroClock);
    }

    #[test]
    fn spi_codec_plan_accessor_returns_original_plan() {
        let plan = SpiEncodingPlan::ws2812_3bit();
        let codec = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap();
        assert_eq!(codec.plan(), plan);
    }

    // ── SpiBackend ───────────────────────────────────────────────────

    #[test]
    fn spi_backend_new() {
        let backend = SpiBackend::new(42_u32);
        assert_eq!(*backend.inner(), 42);
    }

    #[test]
    fn spi_backend_into_inner() {
        let backend = SpiBackend::new("hello");
        assert_eq!(backend.into_inner(), "hello");
    }

    #[test]
    fn spi_backend_inner_mut_modifies_value() {
        let mut backend = SpiBackend::new(10_u32);
        *backend.inner_mut() = 99;
        assert_eq!(*backend.inner(), 99);
    }

    // ── Mock SPI transmit ────────────────────────────────────────────

    use core::cell::Cell;
    use embedded_hal::spi::SpiBus;

    #[derive(Debug, Default)]
    struct MockSpi(Cell<usize>);

    impl embedded_hal::spi::ErrorType for MockSpi {
        type Error = core::convert::Infallible;
    }

    impl SpiBus<u8> for MockSpi {
        fn read(&mut self, _words: &mut [u8]) -> Result<(), Self::Error> {
            Ok(())
        }
        fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
            self.0.set(words.len());
            Ok(())
        }
        fn transfer(&mut self, _read: &mut [u8], _write: &[u8]) -> Result<(), Self::Error> {
            Ok(())
        }
        fn transfer_in_place(&mut self, _words: &mut [u8]) -> Result<(), Self::Error> {
            Ok(())
        }
        fn flush(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }
    }

    #[test]
    fn transmit_delegates_to_spi_bus_write() {
        let mut backend = SpiBackend::new(MockSpi::default());
        let data = [1_u8, 2, 3, 4, 5];
        backend.transmit(&data).unwrap();
        assert_eq!(backend.inner().0.get(), 5);
    }

    // ── Other protocol encodings ─────────────────────────────────────

    use crate::{Rgb16Order, RgbwOrder, Ws2816};

    #[test]
    fn encode_sk6812_produces_correct_length() {
        let codec =
            SpiCodec::<Rgbw, Sk6812>::for_protocol(SpiEncodingPlan::sk6812_4bit(), false).unwrap();
        let pixel_count = 2;
        let pixels = [Rgbw::new(0, 0, 0, 0), Rgbw::new(0, 0, 0, 0)];
        let mut out: HVec<u8, 256> = HVec::new();
        codec.encode(RgbwOrder::Grbw, &pixels, &mut out).unwrap();
        assert_eq!(out.len(), codec.encoded_len(pixel_count));
    }

    #[test]
    fn encode_ws2811_produces_correct_length() {
        // 8-bit symbols at 3.2 MHz -- all edges within +/-150 ns of WS2811 spec.
        let codec =
            SpiCodec::<Rgb, Ws2811>::for_protocol(SpiEncodingPlan::ws2811_8bit(), false).unwrap();
        let pixel_count = 2;
        let pixels = [Rgb::new(0, 0, 0), Rgb::new(0, 0, 0)];
        let mut out: HVec<u8, 256> = HVec::new();
        codec.encode(RgbOrder::Rgb, &pixels, &mut out).unwrap();
        assert_eq!(out.len(), codec.encoded_len(pixel_count));
    }

    #[test]
    fn encode_ws2816_produces_correct_length() {
        let codec =
            SpiCodec::<Rgb16, Ws2816>::for_protocol(SpiEncodingPlan::ws2816_5bit(), false).unwrap();
        let pixel_count = 1;
        let pixels = [Rgb16::new(0, 0, 0)];
        let mut out: HVec<u8, 256> = HVec::new();
        codec.encode(Rgb16Order::Grb, &pixels, &mut out).unwrap();
        assert_eq!(out.len(), codec.encoded_len(pixel_count));
        // 48 bits × 5 SPI bits = 30 payload bytes, plus 300 us at 4 MHz = 150 bytes.
        assert_eq!(out.len(), 180);
    }

    #[test]
    fn ws2816_black_and_white_have_different_payloads() {
        let codec =
            SpiCodec::<Rgb16, Ws2816>::for_protocol(SpiEncodingPlan::ws2816_5bit(), false).unwrap();
        let mut black: HVec<u8, 180> = HVec::new();
        let mut white: HVec<u8, 180> = HVec::new();
        codec
            .encode(Rgb16Order::Grb, &[Rgb16::BLACK], &mut black)
            .unwrap();
        codec
            .encode(Rgb16Order::Grb, &[Rgb16::WHITE], &mut white)
            .unwrap();
        assert_ne!(&black[..30], &white[..30]);
        assert_eq!(&black[30..], &[0; 150]);
        assert_eq!(&white[30..], &[0; 150]);
    }

    #[test]
    fn ws2816_rejects_the_previous_four_bit_plan() {
        let plan = SpiEncodingPlan::new(4_000_000, 0b1000, 0b1100, 4);
        assert_eq!(
            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
            SpiCodecPlanError::TimingOutOfRange {
                edge: TimingEdge::ZeroLow,
                actual_ns: 750,
                minimum_ns: 800,
                maximum_ns: 1_200,
            }
        );
    }

    #[test]
    fn ws2816_checks_the_bit_period_independently_of_phase_limits() {
        // All four phases (200/1000/600/600 ns) satisfy their individual bounds.
        let plan = SpiEncodingPlan::new(5_000_000, 0b100000, 0b111000, 6);
        assert_eq!(
            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
            SpiCodecPlanError::BitPeriodTooShort {
                actual_ns: 1_200,
                minimum_ns: 1_250,
            }
        );
    }

    #[test]
    fn ws2816_does_not_round_a_short_bit_period_up_to_the_limit() {
        SpiCodec::<Rgb16, Ws2816>::for_protocol(SpiEncodingPlan::ws2816_5bit(), false).unwrap();
        // Its phases remain valid, but the 1249.9996875 ns period is too short.
        let plan = SpiEncodingPlan::new(4_000_001, 0b10000, 0b11100, 5);
        assert_eq!(
            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
            SpiCodecPlanError::BitPeriodTooShort {
                actual_ns: 1_250,
                minimum_ns: 1_250,
            }
        );
    }

    #[test]
    fn ws2816_accepts_inclusive_phase_boundaries() {
        let plans = [
            // T0H=200 min, T0L=1200 max, T1H=800 max, T1L=600 ns.
            SpiEncodingPlan::new(5_000_000, 0b1000000, 0b1111000, 7),
            // T0H=320 max, T0L=960, T1H=800 max, T1L=480 min ns.
            SpiEncodingPlan::new(6_250_000, 0b11000000, 0b11111000, 8),
        ];
        for plan in plans {
            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap();
        }
    }

    #[test]
    fn ws2816_rejects_fractional_phase_boundary_violations() {
        let cases = [
            // T0H is slightly below 200 ns.
            (
                SpiEncodingPlan::new(5_000_001, 0b1000000, 0b1111000, 7),
                TimingEdge::ZeroHigh,
            ),
            // T0L is slightly above 1200 ns.
            (
                SpiEncodingPlan::new(4_999_999, 0b1000000, 0b1111000, 7),
                TimingEdge::ZeroLow,
            ),
            // T0H is slightly above 320 ns.
            (
                SpiEncodingPlan::new(6_249_999, 0b11000000, 0b11111000, 8),
                TimingEdge::ZeroHigh,
            ),
            // T1L is slightly below 480 ns.
            (
                SpiEncodingPlan::new(6_250_001, 0b11000000, 0b11111000, 8),
                TimingEdge::OneLow,
            ),
        ];
        for (plan, expected_edge) in cases {
            assert!(matches!(
                SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false),
                Err(SpiCodecPlanError::TimingOutOfRange { edge, .. }) if edge == expected_edge
            ));
        }
    }

    #[test]
    fn ws2816_checks_the_fractional_one_high_lower_boundary() {
        // A 520 ns phase cannot be represented exactly with these SPI frequencies.
        // Two cycles fall just above the limit at 3_846_153 Hz and below it at
        // 3_846_154 Hz, although both diagnostic durations round to 520 ns.
        let inside = SpiEncodingPlan::new(3_846_153, 0b10000, 0b11000, 5);
        SpiCodec::<Rgb16, Ws2816>::for_protocol(inside, false).unwrap();
        let outside = SpiEncodingPlan::new(3_846_154, 0b10000, 0b11000, 5);
        assert_eq!(
            SpiCodec::<Rgb16, Ws2816>::for_protocol(outside, false).unwrap_err(),
            SpiCodecPlanError::TimingOutOfRange {
                edge: TimingEdge::OneHigh,
                actual_ns: 520,
                minimum_ns: 520,
                maximum_ns: 800,
            }
        );
    }

    #[test]
    fn timing_accepts_valid_fractional_phases_without_rounding_each_spi_cycle() {
        // WS2812B phases: 466.853/700.280/700.280/466.853 ns, all within limits.
        let plan = SpiEncodingPlan::new(4_284_000, 0b11000, 0b11100, 5);
        SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap();
        // WS2811 phases: 616.998/1850.995/1233.997/1233.997 ns, all within limits.
        let plan = SpiEncodingPlan::new(3_241_500, 0b11000000, 0b11110000, 8);
        SpiCodec::<Rgb, Ws2811>::for_protocol(plan, false).unwrap();
    }

    #[test]
    fn timing_rejects_fractional_phases_outside_the_legacy_tolerance() {
        // T0L is 699.301 ns, below the 700 ns minimum.
        let plan = SpiEncodingPlan::new(2_860_000, 0b100, 0b110, 3);
        assert!(matches!(
            SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false),
            Err(SpiCodecPlanError::TimingOutOfTolerance {
                edge: TimingEdge::ZeroLow,
                ..
            })
        ));
    }

    #[test]
    fn timing_returns_an_error_for_one_hz_without_overflowing() {
        let plan = SpiEncodingPlan::new(1, 0b111110, 0b100000, 6);
        assert_eq!(
            SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap_err(),
            SpiCodecPlanError::TimingOutOfTolerance {
                edge: TimingEdge::ZeroHigh,
                actual_ns: u32::MAX,
                expected_ns: 400,
                tolerance_ns: 150,
            }
        );
    }

    #[test]
    fn constructors_reject_identical_symbols() {
        let plan = SpiEncodingPlan::new(4_000_000, 0b100, 0b100, 3);
        let expected = SpiCodecPlanError::IdenticalSymbolPatterns { pattern: 0b100 };
        assert_eq!(
            SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err(),
            expected
        );
        assert_eq!(
            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
            expected
        );
    }

    // ── Extra reset_ns ───────────────────────────────────────────────

    #[test]
    fn extra_reset_ns_increases_encoded_len() {
        let plan_normal = SpiEncodingPlan::ws2812_3bit();
        let plan_extra = SpiEncodingPlan::ws2812_3bit().with_extra_reset_ns(100_000);
        let codec_normal = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan_normal, false).unwrap();
        let codec_extra = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan_extra, false).unwrap();
        let pixel_count = 1;
        let len_normal = codec_normal.encoded_len(pixel_count);
        let len_extra = codec_extra.encoded_len(pixel_count);
        assert!(
            len_extra > len_normal,
            "extra reset should increase encoded length"
        );
    }

    // ── Plan validation edge cases ───────────────────────────────────

    #[test]
    fn validate_plan_rejects_zero_bits_per_symbol() {
        let plan = SpiEncodingPlan::new(2_400_000, 0b100, 0b110, 0);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert_eq!(err, SpiCodecPlanError::ZeroBitsPerSymbol);
    }

    #[test]
    fn validate_plan_rejects_bits_per_symbol_too_wide() {
        let plan = SpiEncodingPlan::new(2_400_000, 0b1, 0b1, 9);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert_eq!(
            err,
            SpiCodecPlanError::BitsPerSymbolTooWide { bits_per_symbol: 9 }
        );
    }

    #[test]
    fn validate_plan_rejects_zero_pattern_out_of_range() {
        let plan = SpiEncodingPlan::new(2_400_000, 0b1111, 0b110, 3);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert!(matches!(
            err,
            SpiCodecPlanError::PatternOutOfRange {
                pattern: 0b1111,
                bits_per_symbol: 3,
            }
        ));
    }

    #[test]
    fn validate_plan_rejects_one_pattern_out_of_range() {
        let plan = SpiEncodingPlan::new(2_400_000, 0b100, 0b1111, 3);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert!(matches!(
            err,
            SpiCodecPlanError::PatternOutOfRange {
                pattern: 0b1111,
                bits_per_symbol: 3,
            }
        ));
    }

    #[test]
    fn validate_plan_rejects_non_contiguous_waveform() {
        let plan = SpiEncodingPlan::new(2_400_000, 0b101, 0b110, 3);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert!(matches!(
            err,
            SpiCodecPlanError::InvalidSymbolWaveform {
                pattern: 0b101,
                bits_per_symbol: 3,
            }
        ));
    }

    #[test]
    fn validate_plan_rejects_low_leading_waveform() {
        let plan = SpiEncodingPlan::new(2_400_000, 0b011, 0b110, 3);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert!(matches!(
            err,
            SpiCodecPlanError::InvalidSymbolWaveform {
                pattern: 0b011,
                bits_per_symbol: 3,
            }
        ));
    }

    #[test]
    fn validate_plan_rejects_reset_duration_overflow() {
        // (RESET_NS + extra_reset_ns) × spi_hz ≈ 1.84e19 exceeds the u64
        // fixed-point range, so `reset_bytes` would overflow without this check.
        let plan = SpiEncodingPlan::new(u32::MAX, 0b100, 0b110, 3).with_extra_reset_ns(u32::MAX);
        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
        assert!(matches!(
            err,
            SpiCodecPlanError::ResetDurationOverflow {
                total_reset_ns: 4_295_017_295,
                spi_hz: u32::MAX,
            }
        ));
    }

    #[test]
    fn encode_error_display_internal_consistency() {
        let s = SpiEncodeError::InternalConsistency {
            stage: "append_pattern_push",
            required: 64,
            capacity: 64,
            attempted_len: 65,
        }
        .to_string();
        assert!(s.contains("internal consistency error"), "{s}");
        assert!(s.contains("append_pattern_push"), "{s}");
        assert!(s.contains("attempted_len=65"), "{s}");
    }
}