Skip to main content

ftui_render/
cell.rs

1#![forbid(unsafe_code)]
2
3//! Cell types and invariants.
4//!
5//! The `Cell` is the fundamental unit of the terminal grid. Each cell occupies
6//! exactly **16 bytes** to ensure optimal cache utilization (4 cells per 64-byte
7//! cache line) and enable fast SIMD comparisons.
8//!
9//! # Layout (16 bytes, non-negotiable)
10//!
11//! ```text
12//! Cell {
13//!     content: CellContent,  // 4 bytes - char or GraphemeId
14//!     fg: PackedRgba,        // 4 bytes - foreground color
15//!     bg: PackedRgba,        // 4 bytes - background color
16//!     attrs: CellAttrs,      // 4 bytes - style flags + link ID
17//! }
18//! ```
19//!
20//! # Why 16 Bytes?
21//!
22//! - 4 cells per 64-byte cache line (perfect fit)
23//! - Single 128-bit SIMD comparison
24//! - No heap allocation for 99% of cells
25//! - 24 bytes wastes cache, 32 bytes doubles bandwidth
26
27use crate::char_width;
28
29/// Grapheme ID: reference to an interned string in `GraphemePool`.
30///
31/// # Layout
32///
33/// ```text
34/// [30-27: width (4 bits)][26-16: generation (11 bits)][15-0: pool slot (16 bits)]
35/// ```
36///
37/// # Capacity
38///
39/// - Pool slots: 65,536 (16 bits = 64K entries)
40/// - Generation: 2048 versions (11 bits) for stale access detection
41/// - Width range: 0-15 (4 bits)
42///
43/// # Design Rationale
44///
45/// - 16 bits for slot (64K) is sufficient for any single frame's unique graphemes.
46/// - 11 bits for generation allows detecting access to reused slots (fixing the ABA problem).
47/// - 4 bits for width allows display widths 0-15.
48/// - Total 31 bits leaves bit 31 for `CellContent` type discrimination.
49#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
50#[repr(transparent)]
51pub struct GraphemeId(u32);
52
53impl GraphemeId {
54    /// Maximum slot index (16 bits).
55    pub const MAX_SLOT: u32 = 0xFFFF;
56
57    /// Maximum width (4 bits).
58    pub const MAX_WIDTH: u8 = 15;
59
60    /// Maximum generation (11 bits).
61    pub const MAX_GENERATION: u16 = 2047;
62
63    /// Create a new `GraphemeId` from slot index, generation, and display width.
64    ///
65    /// # Panics
66    ///
67    /// Panics in debug mode if `slot > MAX_SLOT` or `width > MAX_WIDTH`.
68    #[inline]
69    pub const fn new(slot: u32, generation: u16, width: u8) -> Self {
70        debug_assert!(slot <= Self::MAX_SLOT, "slot overflow");
71        debug_assert!(generation <= Self::MAX_GENERATION, "generation overflow");
72        debug_assert!(width <= Self::MAX_WIDTH, "width overflow");
73        Self(
74            (slot & Self::MAX_SLOT)
75                | (((generation as u32) & 0x7FF) << 16)
76                // Mask like the sibling fields: an unmasked width >= 16
77                // would set the reserved bit 31 (the CellContent type
78                // discriminator) in release builds.
79                | (((width as u32) & 0x0F) << 27),
80        )
81    }
82
83    /// Extract the pool slot index (0-64K).
84    #[inline]
85    pub const fn slot(self) -> usize {
86        (self.0 & Self::MAX_SLOT) as usize
87    }
88
89    /// Extract the generation counter (0-2047).
90    #[inline]
91    pub const fn generation(self) -> u16 {
92        ((self.0 >> 16) & 0x7FF) as u16
93    }
94
95    /// Extract the display width (0-15).
96    #[inline]
97    pub const fn width(self) -> usize {
98        ((self.0 >> 27) & 0x0F) as usize
99    }
100
101    /// Raw u32 value for storage in `CellContent`.
102    #[inline]
103    pub const fn raw(self) -> u32 {
104        self.0
105    }
106
107    /// Reconstruct from a raw u32.
108    #[inline]
109    pub const fn from_raw(raw: u32) -> Self {
110        Self(raw)
111    }
112}
113
114impl core::fmt::Debug for GraphemeId {
115    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
116        f.debug_struct("GraphemeId")
117            .field("slot", &self.slot())
118            .field("gen", &self.generation())
119            .field("width", &self.width())
120            .finish()
121    }
122}
123
124/// Cell content: either a direct Unicode char or a reference to a grapheme cluster.
125///
126/// # Encoding Scheme (4 bytes)
127///
128/// ```text
129/// Bit 31 (type discriminator):
130///   0: Direct char (bits 0-20 contain Unicode scalar value, max U+10FFFF)
131///   1: GraphemeId reference (bits 0-30 contain slot + width)
132/// ```
133///
134/// This allows:
135/// - 99% of cells (ASCII/BMP) to be stored without heap allocation
136/// - Complex graphemes (emoji, ZWJ sequences) stored in pool
137///
138/// # Special Values
139///
140/// - `EMPTY` (0x0): Empty cell, width 0
141/// - `CONTINUATION` (0x1): Placeholder for wide character continuation
142#[derive(Clone, Copy, PartialEq, Eq, Hash)]
143#[repr(transparent)]
144pub struct CellContent(u32);
145
146impl CellContent {
147    /// Empty cell content (no character).
148    pub const EMPTY: Self = Self(0);
149
150    /// Continuation marker for wide characters.
151    ///
152    /// When a character has display width > 1, subsequent cells are filled
153    /// with this marker to indicate they are part of the previous character.
154    ///
155    /// Value is `0x7FFF_FFFF` (max i32), which is outside valid Unicode scalar
156    /// range (0..0x10FFFF) but fits in 31 bits (Direct Char mode).
157    pub const CONTINUATION: Self = Self(0x7FFF_FFFF);
158
159    /// Create content from a single Unicode character.
160    ///
161    /// For characters with display width > 1, subsequent cells should be
162    /// filled with `CONTINUATION`.
163    ///
164    /// # Tab Handling
165    ///
166    /// The tab character `\t` is normalized to a space. This prevents cursor
167    /// desynchronization, as the `Presenter` cannot predict terminal tab stops.
168    #[inline]
169    pub const fn from_char(c: char) -> Self {
170        if c == '\t' {
171            Self(' ' as u32)
172        } else {
173            Self(c as u32)
174        }
175    }
176
177    /// Create content from a grapheme ID (for multi-codepoint clusters).
178    ///
179    /// The grapheme ID references an entry in the `GraphemePool`.
180    #[inline]
181    pub const fn from_grapheme(id: GraphemeId) -> Self {
182        Self(0x8000_0000 | id.raw())
183    }
184
185    /// Check if this content is a grapheme reference (vs direct char).
186    #[inline]
187    pub const fn is_grapheme(self) -> bool {
188        self.0 & 0x8000_0000 != 0
189    }
190
191    /// Check if this is a continuation cell (part of a wide character).
192    #[inline]
193    pub const fn is_continuation(self) -> bool {
194        self.0 == Self::CONTINUATION.0
195    }
196
197    /// Check if this cell is empty.
198    #[inline]
199    pub const fn is_empty(self) -> bool {
200        self.0 == Self::EMPTY.0
201    }
202
203    /// Check if this content is the default value.
204    ///
205    /// This is equivalent to `is_empty()` and primarily exists for readability in tests.
206    #[inline]
207    pub const fn is_default(self) -> bool {
208        self.0 == Self::EMPTY.0
209    }
210
211    /// Extract the character if this is a direct char (not a grapheme).
212    ///
213    /// Returns `None` if this is empty, continuation, or a grapheme reference.
214    #[inline]
215    pub fn as_char(self) -> Option<char> {
216        if self.is_grapheme() || self.0 == Self::EMPTY.0 || self.0 == Self::CONTINUATION.0 {
217            None
218        } else {
219            char::from_u32(self.0)
220        }
221    }
222
223    /// Extract the grapheme ID if this is a grapheme reference.
224    ///
225    /// Returns `None` if this is a direct char.
226    #[inline]
227    pub const fn grapheme_id(self) -> Option<GraphemeId> {
228        if self.is_grapheme() {
229            Some(GraphemeId::from_raw(self.0 & !0x8000_0000))
230        } else {
231            None
232        }
233    }
234
235    /// Get the display width of this content.
236    ///
237    /// - Empty: 0
238    /// - Continuation: 0
239    /// - Grapheme: width embedded in GraphemeId
240    /// - Char: requires external width lookup (returns 1 as default for ASCII)
241    ///
242    /// Note: For accurate char width, use the unicode-display-width-based
243    /// helpers in this crate. This method provides a fast path for known cases.
244    #[inline]
245    pub const fn width_hint(self) -> usize {
246        if self.is_empty() || self.is_continuation() {
247            0
248        } else if self.is_grapheme() {
249            ((self.0 >> 27) & 0x0F) as usize
250        } else {
251            // For direct chars, assume width 1 (fast path for ASCII)
252            // Callers should use unicode-width for accurate measurement
253            1
254        }
255    }
256
257    /// Get the display width of this content with Unicode width semantics.
258    ///
259    /// This is the accurate (but slower) width computation for direct chars.
260    #[inline]
261    pub fn width(self) -> usize {
262        if self.is_empty() || self.is_continuation() {
263            0
264        } else if self.is_grapheme() {
265            ((self.0 >> 27) & 0x0F) as usize
266        } else {
267            let Some(c) = self.as_char() else {
268                return 1;
269            };
270            char_width(c)
271        }
272    }
273
274    /// Raw u32 value.
275    #[inline]
276    pub const fn raw(self) -> u32 {
277        self.0
278    }
279}
280
281impl Default for CellContent {
282    fn default() -> Self {
283        Self::EMPTY
284    }
285}
286
287impl core::fmt::Debug for CellContent {
288    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
289        if self.is_empty() {
290            write!(f, "CellContent::EMPTY")
291        } else if self.is_continuation() {
292            write!(f, "CellContent::CONTINUATION")
293        } else if let Some(c) = self.as_char() {
294            write!(f, "CellContent::Char({c:?})")
295        } else if let Some(id) = self.grapheme_id() {
296            write!(f, "CellContent::Grapheme({id:?})")
297        } else {
298            write!(f, "CellContent(0x{:08x})", self.0)
299        }
300    }
301}
302
303/// A single terminal cell (16 bytes).
304///
305/// # Layout
306///
307/// ```text
308/// #[repr(C, align(16))]
309/// Cell {
310///     content: CellContent,  // 4 bytes
311///     fg: PackedRgba,        // 4 bytes
312///     bg: PackedRgba,        // 4 bytes
313///     attrs: CellAttrs,      // 4 bytes
314/// }
315/// ```
316///
317/// # Invariants
318///
319/// - Size is exactly 16 bytes (verified by compile-time assert)
320/// - All fields are valid (no uninitialized memory)
321/// - Continuation cells should not have meaningful fg/bg (they inherit from parent)
322///
323/// # Default
324///
325/// The default cell is empty with transparent background, white foreground,
326/// and no style attributes.
327#[derive(Clone, Copy, PartialEq, Eq)]
328#[repr(C, align(16))]
329pub struct Cell {
330    /// Character or grapheme content.
331    pub content: CellContent,
332    /// Foreground color.
333    pub fg: PackedRgba,
334    /// Background color.
335    pub bg: PackedRgba,
336    /// Style flags and hyperlink ID.
337    pub attrs: CellAttrs,
338}
339
340// Compile-time size check
341const _: () = assert!(core::mem::size_of::<Cell>() == 16);
342
343impl Cell {
344    /// A continuation cell (placeholder for wide characters).
345    ///
346    /// When a character has display width > 1, subsequent cells are filled
347    /// with this to indicate they are "owned" by the previous cell.
348    pub const CONTINUATION: Self = Self {
349        content: CellContent::CONTINUATION,
350        fg: PackedRgba::TRANSPARENT,
351        bg: PackedRgba::TRANSPARENT,
352        attrs: CellAttrs::NONE,
353    };
354
355    /// Create a new cell with the given content and default colors.
356    #[inline]
357    pub const fn new(content: CellContent) -> Self {
358        Self {
359            content,
360            fg: PackedRgba::WHITE,
361            bg: PackedRgba::TRANSPARENT,
362            attrs: CellAttrs::NONE,
363        }
364    }
365
366    /// Create a cell from a single character.
367    #[inline]
368    pub const fn from_char(c: char) -> Self {
369        Self::new(CellContent::from_char(c))
370    }
371
372    /// Check if this is a continuation cell.
373    #[inline]
374    pub const fn is_continuation(&self) -> bool {
375        self.content.is_continuation()
376    }
377
378    /// Check if this cell is empty.
379    #[inline]
380    pub const fn is_empty(&self) -> bool {
381        self.content.is_empty()
382    }
383
384    /// Get the display width hint for this cell.
385    ///
386    /// See [`CellContent::width_hint`] for details.
387    #[inline]
388    pub const fn width_hint(&self) -> usize {
389        self.content.width_hint()
390    }
391
392    /// Bitwise equality comparison (fast path for diffing).
393    ///
394    /// Uses bitwise AND (`&`) instead of short-circuit AND (`&&`) so all
395    /// four u32 comparisons are always evaluated. This avoids branch
396    /// mispredictions in tight loops and allows LLVM to lower the check
397    /// to a single 128-bit SIMD compare on supported targets.
398    #[inline(always)]
399    pub fn bits_eq(&self, other: &Self) -> bool {
400        (self.content.raw() == other.content.raw())
401            & (self.fg == other.fg)
402            & (self.bg == other.bg)
403            & (self.attrs == other.attrs)
404    }
405
406    /// Set the cell content to a character, preserving other fields.
407    #[inline]
408    #[must_use]
409    pub const fn with_char(mut self, c: char) -> Self {
410        self.content = CellContent::from_char(c);
411        self
412    }
413
414    /// Set the foreground color.
415    #[inline]
416    #[must_use]
417    pub const fn with_fg(mut self, fg: PackedRgba) -> Self {
418        self.fg = fg;
419        self
420    }
421
422    /// Set the background color.
423    #[inline]
424    #[must_use]
425    pub const fn with_bg(mut self, bg: PackedRgba) -> Self {
426        self.bg = bg;
427        self
428    }
429
430    /// Set the style attributes.
431    #[inline]
432    #[must_use]
433    pub const fn with_attrs(mut self, attrs: CellAttrs) -> Self {
434        self.attrs = attrs;
435        self
436    }
437
438    /// Encode this cell's 16 bytes (content, fg, bg, attrs) in little-endian order.
439    #[inline]
440    #[must_use]
441    pub const fn to_le_bytes(&self) -> [u8; 16] {
442        let content = self.content.raw().to_le_bytes();
443        let fg = self.fg.0.to_le_bytes();
444        let bg = self.bg.0.to_le_bytes();
445        let attrs = self.attrs.raw().to_le_bytes();
446        [
447            content[0], content[1], content[2], content[3], fg[0], fg[1], fg[2], fg[3], bg[0],
448            bg[1], bg[2], bg[3], attrs[0], attrs[1], attrs[2], attrs[3],
449        ]
450    }
451}
452impl Default for Cell {
453    fn default() -> Self {
454        Self {
455            content: CellContent::EMPTY,
456            fg: PackedRgba::WHITE,
457            bg: PackedRgba::TRANSPARENT,
458            attrs: CellAttrs::NONE,
459        }
460    }
461}
462
463impl core::fmt::Debug for Cell {
464    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
465        f.debug_struct("Cell")
466            .field("content", &self.content)
467            .field("fg", &self.fg)
468            .field("bg", &self.bg)
469            .field("attrs", &self.attrs)
470            .finish()
471    }
472}
473
474/// A compact RGBA color.
475///
476/// - **Size:** 4 bytes (fits within the `Cell` 16-byte budget).
477/// - **Layout:** `0xRRGGBBAA` (R in bits 31..24, A in bits 7..0).
478///
479/// Notes
480/// -----
481/// This is **straight alpha** storage (RGB channels are not pre-multiplied).
482/// Compositing uses Porter-Duff **SourceOver** (`src over dst`).
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
484#[repr(transparent)]
485pub struct PackedRgba(pub u32);
486
487impl PackedRgba {
488    /// Fully transparent (alpha = 0).
489    pub const TRANSPARENT: Self = Self(0);
490    /// Opaque black.
491    pub const BLACK: Self = Self::rgb(0, 0, 0);
492    /// Opaque white.
493    pub const WHITE: Self = Self::rgb(255, 255, 255);
494    /// Opaque red.
495    pub const RED: Self = Self::rgb(255, 0, 0);
496    /// Opaque green.
497    pub const GREEN: Self = Self::rgb(0, 255, 0);
498    /// Opaque blue.
499    pub const BLUE: Self = Self::rgb(0, 0, 255);
500
501    /// Create an opaque RGB color (alpha = 255).
502    #[inline]
503    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
504        Self::rgba(r, g, b, 255)
505    }
506
507    /// Create an RGBA color with explicit alpha.
508    #[inline]
509    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
510        Self(((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | (a as u32))
511    }
512
513    /// Red channel.
514    #[inline]
515    pub const fn r(self) -> u8 {
516        (self.0 >> 24) as u8
517    }
518
519    /// Green channel.
520    #[inline]
521    pub const fn g(self) -> u8 {
522        (self.0 >> 16) as u8
523    }
524
525    /// Blue channel.
526    #[inline]
527    pub const fn b(self) -> u8 {
528        (self.0 >> 8) as u8
529    }
530
531    /// Alpha channel.
532    #[inline]
533    pub const fn a(self) -> u8 {
534        self.0 as u8
535    }
536
537    #[inline]
538    const fn div_round_u8(numer: u64, denom: u64) -> u8 {
539        debug_assert!(denom != 0);
540        let v = (numer + (denom / 2)) / denom;
541        if v > 255 { 255 } else { v as u8 }
542    }
543
544    /// Porter-Duff SourceOver: `src over dst`.
545    ///
546    /// Stored as straight alpha, so we compute the exact rational form and round at the end
547    /// (avoids accumulating rounding error across intermediate steps).
548    #[inline]
549    #[must_use]
550    pub fn over(self, dst: Self) -> Self {
551        let s_a = self.a() as u64;
552        if s_a == 255 {
553            return self;
554        }
555        if s_a == 0 {
556            return dst;
557        }
558
559        let d_a = dst.a() as u64;
560        let inv_s_a = 255 - s_a;
561
562        // out_a = s_a + d_a*(1 - s_a)  (all in [0,1], scaled by 255)
563        // We compute numer_a in the "255^2 domain" to keep channels exact:
564        // numer_a = 255*s_a + d_a*(255 - s_a)
565        // out_a_u8 = round(numer_a / 255)
566        let numer_a = 255 * s_a + d_a * inv_s_a;
567        if numer_a == 0 {
568            return Self::TRANSPARENT;
569        }
570
571        let out_a = Self::div_round_u8(numer_a, 255);
572
573        // For straight alpha, the exact rational (scaled to [0,255]) is:
574        // out_c_u8 = round( (src_c*s_a*255 + dst_c*d_a*(255 - s_a)) / numer_a )
575        let r = Self::div_round_u8(
576            (self.r() as u64) * s_a * 255 + (dst.r() as u64) * d_a * inv_s_a,
577            numer_a,
578        );
579        let g = Self::div_round_u8(
580            (self.g() as u64) * s_a * 255 + (dst.g() as u64) * d_a * inv_s_a,
581            numer_a,
582        );
583        let b = Self::div_round_u8(
584            (self.b() as u64) * s_a * 255 + (dst.b() as u64) * d_a * inv_s_a,
585            numer_a,
586        );
587
588        Self::rgba(r, g, b, out_a)
589    }
590
591    /// Apply uniform opacity in `[0.0, 1.0]` by scaling alpha.
592    #[inline]
593    #[must_use]
594    pub fn with_opacity(self, opacity: f32) -> Self {
595        let opacity = opacity.clamp(0.0, 1.0);
596        let a = ((self.a() as f32) * opacity).round().clamp(0.0, 255.0) as u8;
597        Self::rgba(self.r(), self.g(), self.b(), a)
598    }
599}
600
601bitflags::bitflags! {
602    /// 8-bit cell style flags.
603    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
604    pub struct StyleFlags: u8 {
605        /// Bold / increased intensity.
606        const BOLD          = 0b0000_0001;
607        /// Dim / decreased intensity.
608        const DIM           = 0b0000_0010;
609        /// Italic text.
610        const ITALIC        = 0b0000_0100;
611        /// Underlined text.
612        const UNDERLINE     = 0b0000_1000;
613        /// Blinking text.
614        const BLINK         = 0b0001_0000;
615        /// Reverse video (swap fg/bg).
616        const REVERSE       = 0b0010_0000;
617        /// Strikethrough text.
618        const STRIKETHROUGH = 0b0100_0000;
619        /// Hidden / invisible text.
620        const HIDDEN        = 0b1000_0000;
621    }
622}
623
624/// Packed cell attributes:
625/// - bits 31..24: `StyleFlags` (8 bits)
626/// - bits 23..0: `link_id` (24 bits)
627#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
628#[repr(transparent)]
629pub struct CellAttrs(u32);
630
631impl CellAttrs {
632    /// No attributes or link.
633    pub const NONE: Self = Self(0);
634
635    /// Sentinel value for "no hyperlink".
636    pub const LINK_ID_NONE: u32 = 0;
637    /// Maximum link ID (24-bit range).
638    ///
639    /// Matches `LinkRegistry`'s MAX_LINK_ID: the registry allocates ids up
640    /// to and including 0x00FF_FFFF (0 is the only sentinel), so the full
641    /// 24-bit range minus zero is valid here. The previous 0x00FF_FFFE
642    /// value debug-panicked on the registry's last legitimately allocated
643    /// id while release builds accepted it — a profile-divergent contract.
644    pub const LINK_ID_MAX: u32 = 0x00FF_FFFF;
645
646    /// Create attributes from flags and a hyperlink ID.
647    #[inline]
648    pub fn new(flags: StyleFlags, link_id: u32) -> Self {
649        debug_assert!(
650            link_id <= Self::LINK_ID_MAX,
651            "link_id overflow: {link_id} (max={})",
652            Self::LINK_ID_MAX
653        );
654        Self(((flags.bits() as u32) << 24) | (link_id & 0x00FF_FFFF))
655    }
656
657    /// Extract the style flags.
658    #[inline]
659    pub fn flags(self) -> StyleFlags {
660        StyleFlags::from_bits_truncate((self.0 >> 24) as u8)
661    }
662
663    /// Extract the hyperlink ID.
664    #[inline]
665    pub fn link_id(self) -> u32 {
666        self.0 & 0x00FF_FFFF
667    }
668
669    /// Return a copy with different style flags.
670    #[inline]
671    #[must_use]
672    pub fn with_flags(self, flags: StyleFlags) -> Self {
673        Self((self.0 & 0x00FF_FFFF) | ((flags.bits() as u32) << 24))
674    }
675
676    /// Return a copy with a different hyperlink ID.
677    #[inline]
678    #[must_use]
679    pub fn with_link(self, link_id: u32) -> Self {
680        debug_assert!(
681            link_id <= Self::LINK_ID_MAX,
682            "link_id overflow: {link_id} (max={})",
683            Self::LINK_ID_MAX
684        );
685        Self((self.0 & 0xFF00_0000) | (link_id & 0x00FF_FFFF))
686    }
687
688    /// Return a copy with additional style flags OR-ed in (preserving existing flags and link ID).
689    ///
690    /// Unlike [`with_flags`](Self::with_flags) which *replaces* all flags, this method
691    /// *merges* the new flags on top so that existing attributes are preserved.
692    #[inline]
693    #[must_use]
694    pub fn merged_flags(self, extra: StyleFlags) -> Self {
695        let combined = self.flags().union(extra);
696        Self((self.0 & 0x00FF_FFFF) | ((combined.bits() as u32) << 24))
697    }
698
699    /// Check whether a specific flag is set.
700    #[inline]
701    pub fn has_flag(self, flag: StyleFlags) -> bool {
702        self.flags().contains(flag)
703    }
704
705    /// Raw packed u32 value (bits 31..24 flags, bits 23..0 link_id).
706    #[inline]
707    #[must_use]
708    pub const fn raw(self) -> u32 {
709        self.0
710    }
711}
712
713#[cfg(test)]
714mod tests {
715    use super::{Cell, CellAttrs, CellContent, GraphemeId, PackedRgba, StyleFlags};
716
717    fn reference_over(src: PackedRgba, dst: PackedRgba) -> PackedRgba {
718        let sr = src.r() as f64 / 255.0;
719        let sg = src.g() as f64 / 255.0;
720        let sb = src.b() as f64 / 255.0;
721        let sa = src.a() as f64 / 255.0;
722
723        let dr = dst.r() as f64 / 255.0;
724        let dg = dst.g() as f64 / 255.0;
725        let db = dst.b() as f64 / 255.0;
726        let da = dst.a() as f64 / 255.0;
727
728        let out_a = sa + da * (1.0 - sa);
729        if out_a <= 0.0 {
730            return PackedRgba::TRANSPARENT;
731        }
732
733        let out_r = (sr * sa + dr * da * (1.0 - sa)) / out_a;
734        let out_g = (sg * sa + dg * da * (1.0 - sa)) / out_a;
735        let out_b = (sb * sa + db * da * (1.0 - sa)) / out_a;
736
737        let to_u8 = |x: f64| -> u8 { (x * 255.0).round().clamp(0.0, 255.0) as u8 };
738        PackedRgba::rgba(to_u8(out_r), to_u8(out_g), to_u8(out_b), to_u8(out_a))
739    }
740
741    #[test]
742    fn packed_rgba_is_4_bytes() {
743        assert_eq!(core::mem::size_of::<PackedRgba>(), 4);
744    }
745
746    #[test]
747    fn rgb_sets_alpha_to_255() {
748        let c = PackedRgba::rgb(1, 2, 3);
749        assert_eq!(c.r(), 1);
750        assert_eq!(c.g(), 2);
751        assert_eq!(c.b(), 3);
752        assert_eq!(c.a(), 255);
753    }
754
755    #[test]
756    fn rgba_round_trips_components() {
757        let c = PackedRgba::rgba(10, 20, 30, 40);
758        assert_eq!(c.r(), 10);
759        assert_eq!(c.g(), 20);
760        assert_eq!(c.b(), 30);
761        assert_eq!(c.a(), 40);
762    }
763
764    #[test]
765    fn over_with_opaque_src_returns_src() {
766        let src = PackedRgba::rgba(1, 2, 3, 255);
767        let dst = PackedRgba::rgba(9, 8, 7, 200);
768        assert_eq!(src.over(dst), src);
769    }
770
771    #[test]
772    fn over_with_transparent_src_returns_dst() {
773        let src = PackedRgba::TRANSPARENT;
774        let dst = PackedRgba::rgba(9, 8, 7, 200);
775        assert_eq!(src.over(dst), dst);
776    }
777
778    #[test]
779    fn over_blends_correctly_for_half_alpha_over_opaque() {
780        // 50% red over opaque blue -> purple-ish, and resulting alpha stays opaque.
781        let src = PackedRgba::rgba(255, 0, 0, 128);
782        let dst = PackedRgba::rgba(0, 0, 255, 255);
783        assert_eq!(src.over(dst), PackedRgba::rgba(128, 0, 127, 255));
784    }
785
786    #[test]
787    fn over_matches_reference_for_partial_alpha_cases() {
788        let cases = [
789            (
790                PackedRgba::rgba(200, 10, 10, 64),
791                PackedRgba::rgba(10, 200, 10, 128),
792            ),
793            (
794                PackedRgba::rgba(1, 2, 3, 1),
795                PackedRgba::rgba(250, 251, 252, 254),
796            ),
797            (
798                PackedRgba::rgba(100, 0, 200, 200),
799                PackedRgba::rgba(0, 120, 30, 50),
800            ),
801        ];
802
803        for (src, dst) in cases {
804            assert_eq!(src.over(dst), reference_over(src, dst));
805        }
806    }
807
808    #[test]
809    fn with_opacity_scales_alpha() {
810        let c = PackedRgba::rgba(10, 20, 30, 255);
811        assert_eq!(c.with_opacity(0.5).a(), 128);
812        assert_eq!(c.with_opacity(-1.0).a(), 0);
813        assert_eq!(c.with_opacity(2.0).a(), 255);
814    }
815
816    #[test]
817    fn cell_attrs_is_4_bytes() {
818        assert_eq!(core::mem::size_of::<CellAttrs>(), 4);
819    }
820
821    #[test]
822    fn cell_attrs_none_has_no_flags_and_no_link() {
823        assert!(CellAttrs::NONE.flags().is_empty());
824        assert_eq!(CellAttrs::NONE.link_id(), 0);
825    }
826
827    #[test]
828    fn cell_attrs_new_stores_flags_and_link() {
829        let flags = StyleFlags::BOLD | StyleFlags::ITALIC;
830        let a = CellAttrs::new(flags, 42);
831        assert_eq!(a.flags(), flags);
832        assert_eq!(a.link_id(), 42);
833    }
834
835    #[test]
836    fn cell_attrs_with_flags_preserves_link_id() {
837        let a = CellAttrs::new(StyleFlags::BOLD, 123);
838        let b = a.with_flags(StyleFlags::UNDERLINE);
839        assert_eq!(b.flags(), StyleFlags::UNDERLINE);
840        assert_eq!(b.link_id(), 123);
841    }
842
843    #[test]
844    fn cell_attrs_merged_flags_ors_without_clearing() {
845        let a = CellAttrs::new(StyleFlags::BOLD, 42);
846        let b = a.merged_flags(StyleFlags::ITALIC);
847        assert_eq!(b.flags(), StyleFlags::BOLD | StyleFlags::ITALIC);
848        assert_eq!(b.link_id(), 42, "link_id must be preserved");
849    }
850
851    #[test]
852    fn cell_attrs_merged_flags_noop_for_empty() {
853        let a = CellAttrs::new(StyleFlags::BOLD, 7);
854        let b = a.merged_flags(StyleFlags::empty());
855        assert_eq!(b.flags(), StyleFlags::BOLD);
856        assert_eq!(b.link_id(), 7);
857    }
858
859    #[test]
860    fn cell_attrs_with_link_preserves_flags() {
861        let a = CellAttrs::new(StyleFlags::BOLD | StyleFlags::ITALIC, 1);
862        let b = a.with_link(999);
863        assert_eq!(b.flags(), StyleFlags::BOLD | StyleFlags::ITALIC);
864        assert_eq!(b.link_id(), 999);
865    }
866
867    #[test]
868    fn cell_attrs_flag_combinations_work() {
869        let flags = StyleFlags::BOLD | StyleFlags::ITALIC;
870        let a = CellAttrs::new(flags, 0);
871        assert!(a.has_flag(StyleFlags::BOLD));
872        assert!(a.has_flag(StyleFlags::ITALIC));
873        assert!(!a.has_flag(StyleFlags::UNDERLINE));
874    }
875
876    #[test]
877    fn cell_attrs_link_id_max_boundary() {
878        let a = CellAttrs::new(StyleFlags::empty(), CellAttrs::LINK_ID_MAX);
879        assert_eq!(a.link_id(), CellAttrs::LINK_ID_MAX);
880    }
881
882    // ====== GraphemeId tests ======
883
884    #[test]
885    fn grapheme_id_is_4_bytes() {
886        assert_eq!(core::mem::size_of::<GraphemeId>(), 4);
887    }
888
889    #[test]
890    fn grapheme_id_encoding_roundtrip() {
891        let id = GraphemeId::new(12345, 42, 2);
892        assert_eq!(id.slot(), 12345);
893        assert_eq!(id.generation(), 42);
894        assert_eq!(id.width(), 2);
895    }
896
897    #[test]
898    fn grapheme_id_max_values() {
899        let id = GraphemeId::new(
900            GraphemeId::MAX_SLOT,
901            GraphemeId::MAX_GENERATION,
902            GraphemeId::MAX_WIDTH,
903        );
904        assert_eq!(id.slot(), 0xFFFF);
905        assert_eq!(id.generation(), GraphemeId::MAX_GENERATION);
906        assert_eq!(id.width(), GraphemeId::MAX_WIDTH as usize);
907    }
908
909    #[test]
910    fn grapheme_id_zero_values() {
911        let id = GraphemeId::new(0, 0, 0);
912        assert_eq!(id.slot(), 0);
913        assert_eq!(id.generation(), 0);
914        assert_eq!(id.width(), 0);
915    }
916
917    #[test]
918    fn grapheme_id_raw_roundtrip() {
919        let id = GraphemeId::new(999, 128, 5);
920        let raw = id.raw();
921        let restored = GraphemeId::from_raw(raw);
922        assert_eq!(restored.slot(), 999);
923        assert_eq!(restored.generation(), 128);
924        assert_eq!(restored.width(), 5);
925    }
926
927    // ====== CellContent tests ======
928
929    #[test]
930    fn cell_content_is_4_bytes() {
931        assert_eq!(core::mem::size_of::<CellContent>(), 4);
932    }
933
934    #[test]
935    fn cell_content_empty_properties() {
936        assert!(CellContent::EMPTY.is_empty());
937        assert!(!CellContent::EMPTY.is_continuation());
938        assert!(!CellContent::EMPTY.is_grapheme());
939        assert_eq!(CellContent::EMPTY.width_hint(), 0);
940    }
941
942    #[test]
943    fn cell_content_continuation_properties() {
944        assert!(CellContent::CONTINUATION.is_continuation());
945        assert!(!CellContent::CONTINUATION.is_empty());
946        assert!(!CellContent::CONTINUATION.is_grapheme());
947        assert_eq!(CellContent::CONTINUATION.width_hint(), 0);
948    }
949
950    #[test]
951    fn cell_content_from_char_ascii() {
952        let c = CellContent::from_char('A');
953        assert!(!c.is_grapheme());
954        assert!(!c.is_empty());
955        assert!(!c.is_continuation());
956        assert_eq!(c.as_char(), Some('A'));
957        assert_eq!(c.width_hint(), 1);
958    }
959
960    #[test]
961    fn cell_content_from_char_unicode() {
962        // BMP character
963        let c = CellContent::from_char('日');
964        assert_eq!(c.as_char(), Some('日'));
965        assert!(!c.is_grapheme());
966
967        // Supplementary plane character (emoji)
968        let c2 = CellContent::from_char('🎉');
969        assert_eq!(c2.as_char(), Some('🎉'));
970        assert!(!c2.is_grapheme());
971    }
972
973    #[test]
974    fn cell_content_from_grapheme() {
975        let id = GraphemeId::new(42, 0, 2);
976        let c = CellContent::from_grapheme(id);
977
978        assert!(c.is_grapheme());
979        assert!(!c.is_empty());
980        assert!(!c.is_continuation());
981        assert_eq!(c.grapheme_id(), Some(id));
982        assert_eq!(c.as_char(), None);
983        assert_eq!(c.width_hint(), 2);
984    }
985
986    #[test]
987    fn cell_content_width_for_chars() {
988        let ascii = CellContent::from_char('A');
989        assert_eq!(ascii.width(), 1);
990
991        let wide = CellContent::from_char('日');
992        assert_eq!(wide.width(), 2);
993
994        let emoji = CellContent::from_char('🎉');
995        assert_eq!(emoji.width(), 2);
996
997        // Unicode East Asian Width properties:
998        // - '⚡' (U+26A1) is Wide → always width 2
999        // - '⚙' (U+2699) is Neutral → 1 (non-CJK) or 2 (CJK)
1000        // - '❤' (U+2764) is Neutral → 1 (non-CJK) or 2 (CJK)
1001        let bolt = CellContent::from_char('⚡');
1002        assert_eq!(bolt.width(), 2, "bolt is Wide, always width 2");
1003
1004        // Neutral-width characters: width depends on CJK mode
1005        let gear = CellContent::from_char('⚙');
1006        let heart = CellContent::from_char('❤');
1007        assert!(
1008            [1, 2].contains(&gear.width()),
1009            "gear should be 1 (non-CJK) or 2 (CJK), got {}",
1010            gear.width()
1011        );
1012        assert_eq!(
1013            gear.width(),
1014            heart.width(),
1015            "gear and heart should have same width (both Neutral)"
1016        );
1017    }
1018
1019    #[test]
1020    fn cell_content_width_for_grapheme() {
1021        let id = GraphemeId::new(7, 0, 3);
1022        let c = CellContent::from_grapheme(id);
1023        assert_eq!(c.width(), 3);
1024    }
1025
1026    #[test]
1027    fn cell_content_width_empty_is_zero() {
1028        assert_eq!(CellContent::EMPTY.width(), 0);
1029        assert_eq!(CellContent::CONTINUATION.width(), 0);
1030    }
1031
1032    #[test]
1033    fn cell_content_grapheme_discriminator_bit() {
1034        // Chars should have bit 31 = 0
1035        let char_content = CellContent::from_char('X');
1036        assert_eq!(char_content.raw() & 0x8000_0000, 0);
1037
1038        // Graphemes should have bit 31 = 1
1039        let grapheme_content = CellContent::from_grapheme(GraphemeId::new(1, 0, 1));
1040        assert_ne!(grapheme_content.raw() & 0x8000_0000, 0);
1041    }
1042
1043    // ====== Cell tests ======
1044
1045    #[test]
1046    fn cell_is_16_bytes() {
1047        assert_eq!(core::mem::size_of::<Cell>(), 16);
1048    }
1049
1050    #[test]
1051    fn cell_alignment_is_16() {
1052        assert_eq!(core::mem::align_of::<Cell>(), 16);
1053    }
1054
1055    #[test]
1056    fn cell_default_properties() {
1057        let cell = Cell::default();
1058        assert!(cell.is_empty());
1059        assert!(!cell.is_continuation());
1060        assert_eq!(cell.fg, PackedRgba::WHITE);
1061        assert_eq!(cell.bg, PackedRgba::TRANSPARENT);
1062        assert_eq!(cell.attrs, CellAttrs::NONE);
1063    }
1064
1065    #[test]
1066    fn cell_continuation_constant() {
1067        assert!(Cell::CONTINUATION.is_continuation());
1068        assert!(!Cell::CONTINUATION.is_empty());
1069    }
1070
1071    #[test]
1072    fn cell_from_char() {
1073        let cell = Cell::from_char('X');
1074        assert_eq!(cell.content.as_char(), Some('X'));
1075        assert_eq!(cell.fg, PackedRgba::WHITE);
1076        assert_eq!(cell.bg, PackedRgba::TRANSPARENT);
1077    }
1078
1079    #[test]
1080    fn cell_builder_methods() {
1081        let cell = Cell::from_char('A')
1082            .with_fg(PackedRgba::rgb(255, 0, 0))
1083            .with_bg(PackedRgba::rgb(0, 0, 255))
1084            .with_attrs(CellAttrs::new(StyleFlags::BOLD, 0));
1085
1086        assert_eq!(cell.content.as_char(), Some('A'));
1087        assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
1088        assert_eq!(cell.bg, PackedRgba::rgb(0, 0, 255));
1089        assert!(cell.attrs.has_flag(StyleFlags::BOLD));
1090    }
1091
1092    #[test]
1093    fn cell_bits_eq_same_cells() {
1094        let cell1 = Cell::from_char('X').with_fg(PackedRgba::rgb(1, 2, 3));
1095        let cell2 = Cell::from_char('X').with_fg(PackedRgba::rgb(1, 2, 3));
1096        assert!(cell1.bits_eq(&cell2));
1097    }
1098
1099    #[test]
1100    fn cell_bits_eq_different_cells() {
1101        let cell1 = Cell::from_char('X');
1102        let cell2 = Cell::from_char('Y');
1103        assert!(!cell1.bits_eq(&cell2));
1104
1105        let cell3 = Cell::from_char('X').with_fg(PackedRgba::rgb(1, 2, 3));
1106        assert!(!cell1.bits_eq(&cell3));
1107    }
1108
1109    #[test]
1110    fn cell_width_hint() {
1111        let empty = Cell::default();
1112        assert_eq!(empty.width_hint(), 0);
1113
1114        let cont = Cell::CONTINUATION;
1115        assert_eq!(cont.width_hint(), 0);
1116
1117        let ascii = Cell::from_char('A');
1118        assert_eq!(ascii.width_hint(), 1);
1119    }
1120
1121    // Property tests moved to top-level `cell_proptests` module for edition 2024 compat.
1122
1123    // ====== PackedRgba extended coverage ======
1124
1125    #[test]
1126    fn packed_rgba_named_constants() {
1127        assert_eq!(PackedRgba::TRANSPARENT, PackedRgba(0));
1128        assert_eq!(PackedRgba::TRANSPARENT.a(), 0);
1129
1130        assert_eq!(PackedRgba::BLACK.r(), 0);
1131        assert_eq!(PackedRgba::BLACK.g(), 0);
1132        assert_eq!(PackedRgba::BLACK.b(), 0);
1133        assert_eq!(PackedRgba::BLACK.a(), 255);
1134
1135        assert_eq!(PackedRgba::WHITE.r(), 255);
1136        assert_eq!(PackedRgba::WHITE.g(), 255);
1137        assert_eq!(PackedRgba::WHITE.b(), 255);
1138        assert_eq!(PackedRgba::WHITE.a(), 255);
1139
1140        assert_eq!(PackedRgba::RED, PackedRgba::rgb(255, 0, 0));
1141        assert_eq!(PackedRgba::GREEN, PackedRgba::rgb(0, 255, 0));
1142        assert_eq!(PackedRgba::BLUE, PackedRgba::rgb(0, 0, 255));
1143    }
1144
1145    #[test]
1146    fn packed_rgba_default_is_transparent() {
1147        assert_eq!(PackedRgba::default(), PackedRgba::TRANSPARENT);
1148    }
1149
1150    #[test]
1151    fn over_both_transparent_returns_transparent() {
1152        // Exercises numer_a == 0 branch (line 508)
1153        let result = PackedRgba::TRANSPARENT.over(PackedRgba::TRANSPARENT);
1154        assert_eq!(result, PackedRgba::TRANSPARENT);
1155    }
1156
1157    #[test]
1158    fn over_partial_alpha_over_transparent_dst() {
1159        // d_a == 0 path: src partial alpha over fully transparent
1160        let src = PackedRgba::rgba(200, 100, 50, 128);
1161        let result = src.over(PackedRgba::TRANSPARENT);
1162        // Output alpha = src_alpha (dst contributes nothing)
1163        assert_eq!(result.a(), 128);
1164        // Colors should be src colors since dst has no contribution
1165        assert_eq!(result.r(), 200);
1166        assert_eq!(result.g(), 100);
1167        assert_eq!(result.b(), 50);
1168    }
1169
1170    #[test]
1171    fn over_very_low_alpha() {
1172        // Near-transparent source (alpha=1) over opaque destination
1173        let src = PackedRgba::rgba(255, 0, 0, 1);
1174        let dst = PackedRgba::rgba(0, 0, 255, 255);
1175        let result = src.over(dst);
1176        // Result should be very close to dst
1177        assert_eq!(result.a(), 255);
1178        assert!(result.b() > 250, "b={} should be near 255", result.b());
1179        assert!(result.r() < 5, "r={} should be near 0", result.r());
1180    }
1181
1182    #[test]
1183    fn with_opacity_exact_zero() {
1184        let c = PackedRgba::rgba(10, 20, 30, 200);
1185        let result = c.with_opacity(0.0);
1186        assert_eq!(result.a(), 0);
1187        assert_eq!(result.r(), 10); // RGB preserved
1188        assert_eq!(result.g(), 20);
1189        assert_eq!(result.b(), 30);
1190    }
1191
1192    #[test]
1193    fn with_opacity_exact_one() {
1194        let c = PackedRgba::rgba(10, 20, 30, 200);
1195        let result = c.with_opacity(1.0);
1196        assert_eq!(result.a(), 200); // Alpha unchanged
1197        assert_eq!(result.r(), 10);
1198    }
1199
1200    #[test]
1201    fn with_opacity_preserves_rgb() {
1202        let c = PackedRgba::rgba(42, 84, 168, 255);
1203        let result = c.with_opacity(0.25);
1204        assert_eq!(result.r(), 42);
1205        assert_eq!(result.g(), 84);
1206        assert_eq!(result.b(), 168);
1207        assert_eq!(result.a(), 64); // 255 * 0.25 = 63.75 → 64
1208    }
1209
1210    // ====== CellContent extended coverage ======
1211
1212    #[test]
1213    fn cell_content_as_char_none_for_empty() {
1214        assert_eq!(CellContent::EMPTY.as_char(), None);
1215    }
1216
1217    #[test]
1218    fn cell_content_as_char_none_for_continuation() {
1219        assert_eq!(CellContent::CONTINUATION.as_char(), None);
1220    }
1221
1222    #[test]
1223    fn cell_content_as_char_none_for_grapheme() {
1224        let id = GraphemeId::new(1, 2, 1);
1225        let c = CellContent::from_grapheme(id);
1226        assert_eq!(c.as_char(), None);
1227    }
1228
1229    #[test]
1230    fn cell_content_grapheme_id_none_for_char() {
1231        let c = CellContent::from_char('A');
1232        assert_eq!(c.grapheme_id(), None);
1233    }
1234
1235    #[test]
1236    fn cell_content_grapheme_id_none_for_empty() {
1237        assert_eq!(CellContent::EMPTY.grapheme_id(), None);
1238    }
1239
1240    #[test]
1241    fn cell_content_width_control_chars() {
1242        // Control characters have width 0, except tab/newline/CR which are 1 cell
1243        // Note: NUL (0x00) is CellContent::EMPTY, so test with other controls
1244        let tab = CellContent::from_char('\t');
1245        assert_eq!(tab.width(), 1);
1246
1247        let bel = CellContent::from_char('\x07');
1248        assert_eq!(bel.width(), 0);
1249    }
1250
1251    #[test]
1252    fn cell_content_width_hint_always_1_for_chars() {
1253        // width_hint is the fast path that always returns 1 for non-special chars
1254        let wide = CellContent::from_char('日');
1255        assert_eq!(wide.width_hint(), 1); // fast path says 1
1256        assert_eq!(wide.width(), 2); // accurate path says 2
1257    }
1258
1259    #[test]
1260    fn cell_content_default_is_empty() {
1261        assert_eq!(CellContent::default(), CellContent::EMPTY);
1262    }
1263
1264    #[test]
1265    fn cell_content_debug_empty() {
1266        let s = format!("{:?}", CellContent::EMPTY);
1267        assert_eq!(s, "CellContent::EMPTY");
1268    }
1269
1270    #[test]
1271    fn cell_content_debug_continuation() {
1272        let s = format!("{:?}", CellContent::CONTINUATION);
1273        assert_eq!(s, "CellContent::CONTINUATION");
1274    }
1275
1276    #[test]
1277    fn cell_content_debug_char() {
1278        let s = format!("{:?}", CellContent::from_char('X'));
1279        assert!(s.starts_with("CellContent::Char("), "got: {s}");
1280    }
1281
1282    #[test]
1283    fn cell_content_debug_grapheme() {
1284        let id = GraphemeId::new(1, 2, 1);
1285        let s = format!("{:?}", CellContent::from_grapheme(id));
1286        assert!(s.starts_with("CellContent::Grapheme("), "got: {s}");
1287    }
1288
1289    #[test]
1290    fn cell_content_raw_value() {
1291        let c = CellContent::from_char('A');
1292        assert_eq!(c.raw(), 'A' as u32);
1293
1294        let g = CellContent::from_grapheme(GraphemeId::new(5, 2, 1));
1295        assert_ne!(g.raw() & 0x8000_0000, 0);
1296    }
1297
1298    // ====== CellAttrs extended coverage ======
1299
1300    #[test]
1301    fn cell_attrs_default_is_none() {
1302        assert_eq!(CellAttrs::default(), CellAttrs::NONE);
1303    }
1304
1305    #[test]
1306    fn cell_attrs_each_flag_isolated() {
1307        let all_flags = [
1308            StyleFlags::BOLD,
1309            StyleFlags::DIM,
1310            StyleFlags::ITALIC,
1311            StyleFlags::UNDERLINE,
1312            StyleFlags::BLINK,
1313            StyleFlags::REVERSE,
1314            StyleFlags::STRIKETHROUGH,
1315            StyleFlags::HIDDEN,
1316        ];
1317
1318        for &flag in &all_flags {
1319            let a = CellAttrs::new(flag, 0);
1320            assert!(a.has_flag(flag), "flag {:?} should be set", flag);
1321
1322            // Verify no other flags are set
1323            for &other in &all_flags {
1324                if other != flag {
1325                    assert!(
1326                        !a.has_flag(other),
1327                        "flag {:?} should NOT be set when only {:?} is",
1328                        other,
1329                        flag
1330                    );
1331                }
1332            }
1333        }
1334    }
1335
1336    #[test]
1337    fn cell_attrs_all_flags_combined() {
1338        let all = StyleFlags::BOLD
1339            | StyleFlags::DIM
1340            | StyleFlags::ITALIC
1341            | StyleFlags::UNDERLINE
1342            | StyleFlags::BLINK
1343            | StyleFlags::REVERSE
1344            | StyleFlags::STRIKETHROUGH
1345            | StyleFlags::HIDDEN;
1346        let a = CellAttrs::new(all, 42);
1347        assert_eq!(a.flags(), all);
1348        assert!(a.has_flag(StyleFlags::BOLD));
1349        assert!(a.has_flag(StyleFlags::HIDDEN));
1350        assert_eq!(a.link_id(), 42);
1351    }
1352
1353    #[test]
1354    fn cell_attrs_link_id_zero() {
1355        let a = CellAttrs::new(StyleFlags::BOLD, CellAttrs::LINK_ID_NONE);
1356        assert_eq!(a.link_id(), 0);
1357        assert!(a.has_flag(StyleFlags::BOLD));
1358    }
1359
1360    #[test]
1361    fn cell_attrs_with_link_to_none() {
1362        let a = CellAttrs::new(StyleFlags::ITALIC, 500);
1363        let b = a.with_link(CellAttrs::LINK_ID_NONE);
1364        assert_eq!(b.link_id(), 0);
1365        assert!(b.has_flag(StyleFlags::ITALIC));
1366    }
1367
1368    #[test]
1369    fn cell_attrs_with_flags_to_empty() {
1370        let a = CellAttrs::new(StyleFlags::BOLD | StyleFlags::ITALIC, 123);
1371        let b = a.with_flags(StyleFlags::empty());
1372        assert!(b.flags().is_empty());
1373        assert_eq!(b.link_id(), 123);
1374    }
1375
1376    // ====== Cell extended coverage ======
1377
1378    #[test]
1379    fn cell_bits_eq_detects_bg_difference() {
1380        let cell1 = Cell::from_char('X');
1381        let cell2 = Cell::from_char('X').with_bg(PackedRgba::RED);
1382        assert!(!cell1.bits_eq(&cell2));
1383    }
1384
1385    #[test]
1386    fn cell_bits_eq_detects_attrs_difference() {
1387        let cell1 = Cell::from_char('X');
1388        let cell2 = Cell::from_char('X').with_attrs(CellAttrs::new(StyleFlags::BOLD, 0));
1389        assert!(!cell1.bits_eq(&cell2));
1390    }
1391
1392    #[test]
1393    fn cell_with_char_preserves_colors_and_attrs() {
1394        let cell = Cell::from_char('A')
1395            .with_fg(PackedRgba::RED)
1396            .with_bg(PackedRgba::BLUE)
1397            .with_attrs(CellAttrs::new(StyleFlags::BOLD, 42));
1398
1399        let updated = cell.with_char('Z');
1400        assert_eq!(updated.content.as_char(), Some('Z'));
1401        assert_eq!(updated.fg, PackedRgba::RED);
1402        assert_eq!(updated.bg, PackedRgba::BLUE);
1403        assert!(updated.attrs.has_flag(StyleFlags::BOLD));
1404        assert_eq!(updated.attrs.link_id(), 42);
1405    }
1406
1407    #[test]
1408    fn cell_new_vs_from_char() {
1409        let a = Cell::new(CellContent::from_char('A'));
1410        let b = Cell::from_char('A');
1411        assert!(a.bits_eq(&b));
1412    }
1413
1414    #[test]
1415    fn cell_continuation_has_transparent_colors() {
1416        assert_eq!(Cell::CONTINUATION.fg, PackedRgba::TRANSPARENT);
1417        assert_eq!(Cell::CONTINUATION.bg, PackedRgba::TRANSPARENT);
1418        assert_eq!(Cell::CONTINUATION.attrs, CellAttrs::NONE);
1419    }
1420
1421    #[test]
1422    fn cell_debug_format() {
1423        let cell = Cell::from_char('A');
1424        let s = format!("{:?}", cell);
1425        assert!(s.contains("Cell"), "got: {s}");
1426        assert!(s.contains("content"), "got: {s}");
1427        assert!(s.contains("fg"), "got: {s}");
1428        assert!(s.contains("bg"), "got: {s}");
1429        assert!(s.contains("attrs"), "got: {s}");
1430    }
1431
1432    #[test]
1433    fn cell_is_empty_for_various() {
1434        assert!(Cell::default().is_empty());
1435        assert!(!Cell::from_char('A').is_empty());
1436        assert!(!Cell::CONTINUATION.is_empty());
1437    }
1438
1439    #[test]
1440    fn cell_is_continuation_for_various() {
1441        assert!(!Cell::default().is_continuation());
1442        assert!(!Cell::from_char('A').is_continuation());
1443        assert!(Cell::CONTINUATION.is_continuation());
1444    }
1445
1446    #[test]
1447    fn cell_width_hint_for_grapheme() {
1448        let id = GraphemeId::new(100, 0, 3);
1449        let cell = Cell::new(CellContent::from_grapheme(id));
1450        assert_eq!(cell.width_hint(), 3);
1451    }
1452
1453    // ====== GraphemeId extended coverage ======
1454
1455    #[test]
1456    fn grapheme_id_default() {
1457        let id = GraphemeId::default();
1458        assert_eq!(id.slot(), 0);
1459        assert_eq!(id.generation(), 0);
1460        assert_eq!(id.width(), 0);
1461    }
1462
1463    #[test]
1464    fn grapheme_id_debug_format() {
1465        let id = GraphemeId::new(42, 5, 2);
1466        let s = format!("{:?}", id);
1467        assert!(s.contains("GraphemeId"), "got: {s}");
1468        assert!(s.contains("42"), "got: {s}");
1469        assert!(s.contains("5"), "got: {s}");
1470        assert!(s.contains("2"), "got: {s}");
1471    }
1472
1473    #[test]
1474    fn grapheme_id_width_isolated_from_slot() {
1475        // Verify slot bits don't leak into width field
1476        let id = GraphemeId::new(GraphemeId::MAX_SLOT, 0, 0);
1477        assert_eq!(id.width(), 0);
1478        assert_eq!(id.slot(), 0xFFFF);
1479
1480        let id2 = GraphemeId::new(0, 0, GraphemeId::MAX_WIDTH);
1481        assert_eq!(id2.slot(), 0);
1482        assert_eq!(id2.width(), GraphemeId::MAX_WIDTH as usize);
1483    }
1484
1485    // ====== StyleFlags coverage ======
1486
1487    #[test]
1488    fn style_flags_empty_has_no_bits() {
1489        assert!(StyleFlags::empty().is_empty());
1490        assert_eq!(StyleFlags::empty().bits(), 0);
1491    }
1492
1493    #[test]
1494    fn style_flags_all_has_all_bits() {
1495        let all = StyleFlags::all();
1496        assert!(all.contains(StyleFlags::BOLD));
1497        assert!(all.contains(StyleFlags::DIM));
1498        assert!(all.contains(StyleFlags::ITALIC));
1499        assert!(all.contains(StyleFlags::UNDERLINE));
1500        assert!(all.contains(StyleFlags::BLINK));
1501        assert!(all.contains(StyleFlags::REVERSE));
1502        assert!(all.contains(StyleFlags::STRIKETHROUGH));
1503        assert!(all.contains(StyleFlags::HIDDEN));
1504    }
1505
1506    #[test]
1507    fn style_flags_union_and_intersection() {
1508        let a = StyleFlags::BOLD | StyleFlags::ITALIC;
1509        let b = StyleFlags::ITALIC | StyleFlags::UNDERLINE;
1510        assert_eq!(
1511            a | b,
1512            StyleFlags::BOLD | StyleFlags::ITALIC | StyleFlags::UNDERLINE
1513        );
1514        assert_eq!(a & b, StyleFlags::ITALIC);
1515    }
1516
1517    #[test]
1518    fn style_flags_from_bits_truncate() {
1519        // 0xFF should give all flags
1520        let all = StyleFlags::from_bits_truncate(0xFF);
1521        assert_eq!(all, StyleFlags::all());
1522
1523        // 0x00 should give empty
1524        let none = StyleFlags::from_bits_truncate(0x00);
1525        assert!(none.is_empty());
1526    }
1527
1528    // ====== Edge-case tests (bd-35ddr) ======
1529
1530    // -- PackedRgba edge cases --
1531
1532    #[test]
1533    fn over_not_commutative() {
1534        let red_half = PackedRgba::rgba(255, 0, 0, 128);
1535        let blue_half = PackedRgba::rgba(0, 0, 255, 128);
1536        let a_over_b = red_half.over(blue_half);
1537        let b_over_a = blue_half.over(red_half);
1538        // Porter-Duff SourceOver is NOT commutative
1539        assert_ne!(a_over_b, b_over_a);
1540    }
1541
1542    #[test]
1543    fn over_opaque_self_compositing_is_idempotent() {
1544        let c = PackedRgba::rgba(42, 84, 168, 255);
1545        assert_eq!(c.over(c), c);
1546    }
1547
1548    #[test]
1549    fn over_near_opaque_src_alpha_254() {
1550        // Non-trivial branch: alpha=254 takes the blending path, not the early-out
1551        let src = PackedRgba::rgba(255, 0, 0, 254);
1552        let dst = PackedRgba::rgba(0, 0, 255, 255);
1553        let result = src.over(dst);
1554        assert_eq!(result.a(), 255);
1555        // Red should dominate but not quite 255
1556        assert!(result.r() >= 253, "r={}", result.r());
1557        assert!(result.b() <= 2, "b={}", result.b());
1558    }
1559
1560    #[test]
1561    fn over_both_partial_alpha_symmetric_colors() {
1562        // 128-alpha red over 128-alpha red — output alpha should be ~192
1563        let c = PackedRgba::rgba(200, 100, 50, 128);
1564        let result = c.over(c);
1565        let ref_result = reference_over(c, c);
1566        assert_eq!(result, ref_result);
1567        // Alpha: 128 + 128*(1-128/255) = 128 + 128*0.498 ≈ 192
1568        assert!(result.a() >= 190 && result.a() <= 194, "a={}", result.a());
1569    }
1570
1571    #[test]
1572    fn over_both_alpha_1_minimal() {
1573        let src = PackedRgba::rgba(255, 255, 255, 1);
1574        let dst = PackedRgba::rgba(0, 0, 0, 1);
1575        let result = src.over(dst);
1576        let ref_result = reference_over(src, dst);
1577        assert_eq!(result, ref_result);
1578        // Output alpha should be ~2 (very transparent)
1579        assert!(result.a() <= 3, "a={}", result.a());
1580    }
1581
1582    #[test]
1583    fn over_white_alpha_0_over_opaque_is_dst() {
1584        // White with alpha=0 should be treated as transparent
1585        let src = PackedRgba::rgba(255, 255, 255, 0);
1586        let dst = PackedRgba::rgba(100, 50, 25, 255);
1587        assert_eq!(src.over(dst), dst);
1588    }
1589
1590    #[test]
1591    fn with_opacity_nan_clamps_to_zero() {
1592        let c = PackedRgba::rgba(10, 20, 30, 200);
1593        let result = c.with_opacity(f32::NAN);
1594        // NaN.clamp(0.0, 1.0) returns... let's verify behavior
1595        // In Rust, NaN.clamp returns NaN, and NaN * 200 = NaN, then NaN.round() = NaN
1596        // NaN as u8 = 0 in Rust
1597        assert_eq!(result.r(), 10);
1598        assert_eq!(result.g(), 20);
1599        assert_eq!(result.b(), 30);
1600    }
1601
1602    #[test]
1603    fn with_opacity_negative_infinity_clamps_to_zero() {
1604        let c = PackedRgba::rgba(10, 20, 30, 200);
1605        let result = c.with_opacity(f32::NEG_INFINITY);
1606        assert_eq!(result.a(), 0);
1607    }
1608
1609    #[test]
1610    fn with_opacity_positive_infinity_clamps_to_original() {
1611        let c = PackedRgba::rgba(10, 20, 30, 200);
1612        let result = c.with_opacity(f32::INFINITY);
1613        assert_eq!(result.a(), 200);
1614    }
1615
1616    #[test]
1617    fn with_opacity_on_transparent_stays_transparent() {
1618        let c = PackedRgba::TRANSPARENT;
1619        assert_eq!(c.with_opacity(0.5).a(), 0);
1620        assert_eq!(c.with_opacity(1.0).a(), 0);
1621    }
1622
1623    #[test]
1624    fn packed_rgba_extreme_channel_values() {
1625        let all_max = PackedRgba::rgba(255, 255, 255, 255);
1626        assert_eq!(all_max.r(), 255);
1627        assert_eq!(all_max.g(), 255);
1628        assert_eq!(all_max.b(), 255);
1629        assert_eq!(all_max.a(), 255);
1630
1631        let all_zero = PackedRgba::rgba(0, 0, 0, 0);
1632        assert_eq!(all_zero, PackedRgba::TRANSPARENT);
1633    }
1634
1635    #[test]
1636    fn packed_rgba_hash_differs_for_different_values() {
1637        use std::collections::HashSet;
1638        let mut set = HashSet::new();
1639        set.insert(PackedRgba::RED);
1640        set.insert(PackedRgba::GREEN);
1641        set.insert(PackedRgba::BLUE);
1642        set.insert(PackedRgba::RED); // duplicate
1643        assert_eq!(set.len(), 3);
1644    }
1645
1646    #[test]
1647    fn packed_rgba_channel_isolation() {
1648        // Changing one channel should not affect others
1649        let base = PackedRgba::rgba(10, 20, 30, 40);
1650        let different_r = PackedRgba::rgba(99, 20, 30, 40);
1651        assert_ne!(base, different_r);
1652        assert_eq!(base.g(), different_r.g());
1653        assert_eq!(base.b(), different_r.b());
1654        assert_eq!(base.a(), different_r.a());
1655    }
1656
1657    // -- CellContent edge cases --
1658
1659    #[test]
1660    fn cell_content_nul_char_equals_empty() {
1661        // '\0' as u32 == 0, same as EMPTY.raw()
1662        let nul = CellContent::from_char('\0');
1663        assert_eq!(nul.raw(), CellContent::EMPTY.raw());
1664        assert!(nul.is_empty());
1665        assert_eq!(nul.as_char(), None); // Empty is filtered out by as_char
1666    }
1667
1668    #[test]
1669    fn cell_content_soh_char_is_not_continuation() {
1670        let soh = CellContent::from_char('\x01');
1671        assert_eq!(soh.raw(), 1);
1672        assert!(!soh.is_empty());
1673        assert!(!soh.is_continuation());
1674        assert_eq!(soh.as_char(), Some('\x01'));
1675    }
1676
1677    #[test]
1678    fn cell_content_max_unicode_codepoint() {
1679        let max = CellContent::from_char('\u{10FFFF}');
1680        assert_eq!(max.as_char(), Some('\u{10FFFF}'));
1681        assert!(!max.is_grapheme());
1682        // U+10FFFF is a noncharacter, should have width 1 (fast path)
1683        assert_eq!(max.width_hint(), 1);
1684    }
1685
1686    #[test]
1687    fn cell_content_bmp_boundary_chars() {
1688        // Last BMP char before surrogates (U+D7FF)
1689        let last_before_surrogates = CellContent::from_char('\u{D7FF}');
1690        assert_eq!(last_before_surrogates.as_char(), Some('\u{D7FF}'));
1691
1692        // First char after surrogates (U+E000)
1693        let first_after_surrogates = CellContent::from_char('\u{E000}');
1694        assert_eq!(first_after_surrogates.as_char(), Some('\u{E000}'));
1695
1696        // First supplementary char (U+10000)
1697        let supplementary = CellContent::from_char('\u{10000}');
1698        assert_eq!(supplementary.as_char(), Some('\u{10000}'));
1699        assert!(!supplementary.is_grapheme()); // bit 31 is NOT set (U+10000 = 0x10000)
1700    }
1701
1702    #[test]
1703    fn cell_content_grapheme_with_zero_width() {
1704        let id = GraphemeId::new(42, 0, 0);
1705        let c = CellContent::from_grapheme(id);
1706        assert_eq!(c.width_hint(), 0);
1707        assert_eq!(c.width(), 0);
1708        assert!(c.is_grapheme());
1709    }
1710
1711    #[test]
1712    fn cell_content_grapheme_with_max_width() {
1713        let id = GraphemeId::new(1, 0, GraphemeId::MAX_WIDTH);
1714        let c = CellContent::from_grapheme(id);
1715        assert_eq!(c.width_hint(), GraphemeId::MAX_WIDTH as usize);
1716        assert_eq!(c.width(), GraphemeId::MAX_WIDTH as usize);
1717    }
1718
1719    #[test]
1720    fn cell_content_continuation_value_is_max_i31() {
1721        // CONTINUATION = 0x7FFF_FFFF — max value with bit 31 clear
1722        assert_eq!(CellContent::CONTINUATION.raw(), 0x7FFF_FFFF);
1723        assert!(!CellContent::CONTINUATION.is_grapheme()); // bit 31 = 0
1724        assert!(CellContent::CONTINUATION.is_continuation());
1725    }
1726
1727    #[test]
1728    fn cell_content_empty_and_continuation_are_distinct() {
1729        assert_ne!(CellContent::EMPTY, CellContent::CONTINUATION);
1730        assert!(CellContent::EMPTY.is_empty());
1731        assert!(!CellContent::EMPTY.is_continuation());
1732        assert!(!CellContent::CONTINUATION.is_empty());
1733        assert!(CellContent::CONTINUATION.is_continuation());
1734    }
1735
1736    #[test]
1737    fn cell_content_grapheme_id_strips_high_bit() {
1738        let id = GraphemeId::new(
1739            GraphemeId::MAX_SLOT,
1740            GraphemeId::MAX_GENERATION,
1741            GraphemeId::MAX_WIDTH,
1742        );
1743        let c = CellContent::from_grapheme(id);
1744        let extracted = c.grapheme_id().unwrap();
1745        assert_eq!(extracted.slot(), id.slot());
1746        assert_eq!(extracted.generation(), id.generation());
1747        assert_eq!(extracted.width(), id.width());
1748    }
1749
1750    // -- GraphemeId edge cases --
1751
1752    #[test]
1753    fn grapheme_id_slot_one_width_one() {
1754        let id = GraphemeId::new(1, 0, 1);
1755        assert_eq!(id.slot(), 1);
1756        assert_eq!(id.width(), 1);
1757    }
1758
1759    #[test]
1760    fn grapheme_id_hash_eq_consistency() {
1761        use std::collections::HashSet;
1762        let a = GraphemeId::new(42, 0, 2);
1763        let b = GraphemeId::new(42, 0, 2);
1764        let c = GraphemeId::new(42, 0, 3);
1765        let d = GraphemeId::new(42, 1, 2);
1766        assert_eq!(a, b);
1767        assert_ne!(a, c);
1768        assert_ne!(a, d);
1769        let mut set = HashSet::new();
1770        set.insert(a);
1771        assert!(set.contains(&b));
1772        assert!(!set.contains(&c));
1773        assert!(!set.contains(&d));
1774    }
1775
1776    #[test]
1777    fn grapheme_id_adjacent_slots_differ() {
1778        let a = GraphemeId::new(0, 0, 1);
1779        let b = GraphemeId::new(1, 0, 1);
1780        assert_ne!(a, b);
1781        assert_ne!(a.slot(), b.slot());
1782        assert_eq!(a.width(), b.width());
1783    }
1784
1785    // -- CellAttrs edge cases --
1786
1787    #[test]
1788    fn cell_attrs_link_id_masks_overflow() {
1789        // In release mode (no debug_assert), overflow is masked to 24 bits
1790        let a = CellAttrs::new(StyleFlags::empty(), 0x00FF_FFFE);
1791        assert_eq!(a.link_id(), 0x00FF_FFFE);
1792    }
1793
1794    #[test]
1795    fn cell_attrs_chained_mutations() {
1796        let a = CellAttrs::new(StyleFlags::BOLD, 100)
1797            .with_flags(StyleFlags::ITALIC)
1798            .with_link(200)
1799            .with_flags(StyleFlags::UNDERLINE | StyleFlags::DIM)
1800            .with_link(300);
1801        assert_eq!(a.flags(), StyleFlags::UNDERLINE | StyleFlags::DIM);
1802        assert_eq!(a.link_id(), 300);
1803    }
1804
1805    #[test]
1806    fn cell_attrs_all_flags_max_link() {
1807        let all_flags = StyleFlags::all();
1808        let a = CellAttrs::new(all_flags, CellAttrs::LINK_ID_MAX);
1809        assert_eq!(a.flags(), all_flags);
1810        assert_eq!(a.link_id(), CellAttrs::LINK_ID_MAX);
1811        // Verify no bit overlap: all 8 flag bits set alongside the full
1812        // 24-bit link id (matches LinkRegistry's MAX_LINK_ID).
1813        assert_eq!(a.flags().bits(), 0xFF);
1814        assert_eq!(a.link_id(), 0x00FF_FFFF);
1815    }
1816
1817    #[test]
1818    fn cell_attrs_link_id_none_is_zero() {
1819        assert_eq!(CellAttrs::LINK_ID_NONE, 0);
1820    }
1821
1822    // -- Cell edge cases --
1823
1824    #[test]
1825    fn cell_eq_matches_bits_eq() {
1826        let pairs = [
1827            (Cell::default(), Cell::default()),
1828            (Cell::from_char('A'), Cell::from_char('A')),
1829            (Cell::from_char('A'), Cell::from_char('B')),
1830            (Cell::CONTINUATION, Cell::CONTINUATION),
1831            (
1832                Cell::from_char('X').with_fg(PackedRgba::RED),
1833                Cell::from_char('X').with_fg(PackedRgba::BLUE),
1834            ),
1835        ];
1836        for (a, b) in &pairs {
1837            assert_eq!(
1838                a == b,
1839                a.bits_eq(b),
1840                "PartialEq and bits_eq disagree for {:?} vs {:?}",
1841                a,
1842                b
1843            );
1844        }
1845    }
1846
1847    #[test]
1848    fn cell_from_grapheme_content() {
1849        let id = GraphemeId::new(42, 0, 2);
1850        let cell = Cell::new(CellContent::from_grapheme(id));
1851        assert!(cell.content.is_grapheme());
1852        assert_eq!(cell.width_hint(), 2);
1853        assert!(!cell.is_empty());
1854        assert!(!cell.is_continuation());
1855    }
1856
1857    #[test]
1858    fn cell_with_char_on_continuation() {
1859        let cell = Cell::CONTINUATION.with_char('A');
1860        assert_eq!(cell.content.as_char(), Some('A'));
1861        assert!(!cell.is_continuation());
1862        // Colors from CONTINUATION are preserved
1863        assert_eq!(cell.fg, PackedRgba::TRANSPARENT);
1864        assert_eq!(cell.bg, PackedRgba::TRANSPARENT);
1865    }
1866
1867    #[test]
1868    fn cell_default_bits_eq_self() {
1869        let cell = Cell::default();
1870        assert!(cell.bits_eq(&cell));
1871    }
1872
1873    #[test]
1874    fn cell_new_empty_equals_default() {
1875        let a = Cell::new(CellContent::EMPTY);
1876        let b = Cell::default();
1877        assert!(a.bits_eq(&b));
1878    }
1879
1880    #[test]
1881    fn cell_all_builder_methods_chain() {
1882        let cell = Cell::default()
1883            .with_char('Z')
1884            .with_fg(PackedRgba::rgba(1, 2, 3, 4))
1885            .with_bg(PackedRgba::rgba(5, 6, 7, 8))
1886            .with_attrs(CellAttrs::new(
1887                StyleFlags::BOLD | StyleFlags::STRIKETHROUGH,
1888                999,
1889            ));
1890        assert_eq!(cell.content.as_char(), Some('Z'));
1891        assert_eq!(cell.fg.r(), 1);
1892        assert_eq!(cell.bg.a(), 8);
1893        assert!(cell.attrs.has_flag(StyleFlags::BOLD));
1894        assert!(cell.attrs.has_flag(StyleFlags::STRIKETHROUGH));
1895        assert!(!cell.attrs.has_flag(StyleFlags::ITALIC));
1896        assert_eq!(cell.attrs.link_id(), 999);
1897    }
1898
1899    #[test]
1900    fn cell_size_and_alignment_invariants() {
1901        // Non-negotiable: 16 bytes, 16-byte aligned
1902        assert_eq!(core::mem::size_of::<Cell>(), 16);
1903        assert_eq!(core::mem::align_of::<Cell>(), 16);
1904        // 4 cells per 64-byte cache line
1905        assert_eq!(64 / core::mem::size_of::<Cell>(), 4);
1906    }
1907
1908    #[test]
1909    fn cell_content_size_invariant() {
1910        assert_eq!(core::mem::size_of::<CellContent>(), 4);
1911    }
1912
1913    #[test]
1914    fn cell_attrs_size_invariant() {
1915        assert_eq!(core::mem::size_of::<CellAttrs>(), 4);
1916    }
1917
1918    // -- Porter-Duff over() stress tests --
1919
1920    #[test]
1921    fn over_associativity_approximate() {
1922        // Porter-Duff SourceOver is NOT perfectly associative due to rounding,
1923        // but results should be very close (within 1 per channel)
1924        let a = PackedRgba::rgba(200, 50, 100, 128);
1925        let b = PackedRgba::rgba(50, 200, 50, 128);
1926        let c = PackedRgba::rgba(100, 100, 200, 128);
1927
1928        let ab_c = a.over(b).over(c);
1929        let a_bc = a.over(b.over(c));
1930
1931        // Allow ±1 per channel for rounding differences
1932        assert!(
1933            (ab_c.r() as i16 - a_bc.r() as i16).unsigned_abs() <= 1,
1934            "r: {} vs {}",
1935            ab_c.r(),
1936            a_bc.r()
1937        );
1938        assert!(
1939            (ab_c.g() as i16 - a_bc.g() as i16).unsigned_abs() <= 1,
1940            "g: {} vs {}",
1941            ab_c.g(),
1942            a_bc.g()
1943        );
1944        assert!(
1945            (ab_c.b() as i16 - a_bc.b() as i16).unsigned_abs() <= 1,
1946            "b: {} vs {}",
1947            ab_c.b(),
1948            a_bc.b()
1949        );
1950        assert!(
1951            (ab_c.a() as i16 - a_bc.a() as i16).unsigned_abs() <= 1,
1952            "a: {} vs {}",
1953            ab_c.a(),
1954            a_bc.a()
1955        );
1956    }
1957
1958    #[test]
1959    fn over_output_alpha_monotonic_with_src_alpha() {
1960        // Higher src alpha → higher output alpha (or equal)
1961        let dst = PackedRgba::rgba(0, 0, 255, 128);
1962        let mut prev_a = 0u8;
1963        for alpha in (0..=255).step_by(5) {
1964            let src = PackedRgba::rgba(255, 0, 0, alpha);
1965            let result = src.over(dst);
1966            assert!(
1967                result.a() >= prev_a,
1968                "alpha monotonicity violated at src_a={}: result_a={} < prev={}",
1969                alpha,
1970                result.a(),
1971                prev_a
1972            );
1973            prev_a = result.a();
1974        }
1975    }
1976
1977    #[test]
1978    fn over_sweep_matches_reference() {
1979        // Sweep through alpha values and verify each matches the f64 reference
1980        for alpha in (0..=255).step_by(17) {
1981            let src = PackedRgba::rgba(200, 100, 50, alpha);
1982            let dst = PackedRgba::rgba(50, 100, 200, 200);
1983            assert_eq!(
1984                src.over(dst),
1985                reference_over(src, dst),
1986                "mismatch at src_alpha={}",
1987                alpha
1988            );
1989        }
1990    }
1991}
1992
1993/// Property tests for Cell types (bd-10i.13.2).
1994///
1995/// Top-level `#[cfg(test)]` scope: the `proptest!` macro has edition-2024
1996/// compatibility issues when nested inside another test module.
1997#[cfg(test)]
1998mod cell_proptests {
1999    use super::{Cell, CellAttrs, CellContent, GraphemeId, PackedRgba, StyleFlags};
2000    use proptest::prelude::*;
2001
2002    fn arb_packed_rgba() -> impl Strategy<Value = PackedRgba> {
2003        (any::<u8>(), any::<u8>(), any::<u8>(), any::<u8>())
2004            .prop_map(|(r, g, b, a)| PackedRgba::rgba(r, g, b, a))
2005    }
2006
2007    fn arb_grapheme_id() -> impl Strategy<Value = GraphemeId> {
2008        (
2009            0u32..=GraphemeId::MAX_SLOT,
2010            0u16..=GraphemeId::MAX_GENERATION,
2011            0u8..=GraphemeId::MAX_WIDTH,
2012        )
2013            .prop_map(|(slot, generation, width)| GraphemeId::new(slot, generation, width))
2014    }
2015
2016    fn arb_style_flags() -> impl Strategy<Value = StyleFlags> {
2017        any::<u8>().prop_map(StyleFlags::from_bits_truncate)
2018    }
2019
2020    proptest! {
2021        #[test]
2022        fn packed_rgba_roundtrips_all_components(tuple in (any::<u8>(), any::<u8>(), any::<u8>(), any::<u8>())) {
2023            let (r, g, b, a) = tuple;
2024            let c = PackedRgba::rgba(r, g, b, a);
2025            prop_assert_eq!(c.r(), r);
2026            prop_assert_eq!(c.g(), g);
2027            prop_assert_eq!(c.b(), b);
2028            prop_assert_eq!(c.a(), a);
2029        }
2030
2031        #[test]
2032        fn packed_rgba_rgb_always_opaque(tuple in (any::<u8>(), any::<u8>(), any::<u8>())) {
2033            let (r, g, b) = tuple;
2034            let c = PackedRgba::rgb(r, g, b);
2035            prop_assert_eq!(c.a(), 255);
2036            prop_assert_eq!(c.r(), r);
2037            prop_assert_eq!(c.g(), g);
2038            prop_assert_eq!(c.b(), b);
2039        }
2040
2041        #[test]
2042        fn packed_rgba_over_identity_transparent(dst in arb_packed_rgba()) {
2043            // Transparent source leaves destination unchanged
2044            let result = PackedRgba::TRANSPARENT.over(dst);
2045            prop_assert_eq!(result, dst);
2046        }
2047
2048        #[test]
2049        fn packed_rgba_over_identity_opaque(tuple in (any::<u8>(), any::<u8>(), any::<u8>(), arb_packed_rgba())) {
2050            // Fully opaque source replaces destination
2051            let (r, g, b, dst) = tuple;
2052            let src = PackedRgba::rgba(r, g, b, 255);
2053            let result = src.over(dst);
2054            prop_assert_eq!(result, src);
2055        }
2056
2057        #[test]
2058        fn grapheme_id_components_roundtrip(
2059            tuple in (
2060                0u32..=GraphemeId::MAX_SLOT,
2061                0u16..=GraphemeId::MAX_GENERATION,
2062                0u8..=GraphemeId::MAX_WIDTH,
2063            )
2064        ) {
2065            let (slot, generation, width) = tuple;
2066            let id = GraphemeId::new(slot, generation, width);
2067            prop_assert_eq!(id.slot(), slot as usize);
2068            prop_assert_eq!(id.generation(), generation);
2069            prop_assert_eq!(id.width(), width as usize);
2070        }
2071
2072        #[test]
2073        fn grapheme_id_raw_roundtrip(id in arb_grapheme_id()) {
2074            let raw = id.raw();
2075            let restored = GraphemeId::from_raw(raw);
2076            prop_assert_eq!(restored.slot(), id.slot());
2077            prop_assert_eq!(restored.width(), id.width());
2078        }
2079
2080        #[test]
2081        fn cell_content_char_roundtrip(c in (0x20u32..0xD800u32).prop_union(0xE000u32..0x110000u32)) {
2082            if let Some(ch) = char::from_u32(c) {
2083                let content = CellContent::from_char(ch);
2084                prop_assert_eq!(content.as_char(), Some(ch));
2085                prop_assert!(!content.is_grapheme());
2086                prop_assert!(!content.is_empty());
2087                prop_assert!(!content.is_continuation());
2088            }
2089        }
2090
2091        #[test]
2092        fn cell_content_grapheme_roundtrip(id in arb_grapheme_id()) {
2093            let content = CellContent::from_grapheme(id);
2094            prop_assert!(content.is_grapheme());
2095            prop_assert_eq!(content.grapheme_id(), Some(id));
2096            prop_assert_eq!(content.width_hint(), id.width());
2097        }
2098
2099        #[test]
2100        fn cell_bits_eq_is_reflexive(
2101            tuple in (
2102                (0x20u32..0x80u32).prop_map(|c| char::from_u32(c).unwrap()),
2103                any::<u8>(), any::<u8>(), any::<u8>(),
2104                arb_style_flags(),
2105            ),
2106        ) {
2107            let (c, r, g, b, flags) = tuple;
2108            let cell = Cell::from_char(c)
2109                .with_fg(PackedRgba::rgb(r, g, b))
2110                .with_attrs(CellAttrs::new(flags, 0));
2111            prop_assert!(cell.bits_eq(&cell));
2112        }
2113
2114        #[test]
2115        fn cell_bits_eq_detects_fg_difference(
2116            tuple in (
2117                (0x41u32..0x5Bu32).prop_map(|c| char::from_u32(c).unwrap()),
2118                any::<u8>(), any::<u8>(),
2119            ),
2120        ) {
2121            let (c, r1, r2) = tuple;
2122            prop_assume!(r1 != r2);
2123            let cell1 = Cell::from_char(c).with_fg(PackedRgba::rgb(r1, 0, 0));
2124            let cell2 = Cell::from_char(c).with_fg(PackedRgba::rgb(r2, 0, 0));
2125            prop_assert!(!cell1.bits_eq(&cell2));
2126        }
2127
2128        #[test]
2129        fn cell_attrs_flags_roundtrip(tuple in (arb_style_flags(), 0u32..CellAttrs::LINK_ID_MAX)) {
2130            let (flags, link) = tuple;
2131            let attrs = CellAttrs::new(flags, link);
2132            prop_assert_eq!(attrs.flags(), flags);
2133            prop_assert_eq!(attrs.link_id(), link);
2134        }
2135
2136        #[test]
2137        fn cell_attrs_with_flags_preserves_link(tuple in (arb_style_flags(), 0u32..CellAttrs::LINK_ID_MAX, arb_style_flags())) {
2138            let (flags, link, new_flags) = tuple;
2139            let attrs = CellAttrs::new(flags, link);
2140            let updated = attrs.with_flags(new_flags);
2141            prop_assert_eq!(updated.flags(), new_flags);
2142            prop_assert_eq!(updated.link_id(), link);
2143        }
2144
2145        #[test]
2146        fn cell_attrs_with_link_preserves_flags(tuple in (arb_style_flags(), 0u32..CellAttrs::LINK_ID_MAX, 0u32..CellAttrs::LINK_ID_MAX)) {
2147            let (flags, link1, link2) = tuple;
2148            let attrs = CellAttrs::new(flags, link1);
2149            let updated = attrs.with_link(link2);
2150            prop_assert_eq!(updated.flags(), flags);
2151            prop_assert_eq!(updated.link_id(), link2);
2152        }
2153
2154        // --- Executable Invariant Tests (bd-10i.13.2) ---
2155
2156        #[test]
2157        fn cell_bits_eq_is_symmetric(
2158            tuple in (
2159                (0x41u32..0x5Bu32).prop_map(|c| char::from_u32(c).unwrap()),
2160                (0x41u32..0x5Bu32).prop_map(|c| char::from_u32(c).unwrap()),
2161                arb_packed_rgba(),
2162                arb_packed_rgba(),
2163            ),
2164        ) {
2165            let (c1, c2, fg1, fg2) = tuple;
2166            let cell_a = Cell::from_char(c1).with_fg(fg1);
2167            let cell_b = Cell::from_char(c2).with_fg(fg2);
2168            prop_assert_eq!(cell_a.bits_eq(&cell_b), cell_b.bits_eq(&cell_a),
2169                "bits_eq is not symmetric");
2170        }
2171
2172        #[test]
2173        fn cell_content_bit31_discriminates(id in arb_grapheme_id()) {
2174            // Char content: bit 31 is 0
2175            let char_content = CellContent::from_char('A');
2176            prop_assert!(!char_content.is_grapheme());
2177            prop_assert!(char_content.as_char().is_some());
2178            prop_assert!(char_content.grapheme_id().is_none());
2179
2180            // Grapheme content: bit 31 is 1
2181            let grapheme_content = CellContent::from_grapheme(id);
2182            prop_assert!(grapheme_content.is_grapheme());
2183            prop_assert!(grapheme_content.grapheme_id().is_some());
2184            prop_assert!(grapheme_content.as_char().is_none());
2185        }
2186
2187        #[test]
2188        fn cell_from_char_width_matches_unicode(
2189            c in (0x20u32..0x7Fu32).prop_map(|c| char::from_u32(c).unwrap()),
2190        ) {
2191            let cell = Cell::from_char(c);
2192            prop_assert_eq!(cell.width_hint(), 1,
2193                "Cell width hint for '{}' should be 1 for ASCII", c);
2194        }
2195    }
2196
2197    // Zero-parameter invariant tests (cannot be inside proptest! macro)
2198
2199    #[test]
2200    fn cell_content_continuation_has_zero_width() {
2201        let cont = CellContent::CONTINUATION;
2202        assert_eq!(cont.width(), 0, "CONTINUATION cell should have width 0");
2203        assert!(cont.is_continuation());
2204        assert!(!cont.is_grapheme());
2205    }
2206
2207    #[test]
2208    fn cell_content_empty_has_zero_width() {
2209        let empty = CellContent::EMPTY;
2210        assert_eq!(empty.width(), 0, "EMPTY cell should have width 0");
2211        assert!(empty.is_empty());
2212        assert!(!empty.is_grapheme());
2213        assert!(!empty.is_continuation());
2214    }
2215
2216    #[test]
2217    fn cell_default_is_empty() {
2218        let cell = Cell::default();
2219        assert!(cell.is_empty());
2220        assert_eq!(cell.width_hint(), 0);
2221    }
2222}
2223
2224#[cfg(test)]
2225mod bit_layout_tests {
2226    use super::GraphemeId;
2227
2228    #[test]
2229    fn grapheme_id_bit_layout_verification() {
2230        // Layout verification to match corrected documentation:
2231        // [30-27: width (4 bits)][26-16: generation (11 bits)][15-0: pool slot (16 bits)]
2232
2233        // Slot = 0xFFFF (max 16 bits)
2234        let t1 = GraphemeId::new(0xFFFF, 0, 0);
2235        assert_eq!(t1.raw(), 0xFFFF, "Slot 0xFFFF should be 0xFFFF");
2236
2237        // Generation = 0x7FF (max 11 bits)
2238        let t2 = GraphemeId::new(0, 0x7FF, 0);
2239        // 0x7FF << 16 = 0x07FF0000
2240        assert_eq!(t2.raw(), 0x07FF0000, "Gen 0x7FF should be 0x07FF0000");
2241
2242        // Width = 0xF (max 4 bits)
2243        let t3 = GraphemeId::new(0, 0, 0xF);
2244        // 0xF << 27 = 0x78000000
2245        assert_eq!(t3.raw(), 0x78000000, "Width 0xF should be 0x78000000");
2246
2247        // Combined max values
2248        let t4 = GraphemeId::new(0xFFFF, 0x7FF, 0xF);
2249        // 0x78000000 | 0x07FF0000 | 0xFFFF = 0x7FFFFFFF
2250        assert_eq!(
2251            t4.raw(),
2252            0x7FFFFFFF,
2253            "Combined max values should be 0x7FFFFFFF"
2254        );
2255
2256        // Ensure bit 31 is clear (reserved for CellContent discriminator)
2257        assert_eq!(t4.raw() & 0x80000000, 0, "Bit 31 must be clear");
2258    }
2259}