Skip to main content

led_strip/
spi.rs

1use core::marker::PhantomData;
2
3use embedded_hal::spi::SpiBus;
4use heapless::Vec;
5
6use crate::{
7    LedPixel, LedStripError, LedStripResult, SingleWireProtocol, TransportBackend, WireCodec,
8};
9
10/// SPI clock frequency, bit patterns, and symbol width for encoding a
11/// single-wire LED protocol over an SPI bus.
12///
13/// Each protocol bit is encoded as `bits_per_symbol` SPI bits (typically 3 or 4).
14/// For example, WS2812B uses 3-bit symbols: `0b100` for logical 0, `0b110` for logical 1.
15///
16/// Use the predefined constructors ([`ws2812_3bit`](Self::ws2812_3bit),
17/// [`sk6812_4bit`](Self::sk6812_4bit), [`ws2811_8bit`](Self::ws2811_8bit),
18/// [`ws2816_5bit`](Self::ws2816_5bit)) or build a custom plan with
19/// [`new`](Self::new).
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct SpiEncodingPlan {
22    /// SPI clock frequency in Hz.
23    spi_hz: u32,
24    /// SPI bit pattern for a logical 0 (MSB-first within the symbol window).
25    zero_pattern: u8,
26    /// SPI bit pattern for a logical 1 (MSB-first within the symbol window).
27    one_pattern: u8,
28    /// Number of SPI bits used to encode one protocol bit (e.g. 3 for 0b100/0b110 WS281x).
29    bits_per_symbol: u8,
30    /// Additional reset extension beyond `Proto::RESET_NS`.
31    /// Actual reset = Proto::RESET_NS + extra_reset_ns. Use when the peripheral
32    /// (inverter, level shifter) needs extra settling time.
33    extra_reset_ns: u32,
34}
35
36impl SpiEncodingPlan {
37    /// Creates a new encoding plan. Use [`SpiCodec::for_protocol`] to validate
38    /// that the plan fits a target protocol's timing tolerances.
39    #[must_use]
40    pub const fn new(spi_hz: u32, zero_pattern: u8, one_pattern: u8, bits_per_symbol: u8) -> Self {
41        Self {
42            spi_hz,
43            zero_pattern,
44            one_pattern,
45            bits_per_symbol,
46            extra_reset_ns: 0,
47        }
48    }
49
50    /// 3-bit SPI plan at 2.4 MHz for WS2812 / WS2812B.
51    ///
52    /// Derived timing (spi_bit ~ 416.667 ns, tolerance +/-150 ns per WS2812B datasheet V1):
53    /// - T0H ~ 416.667 ns (expected 400 ns, delta ~ 16.667 ns OK)
54    /// - T0L ~ 833.333 ns (expected 850 ns, delta ~ 16.667 ns OK)
55    /// - T1H ~ 833.333 ns (expected 800 ns, delta ~ 33.333 ns OK)
56    /// - T1L ~ 416.667 ns (expected 450 ns, delta ~ 33.333 ns OK)
57    ///
58    /// TX bytes per pixel: 3 ch × 8 bits × 3 SPI bits / 8 = 9 bytes.
59    #[must_use]
60    pub const fn ws2812_3bit() -> Self {
61        Self::new(2_400_000, 0b100, 0b110, 3)
62    }
63
64    /// 4-bit SPI plan at 3.2 MHz for SK6812.
65    ///
66    /// Derived timing (spi_bit = 312.5 ns, tolerance +/-150 ns per SK6812 datasheet):
67    /// - T0H = 312.5 ns (expected 300 ns, delta = 12.5 ns OK)
68    /// - T0L = 937.5 ns (expected 900 ns, delta = 37.5 ns OK)
69    /// - T1H ~ 625 ns (expected 600 ns, delta = 25 ns OK)
70    /// - T1L ~ 625 ns (expected 600 ns, delta = 25 ns OK)
71    ///
72    /// TX bytes per pixel: 4 ch × 8 bits × 4 SPI bits / 8 = 16 bytes.
73    /// Note: bits_per_symbol = 4; size TX_CAPACITY accordingly (larger than ws2812_3bit).
74    #[must_use]
75    pub const fn sk6812_4bit() -> Self {
76        Self::new(3_200_000, 0b1000, 0b1100, 4)
77    }
78
79    /// 8-bit SPI plan at 3.2 MHz for WS2811 (400 kbps slow mode).
80    ///
81    /// Derived timing (spi_bit = 312.5 ns, tolerance +/-150 ns):
82    /// - T0H = 625 ns (expected 500 ns, delta = 125 ns OK)
83    /// - T0L = 1875 ns (expected 2000 ns, delta = 125 ns OK)
84    /// - T1H = 1250 ns (expected 1200 ns, delta = 50 ns OK)
85    /// - T1L = 1250 ns (expected 1300 ns, delta = 50 ns OK)
86    ///
87    /// TX bytes per pixel: 3 ch × 8 bits × 8 SPI bits / 8 = 24 bytes.
88    #[must_use]
89    pub const fn ws2811_8bit() -> Self {
90        Self::new(3_200_000, 0b1100_0000, 0b1111_0000, 8)
91    }
92
93    /// 5-bit SPI plan at 4 MHz for the 48-bit WS2816B/WS2816C variants.
94    ///
95    /// T0H/T0L are 250/1000 ns and T1H/T1L are 750/500 ns. Each bit lasts
96    /// 1250 ns, satisfying both the per-phase limits and the minimum bit period.
97    /// TX bytes per pixel: 6 wire bytes × 5 = 30 bytes, plus reset.
98    #[must_use]
99    pub const fn ws2816_5bit() -> Self {
100        Self::new(4_000_000, 0b10000, 0b11100, 5)
101    }
102
103    /// Appends extra reset time for external signal conditioning.
104    #[must_use]
105    pub const fn with_extra_reset_ns(mut self, extra_reset_ns: u32) -> Self {
106        self.extra_reset_ns = extra_reset_ns;
107        self
108    }
109
110    #[must_use]
111    pub const fn spi_hz(&self) -> u32 {
112        self.spi_hz
113    }
114
115    #[must_use]
116    pub const fn zero_pattern(&self) -> u8 {
117        self.zero_pattern
118    }
119
120    #[must_use]
121    pub const fn one_pattern(&self) -> u8 {
122        self.one_pattern
123    }
124
125    #[must_use]
126    pub const fn bits_per_symbol(&self) -> u8 {
127        self.bits_per_symbol
128    }
129
130    #[must_use]
131    pub const fn extra_reset_ns(&self) -> u32 {
132        self.extra_reset_ns
133    }
134}
135
136/// Identifies one of the four timing edges in a single-wire protocol bit:
137/// T0H (zero high), T0L (zero low), T1H (one high), T1L (one low).
138///
139/// Used by [`SpiCodecPlanError`] to report which edge failed validation.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum TimingEdge {
143    /// Logical 0, high phase.
144    ZeroHigh,
145    /// Logical 0, low phase.
146    ZeroLow,
147    /// Logical 1, high phase.
148    OneHigh,
149    /// Logical 1, low phase.
150    OneLow,
151}
152
153impl core::fmt::Display for TimingEdge {
154    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
155        let s = match self {
156            Self::ZeroHigh => "T0H",
157            Self::ZeroLow => "T0L",
158            Self::OneHigh => "T1H",
159            Self::OneLow => "T1L",
160        };
161        f.write_str(s)
162    }
163}
164
165/// Errors returned when constructing a [`SpiCodec`] or validating an
166/// [`SpiEncodingPlan`] against a protocol's timing limits and
167/// reset-duration arithmetic.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169#[non_exhaustive]
170pub enum SpiCodecPlanError {
171    ZeroClock,
172    ZeroBitsPerSymbol,
173    BitsPerSymbolTooWide {
174        bits_per_symbol: u8,
175    },
176    PatternOutOfRange {
177        pattern: u8,
178        bits_per_symbol: u8,
179    },
180    InvalidSymbolWaveform {
181        pattern: u8,
182        bits_per_symbol: u8,
183    },
184    /// Logical 0 and 1 must produce different wire symbols.
185    IdenticalSymbolPatterns {
186        pattern: u8,
187    },
188    TimingOutOfTolerance {
189        edge: TimingEdge,
190        /// Rounded duration for diagnostics, saturated at `u32::MAX`.
191        actual_ns: u32,
192        expected_ns: u32,
193        tolerance_ns: u32,
194    },
195    /// A phase violates explicit protocol timing limits.
196    TimingOutOfRange {
197        edge: TimingEdge,
198        /// Rounded duration for diagnostics, saturated at `u32::MAX`.
199        actual_ns: u32,
200        minimum_ns: u32,
201        maximum_ns: u32,
202    },
203    /// The complete high-plus-low symbol is shorter than the protocol permits.
204    BitPeriodTooShort {
205        /// Rounded duration for diagnostics, saturated at `u32::MAX`.
206        actual_ns: u32,
207        minimum_ns: u32,
208    },
209    /// Reset duration × SPI clock exceeds the `u64` fixed-point range used
210    /// to compute reset byte counts.
211    ResetDurationOverflow {
212        /// Total requested reset duration in nanoseconds
213        /// (`Proto::RESET_NS + extra_reset_ns`).
214        total_reset_ns: u64,
215        /// SPI clock frequency in Hz.
216        spi_hz: u32,
217    },
218}
219
220impl core::fmt::Display for SpiCodecPlanError {
221    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
222        match self {
223            Self::ZeroClock => f.write_str("invalid SPI plan: spi_hz must be non-zero"),
224            Self::ZeroBitsPerSymbol => {
225                f.write_str("invalid SPI plan: bits_per_symbol must be non-zero")
226            }
227            Self::BitsPerSymbolTooWide { bits_per_symbol } => write!(
228                f,
229                "invalid SPI plan: bits_per_symbol={bits_per_symbol} exceeds 8"
230            ),
231            Self::PatternOutOfRange {
232                pattern,
233                bits_per_symbol,
234            } => write!(
235                f,
236                "invalid SPI plan: pattern=0x{pattern:02X} out of range for bits_per_symbol={bits_per_symbol}"
237            ),
238            Self::InvalidSymbolWaveform {
239                pattern,
240                bits_per_symbol,
241            } => write!(
242                f,
243                "invalid SPI plan: pattern=0x{pattern:02X} must be contiguous high then contiguous low within bits_per_symbol={bits_per_symbol}"
244            ),
245            Self::IdenticalSymbolPatterns { pattern } => write!(
246                f,
247                "invalid SPI plan: logical 0 and 1 use the same pattern=0x{pattern:02X}"
248            ),
249            Self::TimingOutOfTolerance {
250                edge,
251                actual_ns,
252                expected_ns,
253                tolerance_ns,
254            } => write!(
255                f,
256                "timing out of tolerance: edge={edge} actual={actual_ns}ns expected={expected_ns}ns tolerance=\u{00B1}{tolerance_ns}ns"
257            ),
258            Self::TimingOutOfRange {
259                edge,
260                actual_ns,
261                minimum_ns,
262                maximum_ns,
263            } => write!(
264                f,
265                "timing out of range: edge={edge} actual={actual_ns}ns permitted={minimum_ns}..={maximum_ns}ns"
266            ),
267            Self::BitPeriodTooShort {
268                actual_ns,
269                minimum_ns,
270            } => write!(
271                f,
272                "bit period too short: actual={actual_ns}ns minimum={minimum_ns}ns"
273            ),
274            Self::ResetDurationOverflow {
275                total_reset_ns,
276                spi_hz,
277            } => write!(
278                f,
279                "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"
280            ),
281        }
282    }
283}
284
285impl core::error::Error for SpiCodecPlanError {}
286
287/// Rare encode-time failures.
288///
289/// `SpiCodec::encode` validates required capacity up front. If
290/// `InternalConsistency` appears, `encoded_len` and hot-path writes have
291/// diverged —this indicates a logic bug in the codec.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293#[non_exhaustive]
294pub enum SpiEncodeError {
295    InternalConsistency {
296        stage: &'static str,
297        required: usize,
298        capacity: usize,
299        attempted_len: usize,
300    },
301}
302
303impl core::fmt::Display for SpiEncodeError {
304    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
305        match self {
306            Self::InternalConsistency {
307                stage,
308                required,
309                capacity,
310                attempted_len,
311            } => write!(
312                f,
313                "internal consistency error at {stage}: encoded_len={required}, capacity={capacity}, attempted_len={attempted_len}"
314            ),
315        }
316    }
317}
318
319impl core::error::Error for SpiEncodeError {}
320
321/// SPI-based wire codec that encodes LED pixel data into a byte stream
322/// using configurable bit patterns (bit-banging over SPI MOSI).
323///
324/// Pre-computes inverted/normal patterns and reset fill bytes at construction
325/// time so the hot encoding path is branch-free.
326///
327/// The type parameters `P` and `Proto` tie the codec to a specific
328/// `<pixel, protocol>` pair at compile time —a codec built via
329/// [`SpiCodec::<Rgb, Ws2812B>::for_protocol`](Self::for_protocol) cannot
330/// be used with a [`LedStrip`](crate::LedStrip) parameterized on a different
331/// protocol, even if both happen to implement the same [`WireCodec`](crate::WireCodec) trait.
332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333pub struct SpiCodec<P, Proto>
334where
335    P: LedPixel,
336    Proto: SingleWireProtocol<P>,
337{
338    plan: SpiEncodingPlan,
339    /// Zero-bit pattern, pre-inverted if `invert_output` was set at construction.
340    zero_pattern: u8,
341    /// One-bit pattern, pre-inverted if `invert_output` was set at construction.
342    one_pattern: u8,
343    /// Reset fill byte: 0x00 for normal, 0xFF for inverted output.
344    reset_fill: u8,
345    _marker: PhantomData<(P, Proto)>,
346}
347
348impl<P, Proto> SpiCodec<P, Proto>
349where
350    P: LedPixel,
351    Proto: SingleWireProtocol<P>,
352{
353    /// Constructs a codec from a plan. Validates the plan's structural
354    /// parameters (clock, symbol width, pattern range) and rejects reset
355    /// durations whose fixed-point arithmetic would overflow, but does
356    /// **not** check protocol timing. Use [`for_protocol`](Self::for_protocol)
357    /// if timing validation is desired.
358    /// Each symbol must be a distinct, contiguous high-then-low waveform.
359    #[must_use = "SPI codec construction validates the plan; ignoring the result would silently drop errors"]
360    pub fn new(plan: SpiEncodingPlan, invert_output: bool) -> Result<Self, SpiCodecPlanError> {
361        validate_plan(plan)?;
362        validate_reset_duration::<P, Proto>(&plan)?;
363        Ok(Self::from_plan(plan, invert_output))
364    }
365
366    /// Constructs a codec with structural, protocol timing limits, and
367    /// reset-duration overflow validation.
368    ///
369    /// Preferred over [`Self::new`] when the target protocol is known at construction time.
370    /// Checks all four phases against `Proto::ZERO_MIN`/`ZERO_MAX` and
371    /// `Proto::ONE_MIN`/`ONE_MAX`, plus `Proto::MIN_BIT_PERIOD_NS`, without
372    /// rounding the durations. Error durations are rounded only for diagnostics.
373    #[must_use = "returns Err on timing violations; use new() to skip timing validation"]
374    pub fn for_protocol(
375        plan: SpiEncodingPlan,
376        invert_output: bool,
377    ) -> Result<Self, SpiCodecPlanError> {
378        validate_plan(plan)?;
379        validate_timing::<P, Proto>(&plan)?;
380        validate_reset_duration::<P, Proto>(&plan)?;
381        Ok(Self::from_plan(plan, invert_output))
382    }
383
384    /// Pre-computes inverted/normal patterns and reset fill based on `invert_output`.
385    ///
386    /// When `invert_output` is true, each pattern bit is flipped within the
387    /// `bits_per_symbol`-wide mask window (e.g. 0b100 —0b011 for 3-bit SPI).
388    const fn from_plan(plan: SpiEncodingPlan, invert_output: bool) -> Self {
389        if invert_output {
390            let mask = pattern_mask(plan.bits_per_symbol());
391            Self {
392                zero_pattern: (!plan.zero_pattern()) & mask,
393                one_pattern: (!plan.one_pattern()) & mask,
394                reset_fill: u8::MAX,
395                plan,
396                _marker: PhantomData,
397            }
398        } else {
399            Self {
400                zero_pattern: plan.zero_pattern(),
401                one_pattern: plan.one_pattern(),
402                reset_fill: 0,
403                plan,
404                _marker: PhantomData,
405            }
406        }
407    }
408
409    #[must_use]
410    pub const fn plan(&self) -> SpiEncodingPlan {
411        self.plan
412    }
413
414    /// Computes how many SPI bytes of `reset_fill` are needed to satisfy
415    /// `Proto::RESET_NS + extra_reset_ns` at the current SPI clock rate.
416    ///
417    /// Uses ceiling division: `ceil(ns * spi_hz / 1e9)`.
418    ///
419    /// Overflow is impossible here: `validate_reset_duration` rejects at
420    /// construction time any plan whose fixed-point intermediate would
421    /// exceed `u64::MAX`, so plain arithmetic is safe.
422    fn reset_bytes(&self) -> usize
423    where
424        P: LedPixel,
425        Proto: SingleWireProtocol<P>,
426    {
427        let total_reset_ns = u64::from(Proto::RESET_NS) + u64::from(self.plan.extra_reset_ns);
428
429        // Fixed-point arithmetic: reset_ns × spi_hz gives scaled clock cycles
430        // (in units of 10^9); dividing by 8 × 10^9 converts to SPI bytes in
431        // one step (cycles → seconds → bytes). See `validate_reset_duration`
432        // for the overflow guarantee covering the multiplication.
433        let scaled_cycles = total_reset_ns * u64::from(self.plan.spi_hz);
434
435        let total_bytes = scaled_cycles.div_ceil(8_000_000_000_u64);
436
437        usize::try_from(total_bytes).unwrap_or(usize::MAX)
438    }
439}
440
441impl<P, Proto> WireCodec<P, Proto, u8> for SpiCodec<P, Proto>
442where
443    P: LedPixel,
444    Proto: SingleWireProtocol<P>,
445{
446    type EncodeError = SpiEncodeError;
447
448    fn encoded_len(&self, pixel_count: usize) -> usize {
449        // Saturating arithmetic: overflow (requiring billions of pixels)
450        // saturates to a value that still fails the capacity check in `encode`,
451        // so no explicit early-return branches are needed.
452        let frame_bytes = pixel_count.saturating_mul(P::BYTES_PER_PIXEL);
453        let payload_bits = frame_bytes
454            .saturating_mul(8)
455            .saturating_mul(usize::from(self.plan.bits_per_symbol));
456        let payload_bytes = payload_bits.saturating_add(7) / 8;
457        let total = payload_bytes.saturating_add(self.reset_bytes());
458
459        debug_assert!(
460            total < usize::MAX / 2,
461            "encoded_len overflowed: frame too large for usize"
462        );
463
464        total
465    }
466
467    fn encode<const TX_CAPACITY: usize>(
468        &self,
469        color_order: P::Order,
470        pixels: &[P],
471        out: &mut Vec<u8, TX_CAPACITY>,
472    ) -> LedStripResult<(), Self::EncodeError> {
473        let required = self.encoded_len(pixels.len());
474        if required > TX_CAPACITY {
475            return Err(LedStripError::BufferTooSmall {
476                required,
477                capacity: TX_CAPACITY,
478            });
479        }
480
481        out.clear();
482
483        let mut current_byte = 0_u8;
484        let mut used_bits = 0_u8;
485        let mut raw = [0_u8; 6];
486        for pixel in pixels.iter().copied() {
487            pixel.encode(color_order, &mut raw[..P::BYTES_PER_PIXEL]);
488
489            for byte in &raw[..P::BYTES_PER_PIXEL] {
490                for bit_index in 0..8 {
491                    let shift = bit_shift(bit_index);
492                    let bit_is_set = ((*byte >> shift) & 1) != 0;
493                    let pattern = if bit_is_set {
494                        self.one_pattern
495                    } else {
496                        self.zero_pattern
497                    };
498
499                    append_pattern::<TX_CAPACITY>(
500                        out,
501                        pattern,
502                        self.plan.bits_per_symbol(),
503                        required,
504                        &mut current_byte,
505                        &mut used_bits,
506                    )?;
507                }
508            }
509        }
510
511        // Invariant: the total encoded bit count is always a multiple of 8
512        // (BYTES_PER_PIXEL × 8 × bits_per_symbol × pixel_count), so `used_bits`
513        // is always 0 here. Any other value indicates a codec logic bug.
514        debug_assert_eq!(used_bits, 0, "total encoded bits must be a multiple of 8");
515
516        let reset_bytes = self.reset_bytes();
517        let target_len = out.len().saturating_add(reset_bytes);
518        out.resize(target_len, self.reset_fill).map_err(|_| {
519            LedStripError::Operation(SpiEncodeError::InternalConsistency {
520                stage: "reset_tail_resize",
521                required,
522                capacity: TX_CAPACITY,
523                attempted_len: target_len,
524            })
525        })?;
526
527        Ok(())
528    }
529}
530
531/// SPI transport backend.
532///
533/// Wraps an [`embedded_hal::spi::SpiBus`] implementor. The codec handles all
534/// protocol-level concerns (timing, bit patterns, reset); this backend only
535/// pushes the resulting byte stream over MOSI.
536#[derive(Debug)]
537pub struct SpiBackend<SPI> {
538    spi: SPI,
539}
540
541impl<SPI> SpiBackend<SPI> {
542    /// Wraps an SPI peripheral.
543    #[must_use]
544    pub const fn new(spi: SPI) -> Self {
545        Self { spi }
546    }
547
548    /// Consumes the backend, returning the underlying SPI peripheral.
549    #[must_use]
550    pub fn into_inner(self) -> SPI {
551        self.spi
552    }
553
554    /// Returns a shared reference to the SPI peripheral.
555    #[must_use]
556    pub fn inner(&self) -> &SPI {
557        &self.spi
558    }
559
560    /// Returns a mutable reference to the SPI peripheral.
561    #[must_use]
562    pub fn inner_mut(&mut self) -> &mut SPI {
563        &mut self.spi
564    }
565}
566
567impl<SPI> TransportBackend for SpiBackend<SPI>
568where
569    SPI: SpiBus<u8>,
570{
571    type Word = u8;
572    type Error = SPI::Error;
573
574    fn transmit(&mut self, words: &[Self::Word]) -> Result<(), Self::Error> {
575        self.spi.write(words)?;
576        self.spi.flush()
577    }
578}
579
580/// Returns the bitmask covering `bits_per_symbol` low bits.
581///
582/// For `bits_per_symbol == 8` this is `0xFF`; otherwise `(1 << n) - 1`.
583const fn pattern_mask(bits_per_symbol: u8) -> u8 {
584    if bits_per_symbol == 8 {
585        u8::MAX
586    } else {
587        (1_u8 << bits_per_symbol) - 1
588    }
589}
590
591fn validate_plan(plan: SpiEncodingPlan) -> Result<(), SpiCodecPlanError> {
592    if plan.spi_hz == 0 {
593        return Err(SpiCodecPlanError::ZeroClock);
594    }
595
596    if plan.bits_per_symbol == 0 {
597        return Err(SpiCodecPlanError::ZeroBitsPerSymbol);
598    }
599
600    if plan.bits_per_symbol > 8 {
601        return Err(SpiCodecPlanError::BitsPerSymbolTooWide {
602            bits_per_symbol: plan.bits_per_symbol,
603        });
604    }
605
606    let limit = pattern_mask(plan.bits_per_symbol);
607
608    if plan.zero_pattern > limit {
609        return Err(SpiCodecPlanError::PatternOutOfRange {
610            pattern: plan.zero_pattern,
611            bits_per_symbol: plan.bits_per_symbol,
612        });
613    }
614
615    if plan.one_pattern > limit {
616        return Err(SpiCodecPlanError::PatternOutOfRange {
617            pattern: plan.one_pattern,
618            bits_per_symbol: plan.bits_per_symbol,
619        });
620    }
621
622    simulate_symbol_phases(plan.zero_pattern, plan.bits_per_symbol)?;
623    simulate_symbol_phases(plan.one_pattern, plan.bits_per_symbol)?;
624
625    if plan.zero_pattern == plan.one_pattern {
626        return Err(SpiCodecPlanError::IdenticalSymbolPatterns {
627            pattern: plan.zero_pattern,
628        });
629    }
630
631    Ok(())
632}
633
634/// Rejects plans whose reset-duration fixed-point arithmetic would overflow
635/// `u64` in [`SpiCodec::reset_bytes`](crate::SpiCodec).
636///
637/// Must be called after `validate_plan`, which guarantees `spi_hz != 0`.
638/// With this guarantee, `reset_bytes` can use plain arithmetic.
639fn validate_reset_duration<P, Proto>(plan: &SpiEncodingPlan) -> Result<(), SpiCodecPlanError>
640where
641    P: LedPixel,
642    Proto: SingleWireProtocol<P>,
643{
644    // RESET_NS and extra_reset_ns are both u32, so the sum cannot overflow u64.
645    let total_reset_ns = u64::from(Proto::RESET_NS) + u64::from(plan.extra_reset_ns);
646
647    // `div_ceil` in `reset_bytes` has no additive intermediate, so the
648    // multiplication is the only step that can overflow.
649    if total_reset_ns > u64::MAX / u64::from(plan.spi_hz) {
650        return Err(SpiCodecPlanError::ResetDurationOverflow {
651            total_reset_ns,
652            spi_hz: plan.spi_hz,
653        });
654    }
655
656    Ok(())
657}
658
659/// Returns the bit position within a pixel byte for the given logical bit index.
660/// All supported protocols transmit the most significant bit first, so
661/// bit 0 -> position 7, bit 1 -> position 6, and so on.
662#[inline]
663fn bit_shift(bit_index: u8) -> u8 {
664    7 - bit_index
665}
666
667/// Stream-oriented SPI bit-packing kernel.
668///
669/// Appends `bits_per_symbol` bits of `pattern` (MSB-first within the pattern)
670/// into the SPI output buffer. Bits are accumulated into `current_byte` from
671/// MSB to LSB; when the byte is full it is pushed and a new byte starts.
672///
673/// The pattern should already be inverted if the output line uses an external
674/// inverter (pre-computed by `SpiCodec::from_plan`).
675///
676/// This is the hot path during `refresh`. The capacity check was already
677/// performed at the top of `encode()`, so push failures here indicate a
678/// logic error in `encoded_len` —the error path is cold but provides a
679/// safe panic-free fallback instead of UB.
680#[inline]
681fn append_pattern<const TX_CAPACITY: usize>(
682    out: &mut Vec<u8, TX_CAPACITY>,
683    pattern: u8,
684    bits_per_symbol: u8,
685    required: usize,
686    current_byte: &mut u8,
687    used_bits: &mut u8,
688) -> LedStripResult<(), SpiEncodeError> {
689    for shift in (0..bits_per_symbol).rev() {
690        let bit = ((pattern >> shift) & 1) != 0;
691
692        if bit {
693            *current_byte |= 1_u8 << (7 - *used_bits);
694        }
695
696        *used_bits += 1;
697        if *used_bits == 8 {
698            out.push(*current_byte).map_err(|_| {
699                LedStripError::Operation(SpiEncodeError::InternalConsistency {
700                    stage: "append_pattern_push",
701                    required,
702                    capacity: TX_CAPACITY,
703                    attempted_len: out.len().saturating_add(1),
704                })
705            })?;
706
707            *current_byte = 0;
708            *used_bits = 0;
709        }
710    }
711    Ok(())
712}
713
714/// Simulates a symbol bit-by-bit and returns `(high_bits, low_bits)`.
715///
716/// Valid symbols are contiguous high followed by contiguous low with at least
717/// one bit in each phase.
718fn simulate_symbol_phases(pattern: u8, bits_per_symbol: u8) -> Result<(u8, u8), SpiCodecPlanError> {
719    let mut high_bits = 0_u8;
720    let mut low_bits = 0_u8;
721    let mut in_low_phase = false;
722
723    for shift in (0..bits_per_symbol).rev() {
724        let bit_is_high = ((pattern >> shift) & 1) != 0;
725
726        if !in_low_phase {
727            if bit_is_high {
728                high_bits += 1;
729            } else if high_bits == 0 {
730                return Err(SpiCodecPlanError::InvalidSymbolWaveform {
731                    pattern,
732                    bits_per_symbol,
733                });
734            } else {
735                in_low_phase = true;
736                low_bits = 1;
737            }
738        } else if bit_is_high {
739            return Err(SpiCodecPlanError::InvalidSymbolWaveform {
740                pattern,
741                bits_per_symbol,
742            });
743        } else {
744            low_bits += 1;
745        }
746    }
747
748    if high_bits == 0 || low_bits == 0 {
749        return Err(SpiCodecPlanError::InvalidSymbolWaveform {
750            pattern,
751            bits_per_symbol,
752        });
753    }
754
755    Ok((high_bits, low_bits))
756}
757
758/// Checks exact phase durations against inclusive protocol bounds.
759/// Cross multiplication avoids rounding an SPI cycle before scaling a phase.
760fn validate_timing<P, Proto>(plan: &SpiEncodingPlan) -> Result<(), SpiCodecPlanError>
761where
762    P: LedPixel,
763    Proto: SingleWireProtocol<P>,
764{
765    let tolerance = Proto::TIMING_TOLERANCE_NS;
766
767    let (zero_high, zero_low) = simulate_symbol_phases(plan.zero_pattern, plan.bits_per_symbol)?;
768    let (one_high, one_low) = simulate_symbol_phases(plan.one_pattern, plan.bits_per_symbol)?;
769
770    check_timing(
771        zero_high,
772        plan.spi_hz,
773        Proto::ZERO.high_ns,
774        Proto::ZERO_MIN.high_ns,
775        Proto::ZERO_MAX.high_ns,
776        tolerance,
777        TimingEdge::ZeroHigh,
778    )?;
779    check_timing(
780        zero_low,
781        plan.spi_hz,
782        Proto::ZERO.low_ns,
783        Proto::ZERO_MIN.low_ns,
784        Proto::ZERO_MAX.low_ns,
785        tolerance,
786        TimingEdge::ZeroLow,
787    )?;
788    check_timing(
789        one_high,
790        plan.spi_hz,
791        Proto::ONE.high_ns,
792        Proto::ONE_MIN.high_ns,
793        Proto::ONE_MAX.high_ns,
794        tolerance,
795        TimingEdge::OneHigh,
796    )?;
797    check_timing(
798        one_low,
799        plan.spi_hz,
800        Proto::ONE.low_ns,
801        Proto::ONE_MIN.low_ns,
802        Proto::ONE_MAX.low_ns,
803        tolerance,
804        TimingEdge::OneLow,
805    )?;
806
807    // Both symbols have the same width, so their total bit periods are equal.
808    if u64::from(plan.bits_per_symbol) * 1_000_000_000
809        < u64::from(Proto::MIN_BIT_PERIOD_NS) * u64::from(plan.spi_hz)
810    {
811        return Err(SpiCodecPlanError::BitPeriodTooShort {
812            actual_ns: rounded_duration_ns(plan.bits_per_symbol, plan.spi_hz),
813            minimum_ns: Proto::MIN_BIT_PERIOD_NS,
814        });
815    }
816
817    Ok(())
818}
819
820fn check_timing(
821    phase_bits: u8,
822    spi_hz: u32,
823    expected_ns: u32,
824    minimum_ns: u32,
825    maximum_ns: u32,
826    tolerance_ns: u32,
827    edge: TimingEdge,
828) -> Result<(), SpiCodecPlanError> {
829    // A u32 nanosecond bound multiplied by a u32 frequency always fits u64.
830    // Validated phase widths are at most 7 bits, even for a 1 Hz SPI clock.
831    let scaled_duration = u64::from(phase_bits) * 1_000_000_000;
832    if scaled_duration < u64::from(minimum_ns) * u64::from(spi_hz)
833        || scaled_duration > u64::from(maximum_ns) * u64::from(spi_hz)
834    {
835        let actual_ns = rounded_duration_ns(phase_bits, spi_hz);
836        // Keep the existing error variant for protocols using the legacy
837        // symmetric tolerance, while reporting explicit limits accurately.
838        if minimum_ns == expected_ns.saturating_sub(tolerance_ns)
839            && maximum_ns == expected_ns.saturating_add(tolerance_ns)
840        {
841            return Err(SpiCodecPlanError::TimingOutOfTolerance {
842                edge,
843                actual_ns,
844                expected_ns,
845                tolerance_ns,
846            });
847        }
848        return Err(SpiCodecPlanError::TimingOutOfRange {
849            edge,
850            actual_ns,
851            minimum_ns,
852            maximum_ns,
853        });
854    }
855    Ok(())
856}
857
858/// Rounds the whole phase for diagnostics only. Validation uses exact ratios.
859fn rounded_duration_ns(bits: u8, spi_hz: u32) -> u32 {
860    let scaled_duration = u64::from(bits) * 1_000_000_000;
861    let actual_ns = (scaled_duration + u64::from(spi_hz) / 2) / u64::from(spi_hz);
862    u32::try_from(actual_ns).unwrap_or(u32::MAX)
863}
864
865#[cfg(test)]
866mod tests {
867    use crate::{
868        Rgb, Rgb16, Rgbw, Sk6812, SpiBackend, TransportBackend, WireCodec, Ws2811, Ws2812B,
869    };
870
871    use super::{SpiCodec, SpiCodecPlanError, SpiEncodeError, SpiEncodingPlan, TimingEdge};
872
873    #[test]
874    fn ws2812_3bit_passes_ws2812b_timing() {
875        SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
876    }
877
878    #[test]
879    fn sk6812_4bit_passes_sk6812_timing() {
880        SpiCodec::<Rgbw, Sk6812>::for_protocol(SpiEncodingPlan::sk6812_4bit(), false).unwrap();
881    }
882
883    #[test]
884    fn ws2812_3bit_rejects_sk6812_timing() {
885        // T1H: actual —832 ns, expected = 600 ns, Δ = 232 ns > 150 ns tolerance.
886        let err = SpiCodec::<Rgbw, Sk6812>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false)
887            .unwrap_err();
888        assert!(matches!(
889            err,
890            SpiCodecPlanError::TimingOutOfTolerance {
891                edge: TimingEdge::OneHigh,
892                ..
893            }
894        ));
895    }
896
897    #[test]
898    fn out_of_tolerance_plan_reports_first_failing_edge() {
899        // 1 MHz 3-bit: spi_bit = 1000 ns, T0H = 1000 ns vs WS2812B T0H = 400 ns, Δ = 600 ns.
900        let plan = SpiEncodingPlan::new(1_000_000, 0b100, 0b110, 3);
901        let err = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap_err();
902        assert_eq!(
903            err,
904            SpiCodecPlanError::TimingOutOfTolerance {
905                edge: TimingEdge::ZeroHigh,
906                actual_ns: 1000,
907                expected_ns: 400,
908                tolerance_ns: 150,
909            }
910        );
911    }
912
913    #[test]
914    fn timing_edge_display_uses_protocol_labels() {
915        assert_eq!(TimingEdge::ZeroHigh.to_string(), "T0H");
916        assert_eq!(TimingEdge::ZeroLow.to_string(), "T0L");
917        assert_eq!(TimingEdge::OneHigh.to_string(), "T1H");
918        assert_eq!(TimingEdge::OneLow.to_string(), "T1L");
919    }
920
921    #[test]
922    fn plan_error_display_zero_clock() {
923        let s = SpiCodecPlanError::ZeroClock.to_string();
924        assert!(s.contains("spi_hz"), "{s}");
925    }
926
927    #[test]
928    fn plan_error_display_zero_bits_per_symbol() {
929        let s = SpiCodecPlanError::ZeroBitsPerSymbol.to_string();
930        assert!(s.contains("bits_per_symbol"), "{s}");
931    }
932
933    #[test]
934    fn plan_error_display_bits_per_symbol_too_wide() {
935        let s = SpiCodecPlanError::BitsPerSymbolTooWide { bits_per_symbol: 9 }.to_string();
936        assert!(s.contains("bits_per_symbol=9"), "{s}");
937    }
938
939    #[test]
940    fn plan_error_display_pattern_out_of_range() {
941        let s = SpiCodecPlanError::PatternOutOfRange {
942            pattern: 0xFF,
943            bits_per_symbol: 3,
944        }
945        .to_string();
946        assert!(s.contains("0xFF"), "{s}");
947        assert!(s.contains("bits_per_symbol=3"), "{s}");
948    }
949
950    #[test]
951    fn plan_error_display_invalid_symbol_waveform() {
952        let s = SpiCodecPlanError::InvalidSymbolWaveform {
953            pattern: 0b101,
954            bits_per_symbol: 3,
955        }
956        .to_string();
957        assert!(s.contains("0x05"), "{s}");
958        assert!(s.contains("contiguous high then contiguous low"), "{s}");
959    }
960
961    #[test]
962    fn plan_error_display_timing_out_of_tolerance_includes_all_fields() {
963        let s = SpiCodecPlanError::TimingOutOfTolerance {
964            edge: TimingEdge::OneHigh,
965            actual_ns: 832,
966            expected_ns: 600,
967            tolerance_ns: 150,
968        }
969        .to_string();
970        assert!(s.contains("T1H"), "{s}");
971        assert!(s.contains("832"), "{s}");
972        assert!(s.contains("600"), "{s}");
973        assert!(s.contains("150"), "{s}");
974    }
975
976    #[test]
977    fn plan_error_display_reset_duration_overflow() {
978        let s = SpiCodecPlanError::ResetDurationOverflow {
979            total_reset_ns: 4_295_017_295,
980            spi_hz: u32::MAX,
981        }
982        .to_string();
983        assert!(s.contains("reset duration overflow"), "{s}");
984        assert!(s.contains("4295017295"), "{s}");
985        assert!(s.contains("4294967295"), "{s}");
986    }
987
988    #[test]
989    fn plan_error_is_core_error() {
990        let _: &dyn core::error::Error = &SpiCodecPlanError::ZeroClock;
991    }
992
993    // ── Encode end-to-end tests ──────────────────────────────────────
994
995    use crate::{LedStripError, RgbOrder};
996    use heapless::Vec as HVec;
997
998    #[test]
999    fn encode_produces_nonempty_buffer() {
1000        let codec =
1001            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
1002        let pixels = [Rgb::new(0, 255, 0)];
1003        let mut out: HVec<u8, 64> = HVec::new();
1004
1005        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();
1006
1007        assert!(!out.is_empty(), "encoded output should not be empty");
1008        // ws2812_3bit: 3 ch × 8 bits × 3 spi_bits / 8 = 9 payload bytes + reset
1009        assert!(out.len() >= 9, "expected >=9 bytes, got {}", out.len());
1010    }
1011
1012    #[test]
1013    fn encode_output_len_matches_encoded_len() {
1014        let codec =
1015            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
1016        let pixel_count = 3;
1017        let pixels = [
1018            Rgb::new(255, 0, 0),
1019            Rgb::new(0, 255, 0),
1020            Rgb::new(0, 0, 255),
1021        ];
1022        let mut out: HVec<u8, 256> = HVec::new();
1023
1024        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();
1025
1026        assert_eq!(
1027            out.len(),
1028            codec.encoded_len(pixel_count),
1029            "output len must match encoded_len prediction"
1030        );
1031    }
1032
1033    #[test]
1034    fn encode_rejects_buffer_too_small() {
1035        let codec =
1036            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
1037        let pixels = [Rgb::new(0, 0, 0), Rgb::new(0, 0, 0)];
1038        // 2 pixels * 9 bytes = 18 + reset_bytes —need > 30, give only 5
1039        let mut out: HVec<u8, 5> = HVec::new();
1040
1041        let err = codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap_err();
1042        assert!(matches!(err, LedStripError::BufferTooSmall { .. }));
1043    }
1044
1045    // ── invert_output tests ──────────────────────────────────────────
1046
1047    #[test]
1048    fn inverted_codec_precomputes_patterns_correctly() {
1049        let plan = SpiEncodingPlan::ws2812_3bit(); // 0b100, 0b110, 3 bits/symbol
1050        let codec = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, true).unwrap();
1051
1052        // In 3-bit window (mask=0b111): !0b100 = 0b011, !0b110 = 0b001
1053        assert_eq!(codec.zero_pattern, 0b011);
1054        assert_eq!(codec.one_pattern, 0b001);
1055        assert_eq!(codec.reset_fill, 0xFF);
1056    }
1057
1058    #[test]
1059    fn invert_output_produces_different_data_and_reset() {
1060        let plan = SpiEncodingPlan::ws2812_3bit();
1061        let codec_normal = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap();
1062        let codec_inverted = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, true).unwrap();
1063        let pixels = [Rgb::new(255, 0, 0)];
1064        let mut out_normal: HVec<u8, 128> = HVec::new();
1065        let mut out_inverted: HVec<u8, 128> = HVec::new();
1066
1067        codec_normal
1068            .encode(RgbOrder::Grb, &pixels, &mut out_normal)
1069            .unwrap();
1070        codec_inverted
1071            .encode(RgbOrder::Grb, &pixels, &mut out_inverted)
1072            .unwrap();
1073
1074        // Same length
1075        assert_eq!(out_normal.len(), out_inverted.len());
1076        // Different content (inverted data bits)
1077        assert_ne!(out_normal, out_inverted);
1078        // Reset fill bytes differ
1079        let last_normal = *out_normal.last().unwrap();
1080        let last_inverted = *out_inverted.last().unwrap();
1081        assert_eq!(last_normal, 0x00, "normal reset fill should be 0x00");
1082        assert_eq!(last_inverted, 0xFF, "inverted reset fill should be 0xFF");
1083    }
1084
1085    // ── Golden output tests ─────────────────────────────────────────
1086
1087    #[test]
1088    fn black_pixel_produces_all_zero_patterns() {
1089        // One BLACK pixel (Rgb=0,0,0) with ws2812_3bit: every payload byte
1090        // is 0x92, 0x49, 0x24 (3 bytes per channel, GRB order, repeated).
1091        let codec =
1092            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
1093        let pixels = [Rgb::BLACK];
1094        let mut out: HVec<u8, 128> = HVec::new();
1095        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();
1096
1097        let payload_bytes = out.len() - codec.reset_bytes();
1098        // 3 channels * 3 bytes/channel = 9 payload bytes
1099        assert_eq!(payload_bytes, 9);
1100        let expected_cycle: [u8; 3] = [0x92, 0x49, 0x24];
1101        for (i, &b) in out[..payload_bytes].iter().enumerate() {
1102            assert_eq!(
1103                b,
1104                expected_cycle[i % 3],
1105                "black pixel byte {i}: expected 0x{:02X}, got 0x{b:02X}",
1106                expected_cycle[i % 3]
1107            );
1108        }
1109    }
1110
1111    #[test]
1112    fn white_pixel_produces_all_one_patterns() {
1113        let codec =
1114            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
1115        let pixels = [Rgb::WHITE];
1116        let mut out: HVec<u8, 128> = HVec::new();
1117        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();
1118
1119        let payload_bytes = out.len() - codec.reset_bytes();
1120        assert_eq!(payload_bytes, 9);
1121        let expected_cycle: [u8; 3] = [0xDB, 0x6D, 0xB6];
1122        for (i, &b) in out[..payload_bytes].iter().enumerate() {
1123            assert_eq!(
1124                b,
1125                expected_cycle[i % 3],
1126                "white pixel byte {i}: expected 0x{:02X}, got 0x{b:02X}",
1127                expected_cycle[i % 3]
1128            );
1129        }
1130    }
1131
1132    #[test]
1133    fn green_pixel_produces_mixed_patterns_grb() {
1134        // Rgb(0,255,0) in GRB order: G=255 (ones), R=0 (zeros), B=0 (zeros)
1135        let codec =
1136            SpiCodec::<Rgb, Ws2812B>::for_protocol(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
1137        let pixels = [Rgb::new(0, 255, 0)];
1138        let mut out: HVec<u8, 128> = HVec::new();
1139        codec.encode(RgbOrder::Grb, &pixels, &mut out).unwrap();
1140
1141        let payload_bytes = out.len() - codec.reset_bytes();
1142        assert_eq!(payload_bytes, 9);
1143        // Channel 1 (G): ones pattern
1144        let ones: [u8; 3] = [0xDB, 0x6D, 0xB6];
1145        // Channel 2 (R): zeros pattern
1146        let zeros: [u8; 3] = [0x92, 0x49, 0x24];
1147        // Channel 3 (B): zeros pattern
1148        assert_eq!(&out[0..3], &ones, "G channel (first) should be all-ones");
1149        assert_eq!(&out[3..6], &zeros, "R channel (second) should be all-zeros");
1150        assert_eq!(&out[6..9], &zeros, "B channel (third) should be all-zeros");
1151    }
1152
1153    // ── Timing validation boundary tests ─────────────────────────────
1154
1155    #[test]
1156    fn validate_timing_reports_first_failing_edge() {
1157        // 4 MHz 3-bit: spi_bit=250 ns
1158        // T0H=250 ns (Δ=150, at tolerance —, T0L=500 ns (Δ=350, >150 —
1159        let plan = SpiEncodingPlan::new(4_000_000, 0b100, 0b110, 3);
1160        let err = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap_err();
1161        assert!(matches!(
1162            err,
1163            SpiCodecPlanError::TimingOutOfTolerance {
1164                edge: TimingEdge::ZeroLow,
1165                ..
1166            }
1167        ));
1168    }
1169
1170    #[test]
1171    fn timing_exactly_at_tolerance_boundary_passes() {
1172        // T0H=400, T0L=1000, T1H=800, T1L=600 ns.
1173        // Both low phases are exactly at their +150 ns tolerance boundary.
1174        let plan = SpiEncodingPlan::new(5_000_000, 0b1100000, 0b1111000, 7);
1175        SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap();
1176    }
1177
1178    // ── SpiEncodingPlan getters / extra_reset ───────────────────────
1179
1180    #[test]
1181    fn plan_getters_return_construction_values() {
1182        let plan = SpiEncodingPlan::new(3_000_000, 0b1010, 0b1110, 4);
1183        assert_eq!(plan.spi_hz(), 3_000_000);
1184        assert_eq!(plan.zero_pattern(), 0b1010);
1185        assert_eq!(plan.one_pattern(), 0b1110);
1186        assert_eq!(plan.bits_per_symbol(), 4);
1187        assert_eq!(plan.extra_reset_ns(), 0);
1188    }
1189
1190    #[test]
1191    fn plan_with_extra_reset_ns_stores_value() {
1192        let plan = SpiEncodingPlan::ws2812_3bit().with_extra_reset_ns(10_000);
1193        assert_eq!(plan.extra_reset_ns(), 10_000);
1194    }
1195
1196    // ── SpiCodec::new (no timing, structural only) ──────────────────
1197
1198    #[test]
1199    fn spi_codec_new_with_valid_plan_succeeds() {
1200        SpiCodec::<Rgb, Ws2812B>::new(SpiEncodingPlan::ws2812_3bit(), false).unwrap();
1201    }
1202
1203    #[test]
1204    fn spi_codec_new_with_inverted_output_succeeds() {
1205        SpiCodec::<Rgb, Ws2812B>::new(SpiEncodingPlan::ws2812_3bit(), true).unwrap();
1206    }
1207
1208    #[test]
1209    fn spi_codec_new_rejects_zero_clock() {
1210        let plan = SpiEncodingPlan::new(0, 0b100, 0b110, 3);
1211        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1212        assert_eq!(err, SpiCodecPlanError::ZeroClock);
1213    }
1214
1215    #[test]
1216    fn spi_codec_plan_accessor_returns_original_plan() {
1217        let plan = SpiEncodingPlan::ws2812_3bit();
1218        let codec = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap();
1219        assert_eq!(codec.plan(), plan);
1220    }
1221
1222    // ── SpiBackend ───────────────────────────────────────────────────
1223
1224    #[test]
1225    fn spi_backend_new() {
1226        let backend = SpiBackend::new(42_u32);
1227        assert_eq!(*backend.inner(), 42);
1228    }
1229
1230    #[test]
1231    fn spi_backend_into_inner() {
1232        let backend = SpiBackend::new("hello");
1233        assert_eq!(backend.into_inner(), "hello");
1234    }
1235
1236    #[test]
1237    fn spi_backend_inner_mut_modifies_value() {
1238        let mut backend = SpiBackend::new(10_u32);
1239        *backend.inner_mut() = 99;
1240        assert_eq!(*backend.inner(), 99);
1241    }
1242
1243    // ── Mock SPI transmit ────────────────────────────────────────────
1244
1245    use core::cell::Cell;
1246    use embedded_hal::spi::SpiBus;
1247
1248    #[derive(Debug, Default)]
1249    struct MockSpi(Cell<usize>);
1250
1251    impl embedded_hal::spi::ErrorType for MockSpi {
1252        type Error = core::convert::Infallible;
1253    }
1254
1255    impl SpiBus<u8> for MockSpi {
1256        fn read(&mut self, _words: &mut [u8]) -> Result<(), Self::Error> {
1257            Ok(())
1258        }
1259        fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
1260            self.0.set(words.len());
1261            Ok(())
1262        }
1263        fn transfer(&mut self, _read: &mut [u8], _write: &[u8]) -> Result<(), Self::Error> {
1264            Ok(())
1265        }
1266        fn transfer_in_place(&mut self, _words: &mut [u8]) -> Result<(), Self::Error> {
1267            Ok(())
1268        }
1269        fn flush(&mut self) -> Result<(), Self::Error> {
1270            Ok(())
1271        }
1272    }
1273
1274    #[test]
1275    fn transmit_delegates_to_spi_bus_write() {
1276        let mut backend = SpiBackend::new(MockSpi::default());
1277        let data = [1_u8, 2, 3, 4, 5];
1278        backend.transmit(&data).unwrap();
1279        assert_eq!(backend.inner().0.get(), 5);
1280    }
1281
1282    // ── Other protocol encodings ─────────────────────────────────────
1283
1284    use crate::{Rgb16Order, RgbwOrder, Ws2816};
1285
1286    #[test]
1287    fn encode_sk6812_produces_correct_length() {
1288        let codec =
1289            SpiCodec::<Rgbw, Sk6812>::for_protocol(SpiEncodingPlan::sk6812_4bit(), false).unwrap();
1290        let pixel_count = 2;
1291        let pixels = [Rgbw::new(0, 0, 0, 0), Rgbw::new(0, 0, 0, 0)];
1292        let mut out: HVec<u8, 256> = HVec::new();
1293        codec.encode(RgbwOrder::Grbw, &pixels, &mut out).unwrap();
1294        assert_eq!(out.len(), codec.encoded_len(pixel_count));
1295    }
1296
1297    #[test]
1298    fn encode_ws2811_produces_correct_length() {
1299        // 8-bit symbols at 3.2 MHz -- all edges within +/-150 ns of WS2811 spec.
1300        let codec =
1301            SpiCodec::<Rgb, Ws2811>::for_protocol(SpiEncodingPlan::ws2811_8bit(), false).unwrap();
1302        let pixel_count = 2;
1303        let pixels = [Rgb::new(0, 0, 0), Rgb::new(0, 0, 0)];
1304        let mut out: HVec<u8, 256> = HVec::new();
1305        codec.encode(RgbOrder::Rgb, &pixels, &mut out).unwrap();
1306        assert_eq!(out.len(), codec.encoded_len(pixel_count));
1307    }
1308
1309    #[test]
1310    fn encode_ws2816_produces_correct_length() {
1311        let codec =
1312            SpiCodec::<Rgb16, Ws2816>::for_protocol(SpiEncodingPlan::ws2816_5bit(), false).unwrap();
1313        let pixel_count = 1;
1314        let pixels = [Rgb16::new(0, 0, 0)];
1315        let mut out: HVec<u8, 256> = HVec::new();
1316        codec.encode(Rgb16Order::Grb, &pixels, &mut out).unwrap();
1317        assert_eq!(out.len(), codec.encoded_len(pixel_count));
1318        // 48 bits × 5 SPI bits = 30 payload bytes, plus 300 us at 4 MHz = 150 bytes.
1319        assert_eq!(out.len(), 180);
1320    }
1321
1322    #[test]
1323    fn ws2816_black_and_white_have_different_payloads() {
1324        let codec =
1325            SpiCodec::<Rgb16, Ws2816>::for_protocol(SpiEncodingPlan::ws2816_5bit(), false).unwrap();
1326        let mut black: HVec<u8, 180> = HVec::new();
1327        let mut white: HVec<u8, 180> = HVec::new();
1328        codec
1329            .encode(Rgb16Order::Grb, &[Rgb16::BLACK], &mut black)
1330            .unwrap();
1331        codec
1332            .encode(Rgb16Order::Grb, &[Rgb16::WHITE], &mut white)
1333            .unwrap();
1334        assert_ne!(&black[..30], &white[..30]);
1335        assert_eq!(&black[30..], &[0; 150]);
1336        assert_eq!(&white[30..], &[0; 150]);
1337    }
1338
1339    #[test]
1340    fn ws2816_rejects_the_previous_four_bit_plan() {
1341        let plan = SpiEncodingPlan::new(4_000_000, 0b1000, 0b1100, 4);
1342        assert_eq!(
1343            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
1344            SpiCodecPlanError::TimingOutOfRange {
1345                edge: TimingEdge::ZeroLow,
1346                actual_ns: 750,
1347                minimum_ns: 800,
1348                maximum_ns: 1_200,
1349            }
1350        );
1351    }
1352
1353    #[test]
1354    fn ws2816_checks_the_bit_period_independently_of_phase_limits() {
1355        // All four phases (200/1000/600/600 ns) satisfy their individual bounds.
1356        let plan = SpiEncodingPlan::new(5_000_000, 0b100000, 0b111000, 6);
1357        assert_eq!(
1358            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
1359            SpiCodecPlanError::BitPeriodTooShort {
1360                actual_ns: 1_200,
1361                minimum_ns: 1_250,
1362            }
1363        );
1364    }
1365
1366    #[test]
1367    fn ws2816_does_not_round_a_short_bit_period_up_to_the_limit() {
1368        SpiCodec::<Rgb16, Ws2816>::for_protocol(SpiEncodingPlan::ws2816_5bit(), false).unwrap();
1369        // Its phases remain valid, but the 1249.9996875 ns period is too short.
1370        let plan = SpiEncodingPlan::new(4_000_001, 0b10000, 0b11100, 5);
1371        assert_eq!(
1372            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
1373            SpiCodecPlanError::BitPeriodTooShort {
1374                actual_ns: 1_250,
1375                minimum_ns: 1_250,
1376            }
1377        );
1378    }
1379
1380    #[test]
1381    fn ws2816_accepts_inclusive_phase_boundaries() {
1382        let plans = [
1383            // T0H=200 min, T0L=1200 max, T1H=800 max, T1L=600 ns.
1384            SpiEncodingPlan::new(5_000_000, 0b1000000, 0b1111000, 7),
1385            // T0H=320 max, T0L=960, T1H=800 max, T1L=480 min ns.
1386            SpiEncodingPlan::new(6_250_000, 0b11000000, 0b11111000, 8),
1387        ];
1388        for plan in plans {
1389            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap();
1390        }
1391    }
1392
1393    #[test]
1394    fn ws2816_rejects_fractional_phase_boundary_violations() {
1395        let cases = [
1396            // T0H is slightly below 200 ns.
1397            (
1398                SpiEncodingPlan::new(5_000_001, 0b1000000, 0b1111000, 7),
1399                TimingEdge::ZeroHigh,
1400            ),
1401            // T0L is slightly above 1200 ns.
1402            (
1403                SpiEncodingPlan::new(4_999_999, 0b1000000, 0b1111000, 7),
1404                TimingEdge::ZeroLow,
1405            ),
1406            // T0H is slightly above 320 ns.
1407            (
1408                SpiEncodingPlan::new(6_249_999, 0b11000000, 0b11111000, 8),
1409                TimingEdge::ZeroHigh,
1410            ),
1411            // T1L is slightly below 480 ns.
1412            (
1413                SpiEncodingPlan::new(6_250_001, 0b11000000, 0b11111000, 8),
1414                TimingEdge::OneLow,
1415            ),
1416        ];
1417        for (plan, expected_edge) in cases {
1418            assert!(matches!(
1419                SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false),
1420                Err(SpiCodecPlanError::TimingOutOfRange { edge, .. }) if edge == expected_edge
1421            ));
1422        }
1423    }
1424
1425    #[test]
1426    fn ws2816_checks_the_fractional_one_high_lower_boundary() {
1427        // A 520 ns phase cannot be represented exactly with these SPI frequencies.
1428        // Two cycles fall just above the limit at 3_846_153 Hz and below it at
1429        // 3_846_154 Hz, although both diagnostic durations round to 520 ns.
1430        let inside = SpiEncodingPlan::new(3_846_153, 0b10000, 0b11000, 5);
1431        SpiCodec::<Rgb16, Ws2816>::for_protocol(inside, false).unwrap();
1432        let outside = SpiEncodingPlan::new(3_846_154, 0b10000, 0b11000, 5);
1433        assert_eq!(
1434            SpiCodec::<Rgb16, Ws2816>::for_protocol(outside, false).unwrap_err(),
1435            SpiCodecPlanError::TimingOutOfRange {
1436                edge: TimingEdge::OneHigh,
1437                actual_ns: 520,
1438                minimum_ns: 520,
1439                maximum_ns: 800,
1440            }
1441        );
1442    }
1443
1444    #[test]
1445    fn timing_accepts_valid_fractional_phases_without_rounding_each_spi_cycle() {
1446        // WS2812B phases: 466.853/700.280/700.280/466.853 ns, all within limits.
1447        let plan = SpiEncodingPlan::new(4_284_000, 0b11000, 0b11100, 5);
1448        SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap();
1449        // WS2811 phases: 616.998/1850.995/1233.997/1233.997 ns, all within limits.
1450        let plan = SpiEncodingPlan::new(3_241_500, 0b11000000, 0b11110000, 8);
1451        SpiCodec::<Rgb, Ws2811>::for_protocol(plan, false).unwrap();
1452    }
1453
1454    #[test]
1455    fn timing_rejects_fractional_phases_outside_the_legacy_tolerance() {
1456        // T0L is 699.301 ns, below the 700 ns minimum.
1457        let plan = SpiEncodingPlan::new(2_860_000, 0b100, 0b110, 3);
1458        assert!(matches!(
1459            SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false),
1460            Err(SpiCodecPlanError::TimingOutOfTolerance {
1461                edge: TimingEdge::ZeroLow,
1462                ..
1463            })
1464        ));
1465    }
1466
1467    #[test]
1468    fn timing_returns_an_error_for_one_hz_without_overflowing() {
1469        let plan = SpiEncodingPlan::new(1, 0b111110, 0b100000, 6);
1470        assert_eq!(
1471            SpiCodec::<Rgb, Ws2812B>::for_protocol(plan, false).unwrap_err(),
1472            SpiCodecPlanError::TimingOutOfTolerance {
1473                edge: TimingEdge::ZeroHigh,
1474                actual_ns: u32::MAX,
1475                expected_ns: 400,
1476                tolerance_ns: 150,
1477            }
1478        );
1479    }
1480
1481    #[test]
1482    fn constructors_reject_identical_symbols() {
1483        let plan = SpiEncodingPlan::new(4_000_000, 0b100, 0b100, 3);
1484        let expected = SpiCodecPlanError::IdenticalSymbolPatterns { pattern: 0b100 };
1485        assert_eq!(
1486            SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err(),
1487            expected
1488        );
1489        assert_eq!(
1490            SpiCodec::<Rgb16, Ws2816>::for_protocol(plan, false).unwrap_err(),
1491            expected
1492        );
1493    }
1494
1495    // ── Extra reset_ns ───────────────────────────────────────────────
1496
1497    #[test]
1498    fn extra_reset_ns_increases_encoded_len() {
1499        let plan_normal = SpiEncodingPlan::ws2812_3bit();
1500        let plan_extra = SpiEncodingPlan::ws2812_3bit().with_extra_reset_ns(100_000);
1501        let codec_normal = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan_normal, false).unwrap();
1502        let codec_extra = SpiCodec::<Rgb, Ws2812B>::for_protocol(plan_extra, false).unwrap();
1503        let pixel_count = 1;
1504        let len_normal = codec_normal.encoded_len(pixel_count);
1505        let len_extra = codec_extra.encoded_len(pixel_count);
1506        assert!(
1507            len_extra > len_normal,
1508            "extra reset should increase encoded length"
1509        );
1510    }
1511
1512    // ── Plan validation edge cases ───────────────────────────────────
1513
1514    #[test]
1515    fn validate_plan_rejects_zero_bits_per_symbol() {
1516        let plan = SpiEncodingPlan::new(2_400_000, 0b100, 0b110, 0);
1517        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1518        assert_eq!(err, SpiCodecPlanError::ZeroBitsPerSymbol);
1519    }
1520
1521    #[test]
1522    fn validate_plan_rejects_bits_per_symbol_too_wide() {
1523        let plan = SpiEncodingPlan::new(2_400_000, 0b1, 0b1, 9);
1524        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1525        assert_eq!(
1526            err,
1527            SpiCodecPlanError::BitsPerSymbolTooWide { bits_per_symbol: 9 }
1528        );
1529    }
1530
1531    #[test]
1532    fn validate_plan_rejects_zero_pattern_out_of_range() {
1533        let plan = SpiEncodingPlan::new(2_400_000, 0b1111, 0b110, 3);
1534        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1535        assert!(matches!(
1536            err,
1537            SpiCodecPlanError::PatternOutOfRange {
1538                pattern: 0b1111,
1539                bits_per_symbol: 3,
1540            }
1541        ));
1542    }
1543
1544    #[test]
1545    fn validate_plan_rejects_one_pattern_out_of_range() {
1546        let plan = SpiEncodingPlan::new(2_400_000, 0b100, 0b1111, 3);
1547        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1548        assert!(matches!(
1549            err,
1550            SpiCodecPlanError::PatternOutOfRange {
1551                pattern: 0b1111,
1552                bits_per_symbol: 3,
1553            }
1554        ));
1555    }
1556
1557    #[test]
1558    fn validate_plan_rejects_non_contiguous_waveform() {
1559        let plan = SpiEncodingPlan::new(2_400_000, 0b101, 0b110, 3);
1560        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1561        assert!(matches!(
1562            err,
1563            SpiCodecPlanError::InvalidSymbolWaveform {
1564                pattern: 0b101,
1565                bits_per_symbol: 3,
1566            }
1567        ));
1568    }
1569
1570    #[test]
1571    fn validate_plan_rejects_low_leading_waveform() {
1572        let plan = SpiEncodingPlan::new(2_400_000, 0b011, 0b110, 3);
1573        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1574        assert!(matches!(
1575            err,
1576            SpiCodecPlanError::InvalidSymbolWaveform {
1577                pattern: 0b011,
1578                bits_per_symbol: 3,
1579            }
1580        ));
1581    }
1582
1583    #[test]
1584    fn validate_plan_rejects_reset_duration_overflow() {
1585        // (RESET_NS + extra_reset_ns) × spi_hz ≈ 1.84e19 exceeds the u64
1586        // fixed-point range, so `reset_bytes` would overflow without this check.
1587        let plan = SpiEncodingPlan::new(u32::MAX, 0b100, 0b110, 3).with_extra_reset_ns(u32::MAX);
1588        let err = SpiCodec::<Rgb, Ws2812B>::new(plan, false).unwrap_err();
1589        assert!(matches!(
1590            err,
1591            SpiCodecPlanError::ResetDurationOverflow {
1592                total_reset_ns: 4_295_017_295,
1593                spi_hz: u32::MAX,
1594            }
1595        ));
1596    }
1597
1598    #[test]
1599    fn encode_error_display_internal_consistency() {
1600        let s = SpiEncodeError::InternalConsistency {
1601            stage: "append_pattern_push",
1602            required: 64,
1603            capacity: 64,
1604            attempted_len: 65,
1605        }
1606        .to_string();
1607        assert!(s.contains("internal consistency error"), "{s}");
1608        assert!(s.contains("append_pattern_push"), "{s}");
1609        assert!(s.contains("attempted_len=65"), "{s}");
1610    }
1611}