Skip to main content

ftui_render/
buffer.rs

1#![forbid(unsafe_code)]
2
3//! Buffer grid storage.
4//!
5//! The `Buffer` is a 2D grid of [`Cell`]s representing the terminal display.
6//! It provides efficient cell access, scissor (clipping) regions, and opacity
7//! stacks for compositing.
8//!
9//! # Layout
10//!
11//! Cells are stored in row-major order: `index = y * width + x`.
12//!
13//! # Invariants
14//!
15//! 1. `cells.len() == width * height`
16//! 2. Width and height never change after creation
17//! 3. Scissor stack intersection monotonically decreases on push
18//! 4. Opacity stack product stays in `[0.0, 1.0]`
19//! 5. Scissor/opacity stacks always have at least one element
20//!
21//! # Dirty Row Tracking (bd-4kq0.1.1)
22//!
23//! ## Mathematical Invariant
24//!
25//! Let D be the set of dirty rows. The fundamental soundness property:
26//!
27//! ```text
28//! ∀ y ∈ [0, height): if ∃ x such that old(x, y) ≠ new(x, y), then y ∈ D
29//! ```
30//!
31//! This ensures the diff algorithm can safely skip non-dirty rows without
32//! missing any changes. The invariant is maintained by marking rows dirty
33//! on every cell mutation.
34//!
35//! ## Bookkeeping Cost
36//!
37//! - O(1) per mutation (single array write)
38//! - O(height) space for dirty bitmap
39//! - Target: < 2% overhead vs baseline rendering
40//!
41//! # Dirty Span Tracking (bd-3e1t.6.2)
42//!
43//! Dirty spans refine dirty rows by recording per-row x-ranges of mutations.
44//!
45//! ## Invariant
46//!
47//! ```text
48//! ∀ (x, y) mutated since last clear, ∃ span in row y with x ∈ [x0, x1)
49//! ```
50//!
51//! Spans are sorted, non-overlapping, and merged when overlapping, adjacent, or separated
52//! by at most `DIRTY_SPAN_MERGE_GAP` cells (gap becomes dirty). If a row exceeds
53//! `DIRTY_SPAN_MAX_SPANS_PER_ROW`, it falls back to full-row scan.
54
55use smallvec::SmallVec;
56
57use crate::budget::DegradationLevel;
58use crate::cell::{Cell, GraphemeId};
59use ftui_core::geometry::Rect;
60
61/// Maximum number of dirty spans per row before falling back to full-row scan.
62const DIRTY_SPAN_MAX_SPANS_PER_ROW: usize = 64;
63/// Merge spans when the gap between them is at most this many cells.
64const DIRTY_SPAN_MERGE_GAP: u16 = 1;
65
66/// Configuration for dirty-span tracking.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct DirtySpanConfig {
69    /// Enable dirty-span tracking (used by diff).
70    pub enabled: bool,
71    /// Maximum spans per row before falling back to full-row scan.
72    pub max_spans_per_row: usize,
73    /// Merge spans when the gap between them is at most this many cells.
74    pub merge_gap: u16,
75    /// Expand spans by this many cells on each side.
76    pub guard_band: u16,
77}
78
79impl Default for DirtySpanConfig {
80    fn default() -> Self {
81        Self {
82            enabled: true,
83            max_spans_per_row: DIRTY_SPAN_MAX_SPANS_PER_ROW,
84            merge_gap: DIRTY_SPAN_MERGE_GAP,
85            guard_band: 0,
86        }
87    }
88}
89
90impl DirtySpanConfig {
91    /// Toggle dirty-span tracking.
92    #[must_use]
93    pub fn with_enabled(mut self, enabled: bool) -> Self {
94        self.enabled = enabled;
95        self
96    }
97
98    /// Set max spans per row before fallback.
99    #[must_use]
100    pub fn with_max_spans_per_row(mut self, max_spans: usize) -> Self {
101        self.max_spans_per_row = max_spans;
102        self
103    }
104
105    /// Set merge gap threshold.
106    #[must_use]
107    pub fn with_merge_gap(mut self, merge_gap: u16) -> Self {
108        self.merge_gap = merge_gap;
109        self
110    }
111
112    /// Set guard band expansion (cells).
113    #[must_use]
114    pub fn with_guard_band(mut self, guard_band: u16) -> Self {
115        self.guard_band = guard_band;
116        self
117    }
118}
119
120/// Half-open dirty span [x0, x1) for a single row.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub(crate) struct DirtySpan {
123    pub x0: u16,
124    pub x1: u16,
125}
126
127impl DirtySpan {
128    #[inline]
129    pub const fn new(x0: u16, x1: u16) -> Self {
130        Self { x0, x1 }
131    }
132
133    #[inline]
134    pub const fn len(self) -> usize {
135        self.x1.saturating_sub(self.x0) as usize
136    }
137}
138
139#[derive(Debug, Default, Clone)]
140pub(crate) struct DirtySpanRow {
141    overflow: bool,
142    /// Inline storage for up to 4 spans (16 bytes) avoids heap allocation for ~90% of rows.
143    spans: SmallVec<[DirtySpan; 4]>,
144}
145
146impl DirtySpanRow {
147    #[inline]
148    fn new_full() -> Self {
149        Self {
150            overflow: true,
151            spans: SmallVec::new(),
152        }
153    }
154
155    #[inline]
156    fn clear(&mut self) {
157        self.overflow = false;
158        self.spans.clear();
159    }
160
161    #[inline]
162    fn set_full(&mut self) {
163        self.overflow = true;
164        self.spans.clear();
165    }
166
167    #[inline(always)]
168    pub(crate) fn spans(&self) -> &[DirtySpan] {
169        &self.spans
170    }
171
172    #[inline(always)]
173    pub(crate) fn is_full(&self) -> bool {
174        self.overflow
175    }
176
177    #[inline(always)]
178    pub(crate) fn is_dirty(&self) -> bool {
179        self.overflow || !self.spans.is_empty()
180    }
181}
182
183/// Dirty-span statistics for logging/telemetry.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct DirtySpanStats {
186    /// Rows marked as full-row dirty.
187    pub rows_full_dirty: usize,
188    /// Rows with at least one span.
189    pub rows_with_spans: usize,
190    /// Total number of spans across all rows.
191    pub total_spans: usize,
192    /// Total number of span overflow events since last clear.
193    pub overflows: usize,
194    /// Total coverage in cells (span lengths + full rows).
195    pub span_coverage_cells: usize,
196    /// Maximum span length observed (including full-row spans).
197    pub max_span_len: usize,
198    /// Configured max spans per row.
199    pub max_spans_per_row: usize,
200}
201
202/// A 2D grid of terminal cells.
203///
204/// # Example
205///
206/// ```
207/// use ftui_render::buffer::Buffer;
208/// use ftui_render::cell::Cell;
209///
210/// let mut buffer = Buffer::new(80, 24);
211/// buffer.set(0, 0, Cell::from_char('H'));
212/// buffer.set(1, 0, Cell::from_char('i'));
213/// ```
214#[derive(Clone)]
215pub struct Buffer {
216    width: u16,
217    height: u16,
218    cells: Vec<Cell>,
219    scissor_stack: Vec<Rect>,
220    opacity_stack: Vec<f32>,
221    /// Current degradation level for this frame.
222    ///
223    /// Widgets read this during rendering to decide how much visual fidelity
224    /// to provide. Set by the runtime before calling `Model::view()`.
225    pub degradation: DegradationLevel,
226    /// Per-row dirty flags for diff optimization.
227    ///
228    /// When a row is marked dirty, the diff algorithm must compare it cell-by-cell.
229    /// Clean rows can be skipped entirely.
230    ///
231    /// Invariant: `dirty_rows.len() == height`
232    dirty_rows: Vec<bool>,
233    /// Per-row dirty span tracking for sparse diff scans.
234    dirty_spans: Vec<DirtySpanRow>,
235    /// Dirty-span tracking configuration.
236    dirty_span_config: DirtySpanConfig,
237    /// Number of span overflow events since the last `clear_dirty()`.
238    dirty_span_overflows: usize,
239    /// Per-cell dirty bitmap for tile-based diff skipping.
240    dirty_bits: Vec<u8>,
241    /// Count of dirty cells tracked in the bitmap.
242    dirty_cells: usize,
243    /// Whether the whole buffer is marked dirty (bitmap may be stale).
244    dirty_all: bool,
245    /// Deterministic mutation generation token for dirty-witness baseline checks.
246    mutation_gen: u64,
247    /// Mutation generation recorded at the last `clear_dirty()`, or `None` when full-dirty.
248    dirty_baseline_gen: Option<u64>,
249}
250
251impl std::fmt::Debug for Buffer {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct("Buffer")
254            .field("width", &self.width)
255            .field("height", &self.height)
256            .field("cells", &self.cells)
257            .field("scissor_stack", &self.scissor_stack)
258            .field("opacity_stack", &self.opacity_stack)
259            .field("degradation", &self.degradation)
260            .field("dirty_rows", &self.dirty_rows)
261            .field("dirty_spans", &self.dirty_spans)
262            .field("dirty_span_config", &self.dirty_span_config)
263            .field("dirty_span_overflows", &self.dirty_span_overflows)
264            .field("dirty_bits", &self.dirty_bits)
265            .field("dirty_cells", &self.dirty_cells)
266            .field("dirty_all", &self.dirty_all)
267            .finish()
268    }
269}
270
271impl Buffer {
272    /// Create a new buffer with the given dimensions.
273    ///
274    /// All cells are initialized to the default (empty cell with white
275    /// foreground and transparent background).
276    ///
277    /// Dimensions are clamped to a minimum of 1x1 to prevent panics during
278    /// extreme window resizes.
279    pub fn new(width: u16, height: u16) -> Self {
280        let width = width.max(1);
281        let height = height.max(1);
282
283        let size = width as usize * height as usize;
284        let cells = vec![Cell::default(); size];
285
286        let dirty_spans = (0..height)
287            .map(|_| DirtySpanRow::new_full())
288            .collect::<Vec<_>>();
289        let dirty_bits = vec![0u8; size];
290        let dirty_cells = size;
291        let dirty_all = true;
292
293        Self {
294            width,
295            height,
296            cells,
297            scissor_stack: vec![Rect::from_size(width, height)],
298            opacity_stack: vec![1.0],
299            degradation: DegradationLevel::Full,
300            // All rows start dirty to ensure initial diffs against this buffer
301            // (e.g. from DoubleBuffer resize) correctly identify it as changed/empty.
302            dirty_rows: vec![true; height as usize],
303            // Start with full-row dirty spans to force initial full scan.
304            dirty_spans,
305            dirty_span_config: DirtySpanConfig::default(),
306            dirty_span_overflows: 0,
307            dirty_bits,
308            dirty_cells,
309            dirty_all,
310            mutation_gen: 0,
311            dirty_baseline_gen: None,
312        }
313    }
314
315    /// Buffer width in cells.
316    #[inline]
317    pub const fn width(&self) -> u16 {
318        self.width
319    }
320
321    /// Buffer height in cells.
322    #[inline]
323    pub const fn height(&self) -> u16 {
324        self.height
325    }
326
327    /// Total number of cells.
328    #[inline]
329    pub fn len(&self) -> usize {
330        self.cells.len()
331    }
332
333    /// Check if the buffer is empty (should never be true for valid buffers).
334    #[inline]
335    pub fn is_empty(&self) -> bool {
336        self.cells.is_empty()
337    }
338
339    /// Bounding rect of the entire buffer.
340    #[inline]
341    pub const fn bounds(&self) -> Rect {
342        Rect::from_size(self.width, self.height)
343    }
344
345    /// Return the height of content (last non-empty row + 1).
346    ///
347    /// Rows are considered empty only if all cells are the default cell.
348    /// Returns 0 if the buffer contains no content.
349    #[inline]
350    pub fn content_height(&self) -> u16 {
351        let default_cell = Cell::default();
352        let width = self.width as usize;
353        for y in (0..self.height).rev() {
354            let row_start = y as usize * width;
355            let row_end = row_start + width;
356            if self.cells[row_start..row_end]
357                .iter()
358                .any(|cell| *cell != default_cell)
359            {
360                return y + 1;
361            }
362        }
363        0
364    }
365
366    /// Compute the 64-bit FNV-1a checksum over each cell's 16 bytes in row-major order.
367    ///
368    /// This is the canonical shadow-run / golden frame checksum shared between
369    /// `ftui-runtime` (`RolloutPolicy::Shadow`) and `ftui-harness`.
370    #[inline]
371    #[must_use]
372    pub fn checksum(&self) -> u64 {
373        buffer_checksum(self)
374    }
375
376    // ----- Dirty Tracking API -----
377
378    #[inline]
379    fn advance_mutation_gen(&mut self, token: u64) {
380        self.mutation_gen = self
381            .mutation_gen
382            .wrapping_add(token.wrapping_add(0x9E37_79B9_7F4A_7C15))
383            .wrapping_mul(0xBF58_476D_1CE4_E5B9);
384    }
385
386    /// Mark a row as dirty (modified since last clear).
387    ///
388    /// This is O(1) and must be called on every cell mutation to maintain
389    /// the dirty-soundness invariant.
390    #[inline]
391    fn mark_dirty_row(&mut self, y: u16) {
392        if let Some(slot) = self.dirty_rows.get_mut(y as usize) {
393            *slot = true;
394        }
395    }
396
397    /// Mark a range of cells in a row as dirty in the bitmap (end exclusive).
398    #[inline]
399    fn mark_dirty_bits_range(&mut self, y: u16, start: u16, end: u16) {
400        if self.dirty_all {
401            return;
402        }
403        if y >= self.height {
404            return;
405        }
406
407        let width = self.width;
408        if start >= width {
409            return;
410        }
411        let end = end.min(width);
412        if start >= end {
413            return;
414        }
415
416        let row_start = y as usize * width as usize;
417        let slice = &mut self.dirty_bits[row_start + start as usize..row_start + end as usize];
418        let newly_dirty = slice.iter().filter(|&&b| b == 0).count();
419        slice.fill(1);
420        self.dirty_cells = self.dirty_cells.saturating_add(newly_dirty);
421    }
422
423    /// Mark an entire row as dirty in the bitmap.
424    #[inline]
425    fn mark_dirty_bits_row(&mut self, y: u16) {
426        self.mark_dirty_bits_range(y, 0, self.width);
427    }
428
429    /// Mark a row as fully dirty (full scan).
430    #[inline]
431    fn mark_dirty_row_full(&mut self, y: u16) {
432        if y >= self.height {
433            return;
434        }
435        let sample = self
436            .cells
437            .get(y as usize * self.width as usize)
438            .map_or(0, |c| {
439                u64::from(c.content.raw()) ^ (u64::from(c.fg.0) << 32)
440            });
441        self.advance_mutation_gen((u64::from(y) << 48) | (u64::from(self.width) << 32) ^ sample);
442        if self.dirty_all {
443            return;
444        }
445        self.mark_dirty_row(y);
446        if self.dirty_span_config.enabled
447            && let Some(row) = self.dirty_spans.get_mut(y as usize)
448        {
449            row.set_full();
450        }
451        self.mark_dirty_bits_row(y);
452    }
453
454    /// Mark a span within a row as dirty (half-open).
455    #[inline]
456    pub(crate) fn mark_dirty_span(&mut self, y: u16, x0: u16, x1: u16) {
457        if y >= self.height {
458            return;
459        }
460        let width = self.width;
461        let (start, mut end) = if x0 <= x1 { (x0, x1) } else { (x1, x0) };
462        if start >= width {
463            return;
464        }
465        if end > width {
466            end = width;
467        }
468        if start >= end {
469            return;
470        }
471
472        let sample = self
473            .cells
474            .get(y as usize * width as usize + start as usize)
475            .map_or(0, |c| {
476                u64::from(c.content.raw()) ^ (u64::from(c.fg.0) << 32)
477            });
478        self.advance_mutation_gen(
479            ((u64::from(y) << 48) | (u64::from(start) << 32) | u64::from(end)) ^ sample,
480        );
481        if self.dirty_all {
482            return;
483        }
484        self.mark_dirty_row(y);
485        self.mark_dirty_bits_range(y, start, end);
486
487        if !self.dirty_span_config.enabled {
488            return;
489        }
490
491        let guard_band = self.dirty_span_config.guard_band;
492        let span_start = start.saturating_sub(guard_band);
493        let mut span_end = end.saturating_add(guard_band);
494        if span_end > width {
495            span_end = width;
496        }
497        if span_start >= span_end {
498            return;
499        }
500
501        let Some(row) = self.dirty_spans.get_mut(y as usize) else {
502            return;
503        };
504
505        if row.is_full() {
506            return;
507        }
508
509        let new_span = DirtySpan::new(span_start, span_end);
510        let spans = &mut row.spans;
511        let insert_at = spans.partition_point(|span| span.x0 <= new_span.x0);
512        spans.insert(insert_at, new_span);
513
514        // Merge overlapping or near-adjacent spans (gap <= merge_gap).
515        let merge_gap = self.dirty_span_config.merge_gap;
516        let mut i = if insert_at > 0 { insert_at - 1 } else { 0 };
517        while i + 1 < spans.len() {
518            let current = spans[i];
519            let next = spans[i + 1];
520            let merge_limit = current.x1.saturating_add(merge_gap);
521            if merge_limit >= next.x0 {
522                spans[i].x1 = current.x1.max(next.x1);
523                spans.remove(i + 1);
524                continue;
525            }
526            i += 1;
527        }
528
529        if spans.len() > self.dirty_span_config.max_spans_per_row {
530            row.set_full();
531            self.dirty_span_overflows = self.dirty_span_overflows.saturating_add(1);
532        }
533    }
534
535    /// Mark all rows as dirty (e.g., after a full clear or bulk write).
536    #[inline]
537    pub fn mark_all_dirty(&mut self) {
538        self.advance_mutation_gen((u64::from(self.height) << 32) | u64::from(self.width));
539        self.dirty_rows.fill(true);
540        if self.dirty_span_config.enabled {
541            for row in &mut self.dirty_spans {
542                row.set_full();
543            }
544        } else {
545            for row in &mut self.dirty_spans {
546                row.clear();
547            }
548        }
549        self.dirty_all = true;
550        self.dirty_cells = self.cells.len();
551        self.dirty_baseline_gen = None;
552    }
553
554    /// Reset all dirty flags and spans to clean.
555    ///
556    /// Call this after the diff has consumed the dirty state (between frames).
557    #[inline]
558    pub fn clear_dirty(&mut self) {
559        self.dirty_rows.fill(false);
560        for row in &mut self.dirty_spans {
561            row.clear();
562        }
563        self.dirty_span_overflows = 0;
564        self.dirty_bits.fill(0);
565        self.dirty_cells = 0;
566        self.dirty_all = false;
567        self.dirty_baseline_gen = Some(self.mutation_gen);
568    }
569
570    /// Check if a specific row is dirty.
571    #[inline]
572    pub fn is_row_dirty(&self, y: u16) -> bool {
573        self.dirty_rows.get(y as usize).copied().unwrap_or(false)
574    }
575
576    /// Get the dirty row flags as a slice.
577    ///
578    /// Each element corresponds to a row: `true` means the row was modified
579    /// since the last `clear_dirty()` call.
580    #[inline]
581    pub fn dirty_rows(&self) -> &[bool] {
582        &self.dirty_rows
583    }
584
585    /// Count the number of dirty rows.
586    #[inline]
587    pub fn dirty_row_count(&self) -> usize {
588        self.dirty_rows.iter().filter(|&&d| d).count()
589    }
590
591    /// Indices of dirty rows in ascending order (the witness consumed by the
592    /// render-certificate narrow path).
593    #[must_use]
594    pub fn dirty_row_indices(&self) -> Vec<u16> {
595        self.dirty_rows
596            .iter()
597            .enumerate()
598            .filter_map(|(y, &dirty)| dirty.then_some(y as u16))
599            .collect()
600    }
601
602    /// Generation token of mutations applied to this buffer's cells.
603    #[inline]
604    #[must_use]
605    pub const fn mutation_gen(&self) -> u64 {
606        self.mutation_gen
607    }
608
609    /// Generation token recorded at the last [`clear_dirty`](Self::clear_dirty) call,
610    /// or `None` when the buffer is in full-dirty state.
611    #[inline]
612    #[must_use]
613    pub const fn dirty_baseline_gen(&self) -> Option<u64> {
614        self.dirty_baseline_gen
615    }
616
617    /// Count of rows with non-empty or full dirty spans.
618    ///
619    /// When dirty-span tracking is disabled, falls back to [`dirty_row_count`](Self::dirty_row_count).
620    #[must_use]
621    pub fn dirty_span_row_count(&self) -> usize {
622        if !self.dirty_span_config.enabled {
623            return self.dirty_row_count();
624        }
625        self.dirty_spans.iter().filter(|row| row.is_dirty()).count()
626    }
627
628    /// Verify internal consistency across `dirty_rows`, `dirty_spans`, and `dirty_cells`.
629    #[must_use]
630    pub fn is_dirty_witness_consistent(&self) -> bool {
631        let height = self.height as usize;
632        if self.dirty_rows.len() != height || self.dirty_spans.len() != height {
633            return false;
634        }
635        let dirty_row_count = self.dirty_row_count();
636        if dirty_row_count == 0 {
637            if self.dirty_all || self.dirty_cells != 0 {
638                return false;
639            }
640            if self.dirty_span_config.enabled && self.dirty_spans.iter().any(DirtySpanRow::is_dirty)
641            {
642                return false;
643            }
644            return true;
645        }
646        if self.dirty_cells < dirty_row_count {
647            return false;
648        }
649        if self.dirty_all && (dirty_row_count != height || self.dirty_cells != self.cells.len()) {
650            return false;
651        }
652        if self.dirty_span_config.enabled {
653            for (y, &row_dirty) in self.dirty_rows.iter().enumerate() {
654                if row_dirty != self.dirty_spans[y].is_dirty() {
655                    return false;
656                }
657            }
658        }
659        true
660    }
661
662    /// Verify that this buffer's dirty tracking is a sound witness for diffing against `old`.
663    ///
664    /// Cross-checks `dirty_rows` against `dirty_spans` and `dirty_cells`, and verifies
665    /// that either `self` is marked fully dirty (`dirty_all`) or `self`'s dirty state
666    /// was cleared (`clear_dirty`) at the exact mutation generation of `old`.
667    #[must_use]
668    pub fn is_dirty_witness_valid_for(&self, old: &Buffer) -> bool {
669        if self.width != old.width || self.height != old.height {
670            return false;
671        }
672        if !self.is_dirty_witness_consistent() {
673            return false;
674        }
675        match self.dirty_baseline_gen {
676            Some(base_gen) => base_gen == old.mutation_gen || base_gen == 0,
677            None => self.dirty_all && self.dirty_row_count() == self.height as usize,
678        }
679    }
680
681    /// Collect dirty-row indices and validate the dirty witness against `old` in a single pass.
682    #[inline]
683    pub(crate) fn collect_dirty_witness_for(&self, old: &Buffer) -> (usize, usize, bool, Vec<u16>) {
684        let height = self.height as usize;
685        let span_enabled = self.dirty_span_config.enabled;
686        let mut dirty_rows = Vec::new();
687        let mut span_dirty_rows = 0usize;
688
689        for y in 0..height {
690            let row_dirty = self.dirty_rows.get(y).copied().unwrap_or(false);
691            if row_dirty {
692                dirty_rows.push(y as u16);
693            }
694            if span_enabled {
695                if self.dirty_spans.get(y).is_some_and(DirtySpanRow::is_dirty) {
696                    span_dirty_rows += 1;
697                }
698            } else if row_dirty {
699                span_dirty_rows += 1;
700            }
701        }
702
703        let dirty_row_count = dirty_rows.len();
704        let consistent = self.width == old.width
705            && self.height == old.height
706            && self.dirty_rows.len() == height
707            && self.dirty_spans.len() == height
708            && span_dirty_rows == dirty_row_count
709            && if dirty_row_count == 0 {
710                !self.dirty_all && self.dirty_cells == 0
711            } else {
712                self.dirty_cells >= dirty_row_count
713                    && (!self.dirty_all
714                        || (dirty_row_count == height && self.dirty_cells == self.cells.len()))
715            };
716
717        let baseline_valid = consistent
718            && match self.dirty_baseline_gen {
719                Some(base_gen) => base_gen == old.mutation_gen || base_gen == 0,
720                None => self.dirty_all && dirty_row_count == height,
721            };
722
723        (dirty_row_count, span_dirty_rows, baseline_valid, dirty_rows)
724    }
725
726    /// Access the per-cell dirty bitmap (0 = clean, 1 = dirty).
727    #[inline]
728    #[allow(dead_code)]
729    pub(crate) fn dirty_bits(&self) -> &[u8] {
730        &self.dirty_bits
731    }
732
733    /// Count of dirty cells tracked in the bitmap.
734    #[inline]
735    #[allow(dead_code)]
736    pub(crate) fn dirty_cell_count(&self) -> usize {
737        self.dirty_cells
738    }
739
740    /// Whether the whole buffer is marked dirty (bitmap may be stale).
741    #[inline]
742    #[allow(dead_code)]
743    pub(crate) fn dirty_all(&self) -> bool {
744        self.dirty_all
745    }
746
747    /// Access a row's dirty span state.
748    #[inline(always)]
749    #[allow(dead_code)]
750    pub(crate) fn dirty_span_row(&self, y: u16) -> Option<&DirtySpanRow> {
751        if !self.dirty_span_config.enabled {
752            return None;
753        }
754        self.dirty_spans.get(y as usize)
755    }
756
757    /// Summarize dirty-span stats for logging/telemetry.
758    pub fn dirty_span_stats(&self) -> DirtySpanStats {
759        if !self.dirty_span_config.enabled {
760            return DirtySpanStats {
761                rows_full_dirty: 0,
762                rows_with_spans: 0,
763                total_spans: 0,
764                overflows: 0,
765                span_coverage_cells: 0,
766                max_span_len: 0,
767                max_spans_per_row: self.dirty_span_config.max_spans_per_row,
768            };
769        }
770
771        let mut rows_full_dirty = 0usize;
772        let mut rows_with_spans = 0usize;
773        let mut total_spans = 0usize;
774        let mut span_coverage_cells = 0usize;
775        let mut max_span_len = 0usize;
776
777        for row in &self.dirty_spans {
778            if row.is_full() {
779                rows_full_dirty += 1;
780                span_coverage_cells += self.width as usize;
781                max_span_len = max_span_len.max(self.width as usize);
782                continue;
783            }
784            if !row.spans().is_empty() {
785                rows_with_spans += 1;
786            }
787            total_spans += row.spans().len();
788            for span in row.spans() {
789                span_coverage_cells += span.len();
790                max_span_len = max_span_len.max(span.len());
791            }
792        }
793
794        DirtySpanStats {
795            rows_full_dirty,
796            rows_with_spans,
797            total_spans,
798            overflows: self.dirty_span_overflows,
799            span_coverage_cells,
800            max_span_len,
801            max_spans_per_row: self.dirty_span_config.max_spans_per_row,
802        }
803    }
804
805    /// Access the dirty-span configuration.
806    #[inline]
807    pub fn dirty_span_config(&self) -> DirtySpanConfig {
808        self.dirty_span_config
809    }
810
811    /// Update dirty-span configuration.
812    ///
813    /// Existing span records were built under the old config, so they are
814    /// replaced conservatively: every currently dirty row goes to full-row
815    /// dirty. Merely clearing the spans (and the full-row overflow flag)
816    /// would break the span soundness invariant — the diff scans only the
817    /// recorded spans of a dirty row, so pre-existing mutations (including a
818    /// fresh buffer's implicit all-dirty state) would silently stop being
819    /// diffed once new mutations record narrower spans.
820    pub fn set_dirty_span_config(&mut self, config: DirtySpanConfig) {
821        if self.dirty_span_config == config {
822            return;
823        }
824        self.dirty_span_config = config;
825        for (y, row) in self.dirty_spans.iter_mut().enumerate() {
826            if self.dirty_rows.get(y).copied().unwrap_or(false) {
827                row.set_full();
828            } else {
829                row.clear();
830            }
831        }
832        self.dirty_span_overflows = 0;
833    }
834
835    // ----- Coordinate Helpers -----
836
837    /// Convert (x, y) coordinates to a linear index.
838    ///
839    /// Returns `None` if coordinates are out of bounds.
840    #[inline]
841    fn index(&self, x: u16, y: u16) -> Option<usize> {
842        if x < self.width && y < self.height {
843            Some(y as usize * self.width as usize + x as usize)
844        } else {
845            None
846        }
847    }
848
849    /// Convert (x, y) coordinates to a linear index without bounds checking.
850    ///
851    /// # Safety
852    ///
853    /// Caller must ensure x < width and y < height.
854    #[inline]
855    pub(crate) fn index_unchecked(&self, x: u16, y: u16) -> usize {
856        debug_assert!(x < self.width && y < self.height);
857        y as usize * self.width as usize + x as usize
858    }
859
860    /// Get mutable reference to a cell at a linear index without bounds checking.
861    ///
862    /// # Safety
863    ///
864    /// Caller must ensure idx < width * height and handle dirty tracking manually.
865    #[inline]
866    pub(crate) fn cell_mut_unchecked(&mut self, idx: usize) -> &mut Cell {
867        &mut self.cells[idx]
868    }
869
870    /// Get a reference to the cell at (x, y).
871    ///
872    /// Returns `None` if coordinates are out of bounds.
873    #[inline]
874    #[must_use]
875    pub fn get(&self, x: u16, y: u16) -> Option<&Cell> {
876        self.index(x, y).map(|i| &self.cells[i])
877    }
878
879    /// Get a mutable reference to the cell at (x, y).
880    ///
881    /// Returns `None` if coordinates are out of bounds.
882    /// Proactively marks the row dirty since the caller may mutate the cell.
883    #[inline]
884    #[must_use]
885    pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut Cell> {
886        let idx = self.index(x, y)?;
887        self.mark_dirty_span(y, x, x.saturating_add(1));
888        Some(&mut self.cells[idx])
889    }
890
891    /// Get a reference to the cell at (x, y) without bounds checking.
892    ///
893    /// # Panics
894    ///
895    /// Panics in debug mode if coordinates are out of bounds.
896    /// May cause undefined behavior in release mode if out of bounds.
897    #[inline]
898    pub fn get_unchecked(&self, x: u16, y: u16) -> &Cell {
899        let i = self.index_unchecked(x, y);
900        &self.cells[i]
901    }
902
903    /// Helper to clean up overlapping multi-width cells before writing.
904    ///
905    /// Returns the half-open span of any cells cleared by this cleanup.
906    #[inline]
907    fn cleanup_overlap(&mut self, x: u16, y: u16, new_cell: &Cell) -> Option<DirtySpan> {
908        let idx = self.index(x, y)?;
909        let current = self.cells[idx];
910        let mut touched = false;
911        let mut min_x = x;
912        let mut max_x = x;
913
914        // Case 1: Overwriting a Wide Head
915        if current.content.width() > 1 {
916            let width = current.content.width();
917            // Clear the head
918            // self.cells[idx] = Cell::default(); // Caller (set) will overwrite this, but for correctness/safety we could.
919            // Actually, `set` overwrites `cells[idx]` immediately after.
920            // But we must clear the tails.
921            for i in 1..width {
922                let Some(cx) = x.checked_add(i as u16) else {
923                    break;
924                };
925                if let Some(tail_idx) = self.index(cx, y)
926                    && self.cells[tail_idx].is_continuation()
927                {
928                    self.cells[tail_idx] = Cell::default();
929                    touched = true;
930                    min_x = min_x.min(cx);
931                    max_x = max_x.max(cx);
932                }
933            }
934        }
935        // Case 2: Overwriting a Continuation
936        else if current.is_continuation() && !new_cell.is_continuation() {
937            let mut back_x = x;
938            // Limit scan to max possible grapheme width to avoid O(N) scan on rows
939            // filled with orphaned continuations.
940            let limit = x.saturating_sub(GraphemeId::MAX_WIDTH as u16);
941
942            while back_x > limit {
943                back_x -= 1;
944                if let Some(h_idx) = self.index(back_x, y) {
945                    let h_cell = self.cells[h_idx];
946                    if !h_cell.is_continuation() {
947                        // Found the potential head
948                        let width = h_cell.content.width();
949                        if (back_x as usize + width) > x as usize {
950                            // This head owns the cell we are overwriting.
951                            // Clear the head.
952                            self.cells[h_idx] = Cell::default();
953                            touched = true;
954                            min_x = min_x.min(back_x);
955                            max_x = max_x.max(back_x);
956
957                            // Clear all its tails (except the one we're about to write, effectively)
958                            // We just iterate 1..width and clear CONTs.
959                            for i in 1..width {
960                                let Some(cx) = back_x.checked_add(i as u16) else {
961                                    break;
962                                };
963                                if let Some(tail_idx) = self.index(cx, y) {
964                                    // Note: tail_idx might be our current `idx`.
965                                    // We can clear it; `set` will overwrite it in a moment.
966                                    if self.cells[tail_idx].is_continuation() {
967                                        self.cells[tail_idx] = Cell::default();
968                                        touched = true;
969                                        min_x = min_x.min(cx);
970                                        max_x = max_x.max(cx);
971                                    }
972                                }
973                            }
974                        }
975                        break;
976                    }
977                }
978            }
979        }
980
981        if touched {
982            Some(DirtySpan::new(min_x, max_x.saturating_add(1)))
983        } else {
984            None
985        }
986    }
987
988    /// Helper to clean up orphaned continuation cells to the right of a write.
989    ///
990    /// If we write a cell at `x`, and `x+1` contains a continuation cell that
991    /// is NOT owned by `x` (which is guaranteed since we just wrote `x`),
992    /// then `x+1` (and subsequent continuations) are orphans. This method
993    /// scans forward and clears them to prevent visual artifacts.
994    #[inline]
995    fn cleanup_orphaned_tails(&mut self, start_x: u16, y: u16) {
996        if start_x >= self.width {
997            return;
998        }
999
1000        // Optimization: check first cell without loop overhead
1001        let Some(idx) = self.index(start_x, y) else {
1002            return;
1003        };
1004        if !self.cells[idx].is_continuation() {
1005            return;
1006        }
1007
1008        // Found an orphan, start scanning
1009        let mut x = start_x;
1010        let mut max_x = x;
1011        let row_end_idx = (y as usize * self.width as usize) + self.width as usize;
1012        let mut curr_idx = idx;
1013
1014        while curr_idx < row_end_idx && self.cells[curr_idx].is_continuation() {
1015            self.cells[curr_idx] = Cell::default();
1016            max_x = x;
1017            x = x.saturating_add(1);
1018            curr_idx += 1;
1019        }
1020
1021        // Mark the cleared range as dirty
1022        self.mark_dirty_span(y, start_x, max_x.saturating_add(1));
1023    }
1024
1025    /// Fast-path cell write for the common case.
1026    ///
1027    /// Bypasses scissor intersection, opacity blending, and overlap cleanup
1028    /// when all of the following hold:
1029    ///
1030    /// - The cell is single-width (`width() <= 1`) and not a continuation
1031    /// - The cell background is either fully opaque or fully transparent
1032    ///   (`bg.a() == 255 || bg.a() == 0`)
1033    /// - Only the base scissor is active (no nested push)
1034    /// - Only the base opacity is active (no nested push)
1035    /// - The existing cell at the target is also single-width and not a continuation
1036    ///
1037    /// Falls through to `set()` for any non-trivial case, so behavior is
1038    /// always identical to calling `set()` directly.
1039    #[inline]
1040    pub fn set_fast(&mut self, x: u16, y: u16, cell: Cell) {
1041        // Bail to full path for wide, continuation, or non-trivial bg alpha cells.
1042        // Must use width() not width_hint(): width_hint() returns 1 for all
1043        // direct chars including CJK, but width() does a proper unicode lookup.
1044        // set() always composites bg over the existing cell (src-over). We can
1045        // skip compositing only when bg alpha is 255 (result is bg) or 0 (result
1046        // is existing bg).
1047        let bg_a = cell.bg.a();
1048        if cell.content.width() > 1 || cell.is_continuation() || (bg_a != 255 && bg_a != 0) {
1049            return self.set(x, y, cell);
1050        }
1051
1052        // Bail if scissor or opacity stacks are non-trivial
1053        if self.scissor_stack.len() != 1 || self.opacity_stack.len() != 1 {
1054            return self.set(x, y, cell);
1055        }
1056
1057        // Bounds check
1058        let Some(idx) = self.index(x, y) else {
1059            return;
1060        };
1061
1062        // Check that existing cell doesn't need overlap cleanup.
1063        // Must use width() for the same reason: a CJK direct char at this
1064        // position would have width() == 2 with a continuation at x+1.
1065        let existing = self.cells[idx];
1066        if existing.content.width() > 1 || existing.is_continuation() {
1067            return self.set(x, y, cell);
1068        }
1069
1070        // All fast-path conditions met: direct write.
1071        //
1072        // bg compositing is safe to skip:
1073        // - alpha 255: bg.over(existing_bg) == bg
1074        // - alpha 0: bg.over(existing_bg) == existing_bg
1075        let mut final_cell = cell;
1076        if bg_a == 0 {
1077            final_cell.bg = existing.bg;
1078        }
1079
1080        self.cells[idx] = final_cell;
1081        self.mark_dirty_span(y, x, x.saturating_add(1));
1082        self.cleanup_orphaned_tails(x.saturating_add(1), y);
1083    }
1084
1085    /// Set the cell at (x, y).
1086    ///
1087    /// This method:
1088    /// - Respects the current scissor region (skips if outside)
1089    /// - Applies the current opacity stack to cell colors
1090    /// - Does nothing if coordinates are out of bounds
1091    /// - **Automatically sets CONTINUATION cells** for multi-width content
1092    /// - **Atomic wide writes**: If a wide character doesn't fully fit in the
1093    ///   scissor region/bounds, NOTHING is written.
1094    ///
1095    /// For bulk operations without scissor/opacity/safety, use `set_raw`.
1096    #[inline]
1097    pub fn set(&mut self, x: u16, y: u16, cell: Cell) {
1098        let width = cell.content.width();
1099
1100        // Single cell fast path (width 0 or 1)
1101        if width <= 1 {
1102            // Check bounds
1103            let Some(idx) = self.index(x, y) else {
1104                return;
1105            };
1106
1107            // Check scissor region
1108            if !self.current_scissor().contains(x, y) {
1109                return;
1110            }
1111
1112            // Cleanup overlaps and track any cleared span.
1113            let mut span_start = x;
1114            let mut span_end = x.saturating_add(1);
1115            if let Some(span) = self.cleanup_overlap(x, y, &cell) {
1116                span_start = span_start.min(span.x0);
1117                span_end = span_end.max(span.x1);
1118            }
1119
1120            let existing_bg = self.cells[idx].bg;
1121
1122            // Apply opacity to the incoming cell, then composite over existing background.
1123            let mut final_cell = if self.current_opacity() < 1.0 {
1124                let opacity = self.current_opacity();
1125                Cell {
1126                    fg: cell.fg.with_opacity(opacity),
1127                    bg: cell.bg.with_opacity(opacity),
1128                    ..cell
1129                }
1130            } else {
1131                cell
1132            };
1133
1134            final_cell.bg = final_cell.bg.over(existing_bg);
1135
1136            self.cells[idx] = final_cell;
1137            self.mark_dirty_span(y, span_start, span_end);
1138            self.cleanup_orphaned_tails(x.saturating_add(1), y);
1139            return;
1140        }
1141
1142        // Multi-width character atomicity check
1143        // Ensure ALL cells (head + tail) are within bounds and scissor
1144        let scissor = self.current_scissor();
1145        for i in 0..width {
1146            let Some(cx) = x.checked_add(i as u16) else {
1147                return;
1148            };
1149            // Check bounds
1150            if cx >= self.width || y >= self.height {
1151                return;
1152            }
1153            // Check scissor
1154            if !scissor.contains(cx, y) {
1155                return;
1156            }
1157        }
1158
1159        // If we get here, it's safe to write everything.
1160
1161        // Cleanup overlaps for all cells and track any cleared span.
1162        let mut span_start = x;
1163        let mut span_end = x.saturating_add(width as u16);
1164        if let Some(span) = self.cleanup_overlap(x, y, &cell) {
1165            span_start = span_start.min(span.x0);
1166            span_end = span_end.max(span.x1);
1167        }
1168        for i in 1..width {
1169            // Safe: atomicity check above verified x + i fits in u16
1170            if let Some(span) = self.cleanup_overlap(x + i as u16, y, &Cell::CONTINUATION) {
1171                span_start = span_start.min(span.x0);
1172                span_end = span_end.max(span.x1);
1173            }
1174        }
1175
1176        // 1. Write Head
1177        let idx = self.index_unchecked(x, y);
1178        let old_cell = self.cells[idx];
1179        let mut final_cell = if self.current_opacity() < 1.0 {
1180            let opacity = self.current_opacity();
1181            Cell {
1182                fg: cell.fg.with_opacity(opacity),
1183                bg: cell.bg.with_opacity(opacity),
1184                ..cell
1185            }
1186        } else {
1187            cell
1188        };
1189
1190        // Composite background (src over dst)
1191        final_cell.bg = final_cell.bg.over(old_cell.bg);
1192
1193        self.cells[idx] = final_cell;
1194
1195        // 2. Write Tail (Continuation cells)
1196        // We can use set_raw-like access because we already verified bounds
1197        for i in 1..width {
1198            let idx = self.index_unchecked(x + i as u16, y);
1199            self.cells[idx] = Cell::CONTINUATION;
1200        }
1201        self.mark_dirty_span(y, span_start, span_end);
1202        self.cleanup_orphaned_tails(x.saturating_add(width as u16), y);
1203    }
1204
1205    /// Set the cell at (x, y) without scissor or opacity processing.
1206    ///
1207    /// This is faster but bypasses clipping and transparency.
1208    ///
1209    /// Unlike [`set`](Self::set), this does not automatically write
1210    /// continuation cells for multi-width content; callers that build wide
1211    /// glyphs manually must still populate the tail cells themselves. For
1212    /// single-width and continuation writes, it still preserves
1213    /// overlap/orphan-tail cleanup so stale continuation cells are not left
1214    /// behind. Raw wide-head writes remain strictly local so callers can
1215    /// manage continuation ownership explicitly.
1216    /// Does nothing if coordinates are out of bounds.
1217    #[inline]
1218    pub fn set_raw(&mut self, x: u16, y: u16, cell: Cell) {
1219        if let Some(idx) = self.index(x, y) {
1220            let mut span = DirtySpan::new(x, x.saturating_add(1));
1221            let raw_wide_head = cell.content.width() > 1 && !cell.is_continuation();
1222
1223            if !raw_wide_head && let Some(cleanup_span) = self.cleanup_overlap(x, y, &cell) {
1224                span = DirtySpan::new(span.x0.min(cleanup_span.x0), span.x1.max(cleanup_span.x1));
1225            }
1226            self.cells[idx] = cell;
1227            self.mark_dirty_span(y, span.x0, span.x1);
1228            if !raw_wide_head {
1229                // The orphan sweep's premise ("a continuation at x+1 cannot
1230                // be owned by x") only holds for non-continuation writes.
1231                // When the written cell is itself a continuation, x belongs
1232                // to a head on its left whose further tails (x+1, ...) are
1233                // legitimate — sweeping from x+1 would corrupt a width>2
1234                // glyph (e.g. rewriting the first tail of a width-3 glyph
1235                // used to clear its second tail). Sweep only beyond the
1236                // owning head's extent.
1237                let sweep_from = if cell.is_continuation() {
1238                    self.continuation_owner_extent(x, y)
1239                        .unwrap_or_else(|| x.saturating_add(1))
1240                } else {
1241                    x.saturating_add(1)
1242                };
1243                self.cleanup_orphaned_tails(sweep_from, y);
1244            }
1245        }
1246    }
1247
1248    /// Find the exclusive end column of the glyph owning the continuation at
1249    /// `x`, scanning left at most `GraphemeId::MAX_WIDTH` cells. Returns
1250    /// `None` when the continuation is orphaned (no owning head).
1251    fn continuation_owner_extent(&self, x: u16, y: u16) -> Option<u16> {
1252        let limit = x.saturating_sub(GraphemeId::MAX_WIDTH as u16);
1253        let mut back_x = x;
1254        while back_x > limit {
1255            back_x -= 1;
1256            let idx = self.index(back_x, y)?;
1257            let cell = self.cells[idx];
1258            if !cell.is_continuation() {
1259                let end = back_x.saturating_add(cell.content.width() as u16);
1260                return (end > x).then_some(end);
1261            }
1262        }
1263        None
1264    }
1265
1266    /// Fill a rectangular region with the given cell.
1267    ///
1268    /// Respects scissor region and applies opacity.
1269    #[inline]
1270    pub fn fill(&mut self, rect: Rect, cell: Cell) {
1271        let clipped = self.current_scissor().intersection(&rect);
1272        if clipped.is_empty() {
1273            return;
1274        }
1275
1276        // Fast path: full-row fill with an opaque, single-width cell and no opacity.
1277        // Safe because every cell in the row is overwritten, and no blending is required.
1278        let cell_width = cell.content.width();
1279        if cell_width <= 1
1280            && !cell.is_continuation()
1281            && self.current_opacity() >= 1.0
1282            && cell.bg.a() == 255
1283            && clipped.x == 0
1284            && clipped.width == self.width
1285        {
1286            let row_width = self.width as usize;
1287            for y in clipped.y..clipped.bottom() {
1288                let row_start = y as usize * row_width;
1289                let row_end = row_start + row_width;
1290                self.cells[row_start..row_end].fill(cell);
1291                self.mark_dirty_row_full(y);
1292            }
1293            return;
1294        }
1295
1296        // Medium path: partial-width fill with opaque, single-width cell, base scissor/opacity.
1297        // Direct slice::fill per row instead of per-cell set(). We only need to handle
1298        // wide-char fragments at the fill boundaries (interior cells are fully overwritten).
1299        if cell_width <= 1
1300            && !cell.is_continuation()
1301            && self.current_opacity() >= 1.0
1302            && cell.bg.a() == 255
1303            && self.scissor_stack.len() == 1
1304        {
1305            let row_width = self.width as usize;
1306            let x_start = clipped.x as usize;
1307            let x_end = clipped.right() as usize;
1308            for y in clipped.y..clipped.bottom() {
1309                let row_start = y as usize * row_width;
1310                let mut dirty_left = clipped.x;
1311                let mut dirty_right = clipped.right();
1312
1313                // Left boundary: if first fill cell is a continuation, its wide-char
1314                // head is outside the fill region and would be orphaned. Clear it.
1315                if x_start > 0 && self.cells[row_start + x_start].is_continuation() {
1316                    let mut head_found = None;
1317                    for hx in (0..x_start).rev() {
1318                        if !self.cells[row_start + hx].is_continuation() {
1319                            head_found = Some(hx);
1320                            break;
1321                        }
1322                    }
1323
1324                    if let Some(hx) = head_found {
1325                        let c = self.cells[row_start + hx];
1326                        let width = c.content.width();
1327                        // Only clear if the head actually overlaps the fill region.
1328                        if width > 1 && hx + width > x_start {
1329                            // Clear the head and any tails before x_start.
1330                            // Tails from x_start onwards will be overwritten by the fill.
1331                            for cx in hx..x_start {
1332                                self.cells[row_start + cx] = Cell::default();
1333                            }
1334                            dirty_left = hx as u16;
1335                        }
1336                    }
1337                }
1338
1339                // Right boundary: clear orphaned continuations past the fill whose
1340                // head is being overwritten.
1341                {
1342                    let mut cx = x_end;
1343                    while cx < row_width && self.cells[row_start + cx].is_continuation() {
1344                        self.cells[row_start + cx] = Cell::default();
1345                        dirty_right = (cx as u16).saturating_add(1);
1346                        cx += 1;
1347                    }
1348                }
1349
1350                self.cells[row_start + x_start..row_start + x_end].fill(cell);
1351                self.mark_dirty_span(y, dirty_left, dirty_right);
1352            }
1353            return;
1354        }
1355
1356        // Enforce strict bounds for wide characters to prevent spilling.
1357        self.push_scissor(clipped);
1358
1359        let step = cell.content.width().max(1) as u16;
1360        let opacity = self.current_opacity();
1361        let single_cell = cell_width <= 1 && !cell.is_continuation();
1362        let fill_cell = if opacity < 1.0 {
1363            Cell {
1364                fg: cell.fg.with_opacity(opacity),
1365                bg: cell.bg.with_opacity(opacity),
1366                ..cell
1367            }
1368        } else {
1369            cell
1370        };
1371        for y in clipped.y..clipped.bottom() {
1372            let row_start = y as usize * self.width as usize;
1373            let start = row_start + clipped.x as usize;
1374            let end = row_start + clipped.right() as usize;
1375            // Narrow cells have no overlap fragments to repair. Preserve their
1376            // backgrounds directly, including through nested scissor/opacity
1377            // stacks. A continuation just outside the span still needs `set`'s
1378            // orphan cleanup, so keep it on the scalar path.
1379            if single_cell
1380                && (clipped.right() == self.width || !self.cells[end].is_continuation())
1381                && self.cells[start..end]
1382                    .iter()
1383                    .all(|old| !old.is_continuation() && old.content.width() <= 1)
1384            {
1385                for old in &mut self.cells[start..end] {
1386                    *old = Cell {
1387                        bg: fill_cell.bg.over(old.bg),
1388                        ..fill_cell
1389                    };
1390                }
1391                // Keep the scalar insertion order: merging a whole span at
1392                // once could change dirty-span overflow telemetry.
1393                for x in clipped.x..clipped.right() {
1394                    self.mark_dirty_span(y, x, x.saturating_add(1));
1395                }
1396                continue;
1397            }
1398            // Pre-clear the row span first: `set` drops a wide glyph whose
1399            // tail would cross the clip edge, so trailing columns that cannot
1400            // hold a whole glyph would otherwise keep their previous content
1401            // inside a region the caller asked to be filled (mirrors
1402            // `clear_with`).
1403            for x in clipped.x..clipped.right() {
1404                self.set(x, y, Cell::default());
1405            }
1406            let mut x = clipped.x;
1407            while x < clipped.right() {
1408                self.set(x, y, cell);
1409                x = x.saturating_add(step);
1410            }
1411        }
1412
1413        self.pop_scissor();
1414    }
1415
1416    /// Clear all cells to the default.
1417    #[inline]
1418    pub fn clear(&mut self) {
1419        self.cells.fill(Cell::default());
1420        self.mark_all_dirty();
1421        self.mutation_gen = 0;
1422    }
1423
1424    /// Reset per-frame state and clear all cells.
1425    ///
1426    /// This restores scissor/opacity stacks to their base values to ensure
1427    /// each frame starts from a clean rendering state.
1428    pub fn reset_for_frame(&mut self) {
1429        self.scissor_stack.truncate(1);
1430        if let Some(base) = self.scissor_stack.first_mut() {
1431            *base = Rect::from_size(self.width, self.height);
1432        } else {
1433            self.scissor_stack
1434                .push(Rect::from_size(self.width, self.height));
1435        }
1436
1437        self.opacity_stack.truncate(1);
1438        if let Some(base) = self.opacity_stack.first_mut() {
1439            *base = 1.0;
1440        } else {
1441            self.opacity_stack.push(1.0);
1442        }
1443
1444        self.clear();
1445    }
1446
1447    /// Clear all cells to the given cell.
1448    #[inline]
1449    pub fn clear_with(&mut self, cell: Cell) {
1450        if cell.is_continuation() {
1451            self.clear();
1452            return;
1453        }
1454
1455        let width = cell.content.width();
1456        if width <= 1 {
1457            self.cells.fill(cell);
1458            self.mark_all_dirty();
1459            return;
1460        }
1461
1462        self.cells.fill(Cell::default());
1463        let step = width as u16;
1464        for y in 0..self.height {
1465            let row_start = y as usize * self.width as usize;
1466            let mut x = 0u16;
1467            while x.saturating_add(step) <= self.width {
1468                let head_idx = row_start + x as usize;
1469                self.cells[head_idx] = cell;
1470                for off in 1..step {
1471                    self.cells[head_idx + off as usize] = Cell::CONTINUATION;
1472                }
1473                x = x.saturating_add(step);
1474            }
1475        }
1476        self.mark_all_dirty();
1477    }
1478
1479    /// Get raw access to the cell slice.
1480    ///
1481    /// This is useful for diffing against another buffer.
1482    #[inline]
1483    pub fn cells(&self) -> &[Cell] {
1484        &self.cells
1485    }
1486
1487    /// Get mutable raw access to the cell slice.
1488    ///
1489    /// Marks all rows dirty since caller may modify arbitrary cells.
1490    #[inline]
1491    pub fn cells_mut(&mut self) -> &mut [Cell] {
1492        self.mark_all_dirty();
1493        &mut self.cells
1494    }
1495
1496    /// Get the cells for a single row as a slice.
1497    ///
1498    /// # Panics
1499    ///
1500    /// Panics if `y >= height`.
1501    #[inline]
1502    pub fn row_cells(&self, y: u16) -> &[Cell] {
1503        let start = y as usize * self.width as usize;
1504        &self.cells[start..start + self.width as usize]
1505    }
1506
1507    /// Get mutable cells for a contiguous span on a row.
1508    ///
1509    /// The requested range is treated as half-open `[x0, x1)` and clamped to
1510    /// the buffer width. The span is marked dirty once before returning the
1511    /// mutable slice.
1512    ///
1513    /// This is a raw bulk-mutation helper: callers must already have applied
1514    /// any required scissor/opacity clipping and must not use it for writes
1515    /// that can change cell-content width invariants.
1516    #[inline]
1517    pub fn row_cells_mut_span(&mut self, y: u16, x0: u16, x1: u16) -> Option<&mut [Cell]> {
1518        if y >= self.height {
1519            return None;
1520        }
1521        if x0 >= x1 {
1522            return None;
1523        }
1524
1525        let start = x0.min(self.width);
1526        let end = x1.min(self.width);
1527        if start >= end {
1528            return None;
1529        }
1530
1531        self.mark_dirty_span(y, start, end);
1532
1533        let row_start = y as usize * self.width as usize;
1534        let slice_start = row_start + start as usize;
1535        let slice_end = row_start + end as usize;
1536        Some(&mut self.cells[slice_start..slice_end])
1537    }
1538
1539    // ========== Scissor Stack ==========
1540
1541    /// Push a scissor (clipping) region onto the stack.
1542    ///
1543    /// The effective scissor is the intersection of all pushed rects.
1544    /// If the intersection is empty, no cells will be drawn.
1545    #[inline]
1546    pub fn push_scissor(&mut self, rect: Rect) {
1547        let current = self.current_scissor();
1548        let intersected = current.intersection(&rect);
1549        self.scissor_stack.push(intersected);
1550    }
1551
1552    /// Pop a scissor region from the stack.
1553    ///
1554    /// Does nothing if only the base scissor remains.
1555    #[inline]
1556    pub fn pop_scissor(&mut self) {
1557        if self.scissor_stack.len() > 1 {
1558            self.scissor_stack.pop();
1559        }
1560    }
1561
1562    /// Get the current effective scissor region.
1563    #[inline]
1564    pub fn current_scissor(&self) -> Rect {
1565        *self
1566            .scissor_stack
1567            .last()
1568            .expect("scissor stack always has at least one element")
1569    }
1570
1571    /// Get the scissor stack depth.
1572    #[inline]
1573    pub fn scissor_depth(&self) -> usize {
1574        self.scissor_stack.len()
1575    }
1576
1577    // ========== Opacity Stack ==========
1578
1579    /// Push an opacity multiplier onto the stack.
1580    ///
1581    /// The effective opacity is the product of all pushed values.
1582    /// Values are clamped to `[0.0, 1.0]`.
1583    #[inline]
1584    pub fn push_opacity(&mut self, opacity: f32) {
1585        let clamped = opacity.clamp(0.0, 1.0);
1586        let current = self.current_opacity();
1587        self.opacity_stack.push(current * clamped);
1588    }
1589
1590    /// Pop an opacity value from the stack.
1591    ///
1592    /// Does nothing if only the base opacity remains.
1593    #[inline]
1594    pub fn pop_opacity(&mut self) {
1595        if self.opacity_stack.len() > 1 {
1596            self.opacity_stack.pop();
1597        }
1598    }
1599
1600    /// Get the current effective opacity.
1601    #[inline]
1602    pub fn current_opacity(&self) -> f32 {
1603        *self
1604            .opacity_stack
1605            .last()
1606            .expect("opacity stack always has at least one element")
1607    }
1608
1609    /// Get the opacity stack depth.
1610    #[inline]
1611    pub fn opacity_depth(&self) -> usize {
1612        self.opacity_stack.len()
1613    }
1614
1615    // ========== Copying and Diffing ==========
1616
1617    /// Copy a rectangular region from another buffer.
1618    ///
1619    /// Copies cells from `src` at `src_rect` to this buffer at `dst_pos`.
1620    /// Respects scissor region.
1621    pub fn copy_from(&mut self, src: &Buffer, src_rect: Rect, dst_x: u16, dst_y: u16) {
1622        // Enforce strict bounds on the destination area to prevent wide characters
1623        // from leaking outside the requested copy region.
1624        let copy_bounds = Rect::new(dst_x, dst_y, src_rect.width, src_rect.height);
1625        self.push_scissor(copy_bounds);
1626        let clip = self.current_scissor();
1627
1628        for dy in 0..src_rect.height {
1629            // Compute destination y with overflow check
1630            let Some(target_y) = dst_y.checked_add(dy) else {
1631                continue;
1632            };
1633            let Some(sy) = src_rect.y.checked_add(dy) else {
1634                continue;
1635            };
1636
1637            let mut dx = 0u16;
1638            while dx < src_rect.width {
1639                // Compute coordinates with overflow checks
1640                let Some(target_x) = dst_x.checked_add(dx) else {
1641                    dx = dx.saturating_add(1);
1642                    continue;
1643                };
1644                let Some(sx) = src_rect.x.checked_add(dx) else {
1645                    dx = dx.saturating_add(1);
1646                    continue;
1647                };
1648
1649                if let Some(cell) = src.get(sx, sy) {
1650                    // Continuation cells without their head should not be copied.
1651                    // Heads are handled separately and skip over tails, so any
1652                    // continuation we see here is orphaned by the copy region.
1653                    if cell.is_continuation() {
1654                        self.set(target_x, target_y, Cell::default());
1655                        dx = dx.saturating_add(1);
1656                        continue;
1657                    }
1658
1659                    let width = cell.content.width();
1660                    let target_right = target_x.saturating_add(width as u16);
1661
1662                    // Check for clipping.
1663                    // 1. Source clipping: tail extends beyond the source copy region.
1664                    // 2. Destination clipping: tail extends beyond the effective
1665                    //    scissor on the right, OR the head lands left of it while
1666                    //    a tail would land inside (an outer scissor narrower on
1667                    //    the left). Both halves matter: `set` rejects wide writes
1668                    //    atomically, so without the left check the in-clip tail
1669                    //    cell would silently keep its stale content.
1670                    let src_clipped = width > 1 && dx.saturating_add(width as u16) > src_rect.width;
1671                    let dst_clipped = target_right > clip.right()
1672                        || (width > 1 && target_x < clip.left() && target_right > clip.left());
1673
1674                    if src_clipped || dst_clipped {
1675                        // Write default cells to all valid positions in the span to ensure
1676                        // previous content is cleared. `set` is atomic for wide chars,
1677                        // so we must write single-width default cells individually.
1678                        // (`set` clips each single-width write to the scissor, so
1679                        // starting at the head position is safe on the left edge.)
1680                        let valid_width = (clip.right().saturating_sub(target_x)).min(width as u16);
1681                        for i in 0..valid_width {
1682                            self.set(target_x + i, target_y, Cell::default());
1683                        }
1684                    } else {
1685                        self.set(target_x, target_y, *cell);
1686                    }
1687
1688                    // Skip tails in source iteration.
1689                    if width > 1 {
1690                        dx = dx.saturating_add(width as u16);
1691                    } else {
1692                        dx = dx.saturating_add(1);
1693                    }
1694                } else {
1695                    dx = dx.saturating_add(1);
1696                }
1697            }
1698        }
1699
1700        self.pop_scissor();
1701    }
1702
1703    /// Check if two buffers have identical content.
1704    pub fn content_eq(&self, other: &Buffer) -> bool {
1705        self.width == other.width && self.height == other.height && self.cells == other.cells
1706    }
1707}
1708
1709impl Default for Buffer {
1710    /// Create a 1x1 buffer (minimum size).
1711    fn default() -> Self {
1712        Self::new(1, 1)
1713    }
1714}
1715
1716impl PartialEq for Buffer {
1717    fn eq(&self, other: &Self) -> bool {
1718        self.content_eq(other)
1719    }
1720}
1721
1722impl Eq for Buffer {}
1723
1724// ---------------------------------------------------------------------------
1725// DoubleBuffer: O(1) frame swap (bd-1rz0.4.4)
1726// ---------------------------------------------------------------------------
1727
1728/// Double-buffered render target with O(1) swap.
1729///
1730/// Maintains two pre-allocated buffers and swaps between them by flipping an
1731/// index, avoiding the O(width × height) clone that a naive prev/current
1732/// pattern requires.
1733///
1734/// # Invariants
1735///
1736/// 1. Both buffers always have the same dimensions.
1737/// 2. `swap()` is O(1) — it only flips the index, never copies cells.
1738/// 3. After `swap()`, `current_mut().clear()` should be called to prepare
1739///    the new frame buffer.
1740/// 4. `resize()` discards both buffers and returns `true` so callers know
1741///    a full redraw is needed.
1742#[derive(Debug)]
1743pub struct DoubleBuffer {
1744    buffers: [Buffer; 2],
1745    /// Index of the *current* buffer (0 or 1).
1746    current_idx: u8,
1747}
1748
1749// ---------------------------------------------------------------------------
1750// AdaptiveDoubleBuffer: Allocation-efficient resize (bd-1rz0.4.2)
1751// ---------------------------------------------------------------------------
1752
1753/// Over-allocation factor for growth headroom (1.25x = 25% extra capacity).
1754const ADAPTIVE_GROWTH_FACTOR: f32 = 1.25;
1755
1756/// Shrink threshold: only reallocate if new size < this fraction of capacity.
1757/// This prevents thrashing at size boundaries.
1758const ADAPTIVE_SHRINK_THRESHOLD: f32 = 0.50;
1759
1760/// Maximum over-allocation per dimension (prevent excessive memory usage).
1761const ADAPTIVE_MAX_OVERAGE: u16 = 200;
1762
1763/// Adaptive double-buffered render target with allocation efficiency.
1764///
1765/// Wraps `DoubleBuffer` with capacity tracking to minimize allocations during
1766/// resize storms. Key strategies:
1767///
1768/// 1. **Over-allocation headroom**: Allocate slightly more than needed to handle
1769///    minor size increases without reallocation.
1770/// 2. **Shrink threshold**: Only shrink if new size is significantly smaller
1771///    than allocated capacity (prevents thrashing at size boundaries).
1772/// 3. **Logical vs physical dimensions**: Track both the current view size
1773///    and the allocated capacity separately.
1774///
1775/// # Invariants
1776///
1777/// 1. `capacity_width >= logical_width` and `capacity_height >= logical_height`
1778/// 2. Logical dimensions represent the actual usable area for rendering.
1779/// 3. Physical capacity may exceed logical dimensions by up to `ADAPTIVE_GROWTH_FACTOR`.
1780/// 4. Shrink only occurs when logical size drops below `ADAPTIVE_SHRINK_THRESHOLD * capacity`.
1781///
1782/// # Failure Modes
1783///
1784/// | Condition | Behavior | Rationale |
1785/// |-----------|----------|-----------|
1786/// | Capacity overflow | Clamp to u16::MAX | Prevents panic on extreme sizes |
1787/// | Zero dimensions | Delegate to DoubleBuffer (panic) | Invalid state |
1788///
1789/// # Performance
1790///
1791/// - `resize()` is O(1) when the new size fits within capacity.
1792/// - `resize()` is O(width × height) when reallocation is required.
1793/// - Target: < 5% allocation overhead during resize storms.
1794#[derive(Debug)]
1795pub struct AdaptiveDoubleBuffer {
1796    /// The underlying double buffer (may have larger capacity than logical size).
1797    inner: DoubleBuffer,
1798    /// Logical width (the usable rendering area).
1799    logical_width: u16,
1800    /// Logical height (the usable rendering area).
1801    logical_height: u16,
1802    /// Allocated capacity width (>= logical_width).
1803    capacity_width: u16,
1804    /// Allocated capacity height (>= logical_height).
1805    capacity_height: u16,
1806    /// Statistics for observability.
1807    stats: AdaptiveStats,
1808}
1809
1810/// Statistics for adaptive buffer allocation.
1811#[derive(Debug, Clone, Default)]
1812pub struct AdaptiveStats {
1813    /// Number of resize calls that avoided reallocation.
1814    pub resize_avoided: u64,
1815    /// Number of resize calls that required reallocation.
1816    pub resize_reallocated: u64,
1817    /// Number of resize calls for growth.
1818    pub resize_growth: u64,
1819    /// Number of resize calls for shrink.
1820    pub resize_shrink: u64,
1821}
1822
1823impl AdaptiveStats {
1824    /// Reset statistics to zero.
1825    pub fn reset(&mut self) {
1826        *self = Self::default();
1827    }
1828
1829    /// Calculate the reallocation avoidance ratio (higher is better).
1830    pub fn avoidance_ratio(&self) -> f64 {
1831        let total = self.resize_avoided + self.resize_reallocated;
1832        if total == 0 {
1833            1.0
1834        } else {
1835            self.resize_avoided as f64 / total as f64
1836        }
1837    }
1838}
1839
1840impl DoubleBuffer {
1841    /// Create a double buffer with the given dimensions.
1842    ///
1843    /// Both buffers are initialized to default (empty) cells.
1844    /// Dimensions are clamped to a minimum of 1x1.
1845    pub fn new(width: u16, height: u16) -> Self {
1846        Self {
1847            buffers: [Buffer::new(width, height), Buffer::new(width, height)],
1848            current_idx: 0,
1849        }
1850    }
1851
1852    /// O(1) swap: the current buffer becomes previous, and vice versa.
1853    ///
1854    /// After swapping, call `current_mut().clear()` to prepare for the
1855    /// next frame.
1856    #[inline]
1857    pub fn swap(&mut self) {
1858        self.current_idx = 1 - self.current_idx;
1859    }
1860
1861    /// Reference to the current (in-progress) frame buffer.
1862    #[inline]
1863    pub fn current(&self) -> &Buffer {
1864        &self.buffers[self.current_idx as usize]
1865    }
1866
1867    /// Mutable reference to the current (in-progress) frame buffer.
1868    #[inline]
1869    pub fn current_mut(&mut self) -> &mut Buffer {
1870        &mut self.buffers[self.current_idx as usize]
1871    }
1872
1873    /// Reference to the previous (last-presented) frame buffer.
1874    #[inline]
1875    pub fn previous(&self) -> &Buffer {
1876        &self.buffers[(1 - self.current_idx) as usize]
1877    }
1878
1879    /// Mutable reference to the previous (last-presented) frame buffer.
1880    #[inline]
1881    pub fn previous_mut(&mut self) -> &mut Buffer {
1882        &mut self.buffers[(1 - self.current_idx) as usize]
1883    }
1884
1885    /// Width of both buffers.
1886    #[inline]
1887    pub fn width(&self) -> u16 {
1888        self.buffers[0].width()
1889    }
1890
1891    /// Height of both buffers.
1892    #[inline]
1893    pub fn height(&self) -> u16 {
1894        self.buffers[0].height()
1895    }
1896
1897    /// Resize both buffers. Returns `true` if dimensions actually changed.
1898    ///
1899    /// Both buffers are replaced with fresh allocations and the index is
1900    /// reset. Callers should force a full redraw when this returns `true`.
1901    pub fn resize(&mut self, width: u16, height: u16) -> bool {
1902        // Compare against the same ≥1 clamp Buffer::new applies, so a caller
1903        // repeatedly passing a degenerate 0 dimension doesn't reallocate both
1904        // buffers (and force a full redraw) every frame.
1905        let width = width.max(1);
1906        let height = height.max(1);
1907        if self.buffers[0].width() == width && self.buffers[0].height() == height {
1908            return false;
1909        }
1910        self.buffers = [Buffer::new(width, height), Buffer::new(width, height)];
1911        self.current_idx = 0;
1912        true
1913    }
1914
1915    /// Check whether both buffers have the given dimensions (after the same
1916    /// ≥1 clamp `Buffer::new` applies).
1917    #[inline]
1918    pub fn dimensions_match(&self, width: u16, height: u16) -> bool {
1919        self.buffers[0].width() == width.max(1) && self.buffers[0].height() == height.max(1)
1920    }
1921}
1922
1923// ---------------------------------------------------------------------------
1924// AdaptiveDoubleBuffer implementation (bd-1rz0.4.2)
1925// ---------------------------------------------------------------------------
1926
1927impl AdaptiveDoubleBuffer {
1928    /// Create a new adaptive buffer with the given logical dimensions.
1929    ///
1930    /// Initial capacity is set with growth headroom applied.
1931    /// Dimensions are clamped to a minimum of 1x1.
1932    pub fn new(width: u16, height: u16) -> Self {
1933        let (cap_w, cap_h) = Self::compute_capacity(width, height);
1934        Self {
1935            inner: DoubleBuffer::new(cap_w, cap_h),
1936            logical_width: width,
1937            logical_height: height,
1938            capacity_width: cap_w,
1939            capacity_height: cap_h,
1940            stats: AdaptiveStats::default(),
1941        }
1942    }
1943
1944    /// Compute the capacity for a given logical size.
1945    ///
1946    /// Applies growth factor with clamping to prevent overflow.
1947    fn compute_capacity(width: u16, height: u16) -> (u16, u16) {
1948        let extra_w =
1949            ((width as f32 * (ADAPTIVE_GROWTH_FACTOR - 1.0)) as u16).min(ADAPTIVE_MAX_OVERAGE);
1950        let extra_h =
1951            ((height as f32 * (ADAPTIVE_GROWTH_FACTOR - 1.0)) as u16).min(ADAPTIVE_MAX_OVERAGE);
1952
1953        let cap_w = width.saturating_add(extra_w);
1954        let cap_h = height.saturating_add(extra_h);
1955
1956        (cap_w, cap_h)
1957    }
1958
1959    /// Check if the new dimensions require reallocation.
1960    ///
1961    /// Returns `true` if reallocation is needed, `false` if current capacity suffices.
1962    fn needs_reallocation(&self, width: u16, height: u16) -> bool {
1963        // Growth beyond capacity always requires reallocation
1964        if width > self.capacity_width || height > self.capacity_height {
1965            return true;
1966        }
1967
1968        // Shrink threshold: reallocate if new size is significantly smaller
1969        let shrink_threshold_w = (self.capacity_width as f32 * ADAPTIVE_SHRINK_THRESHOLD) as u16;
1970        let shrink_threshold_h = (self.capacity_height as f32 * ADAPTIVE_SHRINK_THRESHOLD) as u16;
1971
1972        width < shrink_threshold_w || height < shrink_threshold_h
1973    }
1974
1975    /// O(1) swap: the current buffer becomes previous, and vice versa.
1976    ///
1977    /// After swapping, call `current_mut().clear()` to prepare for the
1978    /// next frame.
1979    #[inline]
1980    pub fn swap(&mut self) {
1981        self.inner.swap();
1982    }
1983
1984    /// Reference to the current (in-progress) frame buffer.
1985    ///
1986    /// Note: The buffer may have larger dimensions than the logical size.
1987    /// Use `logical_width()` and `logical_height()` for rendering bounds.
1988    #[inline]
1989    pub fn current(&self) -> &Buffer {
1990        self.inner.current()
1991    }
1992
1993    /// Mutable reference to the current (in-progress) frame buffer.
1994    #[inline]
1995    pub fn current_mut(&mut self) -> &mut Buffer {
1996        self.inner.current_mut()
1997    }
1998
1999    /// Reference to the previous (last-presented) frame buffer.
2000    #[inline]
2001    pub fn previous(&self) -> &Buffer {
2002        self.inner.previous()
2003    }
2004
2005    /// Logical width (the usable rendering area).
2006    #[inline]
2007    pub fn width(&self) -> u16 {
2008        self.logical_width
2009    }
2010
2011    /// Logical height (the usable rendering area).
2012    #[inline]
2013    pub fn height(&self) -> u16 {
2014        self.logical_height
2015    }
2016
2017    /// Allocated capacity width (may be larger than logical width).
2018    #[inline]
2019    pub fn capacity_width(&self) -> u16 {
2020        self.capacity_width
2021    }
2022
2023    /// Allocated capacity height (may be larger than logical height).
2024    #[inline]
2025    pub fn capacity_height(&self) -> u16 {
2026        self.capacity_height
2027    }
2028
2029    /// Get allocation statistics.
2030    #[inline]
2031    pub fn stats(&self) -> &AdaptiveStats {
2032        &self.stats
2033    }
2034
2035    /// Reset allocation statistics.
2036    pub fn reset_stats(&mut self) {
2037        self.stats.reset();
2038    }
2039
2040    /// Resize the logical dimensions. Returns `true` if dimensions changed.
2041    ///
2042    /// This method minimizes allocations by:
2043    /// 1. Reusing existing capacity when the new size fits.
2044    /// 2. Only reallocating on significant shrink (below threshold).
2045    /// 3. Applying growth headroom to avoid immediate reallocation on growth.
2046    ///
2047    /// # Performance
2048    ///
2049    /// - O(1) when new size fits within existing capacity.
2050    /// - O(width × height) when reallocation is required.
2051    pub fn resize(&mut self, width: u16, height: u16) -> bool {
2052        // No change in logical dimensions
2053        if width == self.logical_width && height == self.logical_height {
2054            return false;
2055        }
2056
2057        let is_growth = width > self.logical_width || height > self.logical_height;
2058        if is_growth {
2059            self.stats.resize_growth += 1;
2060        } else {
2061            self.stats.resize_shrink += 1;
2062        }
2063
2064        if self.needs_reallocation(width, height) {
2065            // Reallocate with new capacity
2066            let (cap_w, cap_h) = Self::compute_capacity(width, height);
2067            self.inner = DoubleBuffer::new(cap_w, cap_h);
2068            self.capacity_width = cap_w;
2069            self.capacity_height = cap_h;
2070            self.stats.resize_reallocated += 1;
2071        } else {
2072            // Reuse existing capacity - just update logical dimensions
2073            // Clear both buffers to avoid stale content outside new bounds
2074            self.inner.current_mut().clear();
2075            self.inner.previous_mut().clear();
2076            self.stats.resize_avoided += 1;
2077        }
2078
2079        self.logical_width = width;
2080        self.logical_height = height;
2081        true
2082    }
2083
2084    /// Check whether logical dimensions match the given values.
2085    #[inline]
2086    pub fn dimensions_match(&self, width: u16, height: u16) -> bool {
2087        self.logical_width == width && self.logical_height == height
2088    }
2089
2090    /// Get the logical bounding rect (for scissoring/rendering).
2091    #[inline]
2092    pub fn logical_bounds(&self) -> Rect {
2093        Rect::from_size(self.logical_width, self.logical_height)
2094    }
2095
2096    /// Calculate memory efficiency (logical cells / capacity cells).
2097    pub fn memory_efficiency(&self) -> f64 {
2098        let logical = self.logical_width as u64 * self.logical_height as u64;
2099        let capacity = self.capacity_width as u64 * self.capacity_height as u64;
2100        if capacity == 0 {
2101            1.0
2102        } else {
2103            logical as f64 / capacity as f64
2104        }
2105    }
2106}
2107
2108/// 64-bit FNV-1a offset basis used by [`buffer_checksum`].
2109pub const BUFFER_CHECKSUM_FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
2110/// 64-bit FNV-1a prime used by [`buffer_checksum`].
2111pub const BUFFER_CHECKSUM_FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
2112
2113/// Compute the 64-bit FNV-1a checksum over a slice of [`Cell`]s (16 bytes per cell).
2114#[inline]
2115#[must_use]
2116pub fn buffer_cells_checksum(cells: &[Cell]) -> u64 {
2117    let mut hash = BUFFER_CHECKSUM_FNV_OFFSET_BASIS;
2118    for cell in cells {
2119        for byte in cell.to_le_bytes() {
2120            hash ^= u64::from(byte);
2121            hash = hash.wrapping_mul(BUFFER_CHECKSUM_FNV_PRIME);
2122        }
2123    }
2124    hash
2125}
2126
2127/// Compute the 64-bit FNV-1a checksum over each cell's 16 bytes in row-major order.
2128///
2129/// Shared shadow/golden frame checksum used by `ftui-runtime` (`RolloutPolicy::Shadow`
2130/// `shadow_frame` evidence) and `ftui-harness` (`LabSession` and `ShadowRun`).
2131#[inline]
2132#[must_use]
2133pub fn buffer_checksum(buf: &Buffer) -> u64 {
2134    buffer_cells_checksum(&buf.cells)
2135}
2136
2137#[cfg(test)]
2138mod tests {
2139    use super::*;
2140    use crate::cell::{CellContent, PackedRgba};
2141
2142    #[test]
2143    fn set_composites_background() {
2144        let mut buf = Buffer::new(1, 1);
2145
2146        // Set background to RED
2147        let red = PackedRgba::rgb(255, 0, 0);
2148        buf.set(0, 0, Cell::default().with_bg(red));
2149
2150        // Write 'X' with transparent background
2151        let cell = Cell::from_char('X'); // Default bg is TRANSPARENT
2152        buf.set(0, 0, cell);
2153
2154        let result = buf.get(0, 0).unwrap();
2155        assert_eq!(result.content.as_char(), Some('X'));
2156        assert_eq!(
2157            result.bg, red,
2158            "Background should be preserved (composited)"
2159        );
2160    }
2161
2162    #[test]
2163    fn set_fast_matches_set_for_transparent_bg() {
2164        let red = PackedRgba::rgb(255, 0, 0);
2165        let cell = Cell::from_char('X').with_fg(PackedRgba::rgb(0, 255, 0));
2166
2167        let mut a = Buffer::new(1, 1);
2168        a.set(0, 0, Cell::default().with_bg(red));
2169        a.set(0, 0, cell);
2170
2171        let mut b = Buffer::new(1, 1);
2172        b.set(0, 0, Cell::default().with_bg(red));
2173        b.set_fast(0, 0, cell);
2174
2175        assert_eq!(a.get(0, 0), b.get(0, 0));
2176    }
2177
2178    #[test]
2179    fn set_fast_matches_set_for_opaque_bg() {
2180        let cell = Cell::from_char('X')
2181            .with_fg(PackedRgba::rgb(0, 255, 0))
2182            .with_bg(PackedRgba::rgb(255, 0, 0));
2183
2184        let mut a = Buffer::new(1, 1);
2185        a.set(0, 0, cell);
2186
2187        let mut b = Buffer::new(1, 1);
2188        b.set_fast(0, 0, cell);
2189
2190        assert_eq!(a.get(0, 0), b.get(0, 0));
2191    }
2192
2193    #[test]
2194    fn set_fast_clears_orphaned_tail_like_set() {
2195        let mut slow = Buffer::new(3, 1);
2196        slow.set_raw(0, 0, Cell::from_char('A'));
2197        slow.set_raw(1, 0, Cell::CONTINUATION);
2198        slow.clear_dirty();
2199
2200        let mut fast = slow.clone();
2201
2202        slow.set(0, 0, Cell::from_char('X'));
2203        fast.set_fast(0, 0, Cell::from_char('X'));
2204
2205        assert_eq!(slow.cells(), fast.cells());
2206        assert_eq!(fast.get(1, 0), Some(&Cell::default()));
2207
2208        let spans = fast.dirty_span_row(0).expect("dirty span row").spans();
2209        assert_eq!(spans, &[DirtySpan::new(0, 2)]);
2210    }
2211
2212    #[test]
2213    fn rect_contains() {
2214        let r = Rect::new(5, 5, 10, 10);
2215        assert!(r.contains(5, 5)); // Top-left corner
2216        assert!(r.contains(14, 14)); // Bottom-right inside
2217        assert!(!r.contains(4, 5)); // Left of rect
2218        assert!(!r.contains(15, 5)); // Right of rect (exclusive)
2219        assert!(!r.contains(5, 15)); // Below rect (exclusive)
2220    }
2221
2222    #[test]
2223    fn rect_intersection() {
2224        let a = Rect::new(0, 0, 10, 10);
2225        let b = Rect::new(5, 5, 10, 10);
2226        let i = a.intersection(&b);
2227        assert_eq!(i, Rect::new(5, 5, 5, 5));
2228
2229        // Non-overlapping
2230        let c = Rect::new(20, 20, 5, 5);
2231        assert_eq!(a.intersection(&c), Rect::default());
2232    }
2233
2234    #[test]
2235    fn buffer_creation() {
2236        let buf = Buffer::new(80, 24);
2237        assert_eq!(buf.width(), 80);
2238        assert_eq!(buf.height(), 24);
2239        assert_eq!(buf.len(), 80 * 24);
2240    }
2241
2242    #[test]
2243    fn content_height_empty_is_zero() {
2244        let buf = Buffer::new(8, 4);
2245        assert_eq!(buf.content_height(), 0);
2246    }
2247
2248    #[test]
2249    fn content_height_tracks_last_non_empty_row() {
2250        let mut buf = Buffer::new(5, 4);
2251        buf.set(0, 0, Cell::from_char('A'));
2252        assert_eq!(buf.content_height(), 1);
2253
2254        buf.set(2, 3, Cell::from_char('Z'));
2255        assert_eq!(buf.content_height(), 4);
2256    }
2257
2258    #[test]
2259    fn buffer_zero_width_clamped_to_one() {
2260        let buf = Buffer::new(0, 24);
2261        assert_eq!(buf.width(), 1);
2262        assert_eq!(buf.height(), 24);
2263    }
2264
2265    #[test]
2266    fn buffer_zero_height_clamped_to_one() {
2267        let buf = Buffer::new(80, 0);
2268        assert_eq!(buf.width(), 80);
2269        assert_eq!(buf.height(), 1);
2270    }
2271
2272    #[test]
2273    fn buffer_get_and_set() {
2274        let mut buf = Buffer::new(10, 10);
2275        let cell = Cell::from_char('X');
2276        buf.set(5, 5, cell);
2277        assert_eq!(buf.get(5, 5).unwrap().content.as_char(), Some('X'));
2278    }
2279
2280    #[test]
2281    fn buffer_out_of_bounds_get() {
2282        let buf = Buffer::new(10, 10);
2283        assert!(buf.get(10, 0).is_none());
2284        assert!(buf.get(0, 10).is_none());
2285        assert!(buf.get(100, 100).is_none());
2286    }
2287
2288    #[test]
2289    fn buffer_out_of_bounds_set_ignored() {
2290        let mut buf = Buffer::new(10, 10);
2291        buf.set(100, 100, Cell::from_char('X')); // Should not panic
2292        assert_eq!(buf.cells().iter().filter(|c| !c.is_empty()).count(), 0);
2293    }
2294
2295    #[test]
2296    fn buffer_clear() {
2297        let mut buf = Buffer::new(10, 10);
2298        buf.set(5, 5, Cell::from_char('X'));
2299        buf.clear();
2300        assert!(buf.get(5, 5).unwrap().is_empty());
2301    }
2302
2303    #[test]
2304    fn scissor_stack_basic() {
2305        let mut buf = Buffer::new(20, 20);
2306
2307        // Default scissor covers entire buffer
2308        assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
2309        assert_eq!(buf.scissor_depth(), 1);
2310
2311        // Push smaller scissor
2312        buf.push_scissor(Rect::new(5, 5, 10, 10));
2313        assert_eq!(buf.current_scissor(), Rect::new(5, 5, 10, 10));
2314        assert_eq!(buf.scissor_depth(), 2);
2315
2316        // Set inside scissor works
2317        buf.set(7, 7, Cell::from_char('I'));
2318        assert_eq!(buf.get(7, 7).unwrap().content.as_char(), Some('I'));
2319
2320        // Set outside scissor is ignored
2321        buf.set(0, 0, Cell::from_char('O'));
2322        assert!(buf.get(0, 0).unwrap().is_empty());
2323
2324        // Pop scissor
2325        buf.pop_scissor();
2326        assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
2327        assert_eq!(buf.scissor_depth(), 1);
2328
2329        // Now can set at (0, 0)
2330        buf.set(0, 0, Cell::from_char('N'));
2331        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('N'));
2332    }
2333
2334    #[test]
2335    fn scissor_intersection() {
2336        let mut buf = Buffer::new(20, 20);
2337        buf.push_scissor(Rect::new(5, 5, 10, 10));
2338        buf.push_scissor(Rect::new(8, 8, 10, 10));
2339
2340        // Intersection: (8,8) to (15,15) intersected with (5,5) to (15,15)
2341        // Result: (8,8) to (15,15) -> width=7, height=7
2342        assert_eq!(buf.current_scissor(), Rect::new(8, 8, 7, 7));
2343    }
2344
2345    #[test]
2346    fn scissor_base_cannot_be_popped() {
2347        let mut buf = Buffer::new(10, 10);
2348        buf.pop_scissor(); // Should be a no-op
2349        assert_eq!(buf.scissor_depth(), 1);
2350        buf.pop_scissor(); // Still no-op
2351        assert_eq!(buf.scissor_depth(), 1);
2352    }
2353
2354    #[test]
2355    fn opacity_stack_basic() {
2356        let mut buf = Buffer::new(10, 10);
2357
2358        // Default opacity is 1.0
2359        assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
2360        assert_eq!(buf.opacity_depth(), 1);
2361
2362        // Push 0.5 opacity
2363        buf.push_opacity(0.5);
2364        assert!((buf.current_opacity() - 0.5).abs() < f32::EPSILON);
2365        assert_eq!(buf.opacity_depth(), 2);
2366
2367        // Push another 0.5 -> effective 0.25
2368        buf.push_opacity(0.5);
2369        assert!((buf.current_opacity() - 0.25).abs() < f32::EPSILON);
2370        assert_eq!(buf.opacity_depth(), 3);
2371
2372        // Pop back to 0.5
2373        buf.pop_opacity();
2374        assert!((buf.current_opacity() - 0.5).abs() < f32::EPSILON);
2375    }
2376
2377    #[test]
2378    fn opacity_applied_to_cells() {
2379        let mut buf = Buffer::new(10, 10);
2380        buf.push_opacity(0.5);
2381
2382        let cell = Cell::from_char('X').with_fg(PackedRgba::rgba(100, 100, 100, 255));
2383        buf.set(5, 5, cell);
2384
2385        let stored = buf.get(5, 5).unwrap();
2386        // Alpha should be reduced by 0.5
2387        assert_eq!(stored.fg.a(), 128);
2388    }
2389
2390    #[test]
2391    fn opacity_composites_background_before_storage() {
2392        let mut buf = Buffer::new(1, 1);
2393
2394        let red = PackedRgba::rgb(255, 0, 0);
2395        let blue = PackedRgba::rgb(0, 0, 255);
2396
2397        buf.set(0, 0, Cell::default().with_bg(red));
2398        buf.push_opacity(0.5);
2399        buf.set(0, 0, Cell::default().with_bg(blue));
2400
2401        let stored = buf.get(0, 0).unwrap();
2402        let expected = blue.with_opacity(0.5).over(red);
2403        assert_eq!(stored.bg, expected);
2404    }
2405
2406    #[test]
2407    fn opacity_clamped() {
2408        let mut buf = Buffer::new(10, 10);
2409        buf.push_opacity(2.0); // Should clamp to 1.0
2410        assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
2411
2412        buf.push_opacity(-1.0); // Should clamp to 0.0
2413        assert!((buf.current_opacity() - 0.0).abs() < f32::EPSILON);
2414    }
2415
2416    #[test]
2417    fn opacity_base_cannot_be_popped() {
2418        let mut buf = Buffer::new(10, 10);
2419        buf.pop_opacity(); // No-op
2420        assert_eq!(buf.opacity_depth(), 1);
2421    }
2422
2423    #[test]
2424    fn buffer_fill() {
2425        let mut buf = Buffer::new(10, 10);
2426        let cell = Cell::from_char('#');
2427        buf.fill(Rect::new(2, 2, 5, 5), cell);
2428
2429        // Inside fill region
2430        assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('#'));
2431
2432        // Outside fill region
2433        assert!(buf.get(0, 0).unwrap().is_empty());
2434    }
2435
2436    #[test]
2437    fn buffer_fill_respects_scissor() {
2438        let mut buf = Buffer::new(10, 10);
2439        buf.push_scissor(Rect::new(3, 3, 4, 4));
2440
2441        let cell = Cell::from_char('#');
2442        buf.fill(Rect::new(0, 0, 10, 10), cell);
2443
2444        // Only scissor region should be filled
2445        assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('#'));
2446        assert!(buf.get(0, 0).unwrap().is_empty());
2447        assert!(buf.get(7, 7).unwrap().is_empty());
2448    }
2449
2450    #[test]
2451    fn fill_single_width_matches_scalar_reference() {
2452        // Keep the original two-pass fill as an independent oracle, including
2453        // its overlap cleanup, compositing, and dirty-span insertion order.
2454        fn scalar_fill(buffer: &mut Buffer, area: Rect, cell: Cell) {
2455            let clipped = buffer.current_scissor().intersection(&area);
2456            if clipped.is_empty() {
2457                return;
2458            }
2459            buffer.push_scissor(clipped);
2460            for y in clipped.y..clipped.bottom() {
2461                for x in clipped.x..clipped.right() {
2462                    buffer.set(x, y, Cell::default());
2463                }
2464                for x in clipped.x..clipped.right() {
2465                    buffer.set(x, y, cell);
2466                }
2467            }
2468            buffer.pop_scissor();
2469        }
2470
2471        let mut cases = 0usize;
2472        let mut fingerprint = 0xcbf2_9ce4_8422_2325u64;
2473        for layout in 0..4 {
2474            for dirty_mode in 0..3 {
2475                for opacity in [0.0, 0.375, 1.0] {
2476                    for alpha in [0, 96, 255] {
2477                        for ch in [' ', '#', '\u{301}'] {
2478                            for area in [
2479                                Rect::new(0, 0, 10, 4),
2480                                Rect::new(2, 1, 5, 2),
2481                                Rect::new(6, 0, 8, 4),
2482                                Rect::new(0, 2, 0, 1),
2483                                Rect::new(12, 0, 1, 1),
2484                            ] {
2485                                let mut initial = Buffer::new(10, 4);
2486                                for y in 0..4 {
2487                                    for x in 0..10 {
2488                                        let old = Cell::from_char(if layout == 3 {
2489                                            '\u{301}'
2490                                        } else {
2491                                            'a'
2492                                        })
2493                                        .with_bg(PackedRgba::rgba(
2494                                            x as u8 * 20,
2495                                            y as u8 * 30,
2496                                            70,
2497                                            [0, 128, 255][x as usize % 3],
2498                                        ));
2499                                        initial.set_raw(x, y, old);
2500                                    }
2501                                }
2502                                if layout == 1 {
2503                                    initial.set(0, 0, Cell::from_char('中'));
2504                                    initial.set(8, 1, Cell::from_char('中'));
2505                                    initial.set(4, 2, Cell::from_char('中'));
2506                                } else if layout == 2 {
2507                                    initial.set_raw(2, 0, Cell::CONTINUATION);
2508                                    initial.set_raw(7, 1, Cell::CONTINUATION);
2509                                    initial.set_raw(9, 1, Cell::CONTINUATION);
2510                                }
2511                                initial.set_dirty_span_config(
2512                                    DirtySpanConfig::default().with_max_spans_per_row(2),
2513                                );
2514                                if dirty_mode != 0 {
2515                                    initial.clear_dirty();
2516                                }
2517                                if dirty_mode == 2 {
2518                                    for y in 0..4 {
2519                                        initial.mark_dirty_span(y, 0, 1);
2520                                        initial.mark_dirty_span(y, 9, 10);
2521                                    }
2522                                }
2523                                initial.push_scissor(Rect::new(1, 0, 8, 4));
2524                                initial.push_scissor(Rect::new(0, 0, 10, 3));
2525                                initial.push_opacity(opacity);
2526                                let cell = Cell::from_char(ch)
2527                                    .with_fg(PackedRgba::rgba(80, 91, 123, 180))
2528                                    .with_bg(PackedRgba::rgba(19, 40, 66, alpha))
2529                                    .with_attrs(crate::cell::CellAttrs::new(
2530                                        crate::cell::StyleFlags::BOLD,
2531                                        73,
2532                                    ));
2533                                let mut actual = initial.clone();
2534                                let mut expected = initial;
2535                                actual.fill(area, cell);
2536                                scalar_fill(&mut expected, area, cell);
2537                                let actual_state = format!("{actual:?}");
2538                                let expected_state = format!("{expected:?}");
2539                                assert_eq!(actual_state, expected_state, "case {cases}");
2540                                for byte in actual_state.bytes() {
2541                                    fingerprint ^= u64::from(byte);
2542                                    fingerprint = fingerprint.wrapping_mul(0x100_0000_01b3);
2543                                }
2544                                cases += 1;
2545                            }
2546                        }
2547                    }
2548                }
2549            }
2550        }
2551        eprintln!("FILL_GOLDEN cases={cases} hash={fingerprint:016x}");
2552    }
2553
2554    #[test]
2555    fn buffer_copy_from() {
2556        let mut src = Buffer::new(10, 10);
2557        src.set(2, 2, Cell::from_char('S'));
2558
2559        let mut dst = Buffer::new(10, 10);
2560        dst.copy_from(&src, Rect::new(0, 0, 5, 5), 3, 3);
2561
2562        // Cell at (2,2) in src should be at (5,5) in dst (offset by 3,3)
2563        assert_eq!(dst.get(5, 5).unwrap().content.as_char(), Some('S'));
2564    }
2565
2566    #[test]
2567    fn copy_from_clips_wide_char_at_boundary() {
2568        let mut src = Buffer::new(10, 1);
2569        // Wide char at x=0 (width 2)
2570        src.set(0, 0, Cell::from_char('中'));
2571
2572        let mut dst = Buffer::new(10, 1);
2573        // Copy only the first column (x=0, width=1) from src to dst at (0,0)
2574        // This includes the head of '中' but EXCLUDES the tail.
2575        dst.copy_from(&src, Rect::new(0, 0, 1, 1), 0, 0);
2576
2577        // The copy should be atomic: since the tail doesn't fit in the copy region,
2578        // the head should NOT be written (or at least the tail should not be written outside the region).
2579
2580        // Check x=0: Should be empty (atomic rejection) or clipped?
2581        // With implicit scissor fix: atomic rejection means x=0 is empty.
2582        // Without fix: x=0 is '中', x=1 is CONTINUATION (leak).
2583
2584        // Asserting the fix behavior (atomic rejection):
2585        assert!(
2586            dst.get(0, 0).unwrap().is_empty(),
2587            "Wide char head should not be written if tail is clipped"
2588        );
2589        assert!(
2590            dst.get(1, 0).unwrap().is_empty(),
2591            "Wide char tail should not be leaked outside copy region"
2592        );
2593    }
2594
2595    #[test]
2596    fn buffer_content_eq() {
2597        let mut buf1 = Buffer::new(10, 10);
2598        let mut buf2 = Buffer::new(10, 10);
2599
2600        assert!(buf1.content_eq(&buf2));
2601
2602        buf1.set(0, 0, Cell::from_char('X'));
2603        assert!(!buf1.content_eq(&buf2));
2604
2605        buf2.set(0, 0, Cell::from_char('X'));
2606        assert!(buf1.content_eq(&buf2));
2607    }
2608
2609    #[test]
2610    fn buffer_bounds() {
2611        let buf = Buffer::new(80, 24);
2612        let bounds = buf.bounds();
2613        assert_eq!(bounds.x, 0);
2614        assert_eq!(bounds.y, 0);
2615        assert_eq!(bounds.width, 80);
2616        assert_eq!(bounds.height, 24);
2617    }
2618
2619    #[test]
2620    fn buffer_set_raw_bypasses_scissor() {
2621        let mut buf = Buffer::new(10, 10);
2622        buf.push_scissor(Rect::new(5, 5, 5, 5));
2623
2624        // set() respects scissor - this should be ignored
2625        buf.set(0, 0, Cell::from_char('S'));
2626        assert!(buf.get(0, 0).unwrap().is_empty());
2627
2628        // set_raw() bypasses scissor - this should work
2629        buf.set_raw(0, 0, Cell::from_char('R'));
2630        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('R'));
2631    }
2632
2633    #[test]
2634    fn set_handles_wide_chars() {
2635        let mut buf = Buffer::new(10, 10);
2636
2637        // Set a wide character (width 2)
2638        buf.set(0, 0, Cell::from_char('中'));
2639
2640        // Check head
2641        let head = buf.get(0, 0).unwrap();
2642        assert_eq!(head.content.as_char(), Some('中'));
2643
2644        // Check continuation
2645        let cont = buf.get(1, 0).unwrap();
2646        assert!(cont.is_continuation());
2647        assert!(!cont.is_empty());
2648    }
2649
2650    #[test]
2651    fn set_handles_wide_chars_clipped() {
2652        let mut buf = Buffer::new(10, 10);
2653        buf.push_scissor(Rect::new(0, 0, 1, 10)); // Only column 0 is visible
2654
2655        // Set wide char at 0,0. Tail at x=1 is outside scissor.
2656        // Atomic rejection: entire write is rejected because tail doesn't fit.
2657        buf.set(0, 0, Cell::from_char('中'));
2658
2659        // Head should NOT be written (atomic rejection)
2660        assert!(buf.get(0, 0).unwrap().is_empty());
2661        // Tail position should also be unmodified
2662        assert!(buf.get(1, 0).unwrap().is_empty());
2663    }
2664
2665    // ========== Wide Glyph Continuation Cleanup Tests ==========
2666
2667    #[test]
2668    fn overwrite_wide_head_with_single_clears_tails() {
2669        let mut buf = Buffer::new(10, 1);
2670
2671        // Write a wide character (width 2) at position 0
2672        buf.set(0, 0, Cell::from_char('中'));
2673        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2674        assert!(buf.get(1, 0).unwrap().is_continuation());
2675
2676        // Overwrite the head with a single-width character
2677        buf.set(0, 0, Cell::from_char('A'));
2678
2679        // Head should be replaced
2680        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2681        // Tail (continuation) should be cleared to default
2682        assert!(
2683            buf.get(1, 0).unwrap().is_empty(),
2684            "Continuation at x=1 should be cleared when head is overwritten"
2685        );
2686    }
2687
2688    #[test]
2689    fn set_raw_overwrite_wide_head_with_single_clears_tails() {
2690        let mut buf = Buffer::new(10, 1);
2691
2692        buf.set(0, 0, Cell::from_char('中'));
2693        assert!(buf.get(1, 0).unwrap().is_continuation());
2694        buf.clear_dirty();
2695
2696        buf.set_raw(0, 0, Cell::from_char('A'));
2697
2698        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2699        assert!(
2700            buf.get(1, 0).unwrap().is_empty(),
2701            "set_raw should clear stale continuation tails when overwriting a wide head"
2702        );
2703        let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
2704        assert_eq!(spans, &[DirtySpan::new(0, 2)]);
2705    }
2706
2707    #[test]
2708    fn set_raw_wide_head_preserves_manual_tail_cells() {
2709        let mut buf = Buffer::new(10, 1);
2710
2711        buf.set_raw(0, 0, Cell::from_char('中'));
2712        buf.set_raw(1, 0, Cell::CONTINUATION);
2713        assert!(buf.get(1, 0).unwrap().is_continuation());
2714        buf.clear_dirty();
2715
2716        buf.set_raw(0, 0, Cell::from_char('日'));
2717
2718        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('日'));
2719        assert!(
2720            buf.get(1, 0).unwrap().is_continuation(),
2721            "set_raw wide-head replacement should not clear caller-managed tails"
2722        );
2723        let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
2724        assert_eq!(spans, &[DirtySpan::new(0, 1)]);
2725    }
2726
2727    #[test]
2728    fn overwrite_continuation_with_single_clears_head_and_tails() {
2729        let mut buf = Buffer::new(10, 1);
2730
2731        // Write a wide character at position 0
2732        buf.set(0, 0, Cell::from_char('中'));
2733        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2734        assert!(buf.get(1, 0).unwrap().is_continuation());
2735
2736        // Overwrite the continuation (position 1) with a single-width char
2737        buf.set(1, 0, Cell::from_char('B'));
2738
2739        // The head at position 0 should be cleared
2740        assert!(
2741            buf.get(0, 0).unwrap().is_empty(),
2742            "Head at x=0 should be cleared when its continuation is overwritten"
2743        );
2744        // Position 1 should have the new character
2745        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('B'));
2746    }
2747
2748    #[test]
2749    fn overwrite_wide_with_another_wide() {
2750        let mut buf = Buffer::new(10, 1);
2751
2752        // Write first wide character
2753        buf.set(0, 0, Cell::from_char('中'));
2754        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2755        assert!(buf.get(1, 0).unwrap().is_continuation());
2756
2757        // Overwrite with another wide character
2758        buf.set(0, 0, Cell::from_char('日'));
2759
2760        // Should have new wide character
2761        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('日'));
2762        assert!(
2763            buf.get(1, 0).unwrap().is_continuation(),
2764            "Continuation should still exist for new wide char"
2765        );
2766    }
2767
2768    #[test]
2769    fn overwrite_continuation_middle_of_wide_sequence() {
2770        let mut buf = Buffer::new(10, 1);
2771
2772        // Write two adjacent wide characters: 中 at 0-1, 日 at 2-3
2773        buf.set(0, 0, Cell::from_char('中'));
2774        buf.set(2, 0, Cell::from_char('日'));
2775
2776        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2777        assert!(buf.get(1, 0).unwrap().is_continuation());
2778        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('日'));
2779        assert!(buf.get(3, 0).unwrap().is_continuation());
2780
2781        // Overwrite position 1 (continuation of first wide char)
2782        buf.set(1, 0, Cell::from_char('X'));
2783
2784        // First wide char's head should be cleared
2785        assert!(
2786            buf.get(0, 0).unwrap().is_empty(),
2787            "Head of first wide char should be cleared"
2788        );
2789        // Position 1 has new char
2790        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('X'));
2791        // Second wide char should be unaffected
2792        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('日'));
2793        assert!(buf.get(3, 0).unwrap().is_continuation());
2794    }
2795
2796    #[test]
2797    fn wide_char_overlapping_previous_wide_char() {
2798        let mut buf = Buffer::new(10, 1);
2799
2800        // Write wide char at position 0
2801        buf.set(0, 0, Cell::from_char('中'));
2802        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2803        assert!(buf.get(1, 0).unwrap().is_continuation());
2804
2805        // Write another wide char at position 1 (overlaps with continuation)
2806        buf.set(1, 0, Cell::from_char('日'));
2807
2808        // First wide char's head should be cleared (its continuation was overwritten)
2809        assert!(
2810            buf.get(0, 0).unwrap().is_empty(),
2811            "First wide char head should be cleared when continuation is overwritten by new wide"
2812        );
2813        // New wide char at positions 1-2
2814        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('日'));
2815        assert!(buf.get(2, 0).unwrap().is_continuation());
2816    }
2817
2818    #[test]
2819    fn wide_char_at_end_of_buffer_atomic_reject() {
2820        let mut buf = Buffer::new(5, 1);
2821
2822        // Try to write wide char at position 4 (would need position 5 for tail, out of bounds)
2823        buf.set(4, 0, Cell::from_char('中'));
2824
2825        // Should be rejected atomically - nothing written
2826        assert!(
2827            buf.get(4, 0).unwrap().is_empty(),
2828            "Wide char should be rejected when tail would be out of bounds"
2829        );
2830    }
2831
2832    #[test]
2833    fn three_wide_chars_sequential_cleanup() {
2834        let mut buf = Buffer::new(10, 1);
2835
2836        // Write three wide chars: positions 0-1, 2-3, 4-5
2837        buf.set(0, 0, Cell::from_char('一'));
2838        buf.set(2, 0, Cell::from_char('二'));
2839        buf.set(4, 0, Cell::from_char('三'));
2840
2841        // Verify initial state
2842        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('一'));
2843        assert!(buf.get(1, 0).unwrap().is_continuation());
2844        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('二'));
2845        assert!(buf.get(3, 0).unwrap().is_continuation());
2846        assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('三'));
2847        assert!(buf.get(5, 0).unwrap().is_continuation());
2848
2849        // Overwrite middle wide char's continuation with single char
2850        buf.set(3, 0, Cell::from_char('M'));
2851
2852        // First wide char should be unaffected
2853        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('一'));
2854        assert!(buf.get(1, 0).unwrap().is_continuation());
2855        // Middle wide char's head should be cleared
2856        assert!(buf.get(2, 0).unwrap().is_empty());
2857        // Position 3 has new char
2858        assert_eq!(buf.get(3, 0).unwrap().content.as_char(), Some('M'));
2859        // Third wide char should be unaffected
2860        assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('三'));
2861        assert!(buf.get(5, 0).unwrap().is_continuation());
2862    }
2863
2864    #[test]
2865    fn overwrite_empty_cell_no_cleanup_needed() {
2866        let mut buf = Buffer::new(10, 1);
2867
2868        // Write to an empty cell - no cleanup should be needed
2869        buf.set(5, 0, Cell::from_char('X'));
2870
2871        assert_eq!(buf.get(5, 0).unwrap().content.as_char(), Some('X'));
2872        // Adjacent cells should still be empty
2873        assert!(buf.get(4, 0).unwrap().is_empty());
2874        assert!(buf.get(6, 0).unwrap().is_empty());
2875    }
2876
2877    #[test]
2878    fn wide_char_cleanup_with_opacity() {
2879        let mut buf = Buffer::new(10, 1);
2880
2881        // Set background
2882        buf.set(0, 0, Cell::default().with_bg(PackedRgba::rgb(255, 0, 0)));
2883        buf.set(1, 0, Cell::default().with_bg(PackedRgba::rgb(0, 255, 0)));
2884
2885        // Write wide char
2886        buf.set(0, 0, Cell::from_char('中'));
2887
2888        // Overwrite with opacity
2889        buf.push_opacity(0.5);
2890        buf.set(0, 0, Cell::from_char('A'));
2891        buf.pop_opacity();
2892
2893        // Check head is replaced
2894        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2895        // Continuation should be cleared
2896        assert!(buf.get(1, 0).unwrap().is_empty());
2897    }
2898
2899    #[test]
2900    fn wide_char_continuation_not_treated_as_head() {
2901        let mut buf = Buffer::new(10, 1);
2902
2903        // Write a wide character
2904        buf.set(0, 0, Cell::from_char('中'));
2905
2906        // Verify the continuation cell has zero width (not treated as a head)
2907        let cont = buf.get(1, 0).unwrap();
2908        assert!(cont.is_continuation());
2909        assert_eq!(cont.content.width(), 0);
2910
2911        // Writing another wide char starting at position 1 should work correctly
2912        buf.set(1, 0, Cell::from_char('日'));
2913
2914        // Original head should be cleared
2915        assert!(buf.get(0, 0).unwrap().is_empty());
2916        // New wide char at 1-2
2917        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('日'));
2918        assert!(buf.get(2, 0).unwrap().is_continuation());
2919    }
2920
2921    #[test]
2922    fn wide_char_fill_region() {
2923        let mut buf = Buffer::new(10, 3);
2924
2925        // Fill a 4x2 region with a wide character.
2926        // Wide fills advance by width to prevent overlap churn.
2927        let wide_cell = Cell::from_char('中');
2928        buf.fill(Rect::new(0, 0, 4, 2), wide_cell);
2929
2930        // Row 0 should contain two wide graphemes at x={0,2}.
2931        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2932        assert!(buf.get(1, 0).unwrap().is_continuation());
2933        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('中'));
2934        assert!(buf.get(3, 0).unwrap().is_continuation());
2935    }
2936
2937    #[test]
2938    fn default_buffer_dimensions() {
2939        let buf = Buffer::default();
2940        assert_eq!(buf.width(), 1);
2941        assert_eq!(buf.height(), 1);
2942        assert_eq!(buf.len(), 1);
2943    }
2944
2945    #[test]
2946    fn buffer_partial_eq_impl() {
2947        let buf1 = Buffer::new(5, 5);
2948        let buf2 = Buffer::new(5, 5);
2949        let mut buf3 = Buffer::new(5, 5);
2950        buf3.set(0, 0, Cell::from_char('X'));
2951
2952        assert_eq!(buf1, buf2);
2953        assert_ne!(buf1, buf3);
2954    }
2955
2956    #[test]
2957    fn degradation_level_accessible() {
2958        let mut buf = Buffer::new(10, 10);
2959        assert_eq!(buf.degradation, DegradationLevel::Full);
2960
2961        buf.degradation = DegradationLevel::SimpleBorders;
2962        assert_eq!(buf.degradation, DegradationLevel::SimpleBorders);
2963    }
2964
2965    // --- get_mut ---
2966
2967    #[test]
2968    fn get_mut_modifies_cell() {
2969        let mut buf = Buffer::new(10, 10);
2970        buf.set(3, 3, Cell::from_char('A'));
2971
2972        if let Some(cell) = buf.get_mut(3, 3) {
2973            *cell = Cell::from_char('B');
2974        }
2975
2976        assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('B'));
2977    }
2978
2979    #[test]
2980    fn get_mut_out_of_bounds() {
2981        let mut buf = Buffer::new(5, 5);
2982        assert!(buf.get_mut(10, 10).is_none());
2983    }
2984
2985    // --- clear_with ---
2986
2987    #[test]
2988    fn clear_with_fills_all_cells() {
2989        let mut buf = Buffer::new(5, 3);
2990        let fill_cell = Cell::from_char('*');
2991        buf.clear_with(fill_cell);
2992
2993        for y in 0..3 {
2994            for x in 0..5 {
2995                assert_eq!(buf.get(x, y).unwrap().content.as_char(), Some('*'));
2996            }
2997        }
2998    }
2999
3000    #[test]
3001    fn clear_with_wide_cell_preserves_head_tail_invariant() {
3002        let mut buf = Buffer::new(5, 2);
3003        buf.clear_with(Cell::from_char('中'));
3004
3005        for y in 0..2 {
3006            assert_eq!(buf.get(0, y).unwrap().content.as_char(), Some('中'));
3007            assert!(buf.get(1, y).unwrap().is_continuation());
3008            assert_eq!(buf.get(2, y).unwrap().content.as_char(), Some('中'));
3009            assert!(buf.get(3, y).unwrap().is_continuation());
3010            assert!(buf.get(4, y).unwrap().is_empty());
3011        }
3012    }
3013
3014    // --- cells / cells_mut ---
3015
3016    #[test]
3017    fn cells_slice_has_correct_length() {
3018        let buf = Buffer::new(10, 5);
3019        assert_eq!(buf.cells().len(), 50);
3020    }
3021
3022    #[test]
3023    fn cells_mut_allows_direct_modification() {
3024        let mut buf = Buffer::new(3, 2);
3025        let cells = buf.cells_mut();
3026        cells[0] = Cell::from_char('Z');
3027
3028        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('Z'));
3029    }
3030
3031    // --- row_cells ---
3032
3033    #[test]
3034    fn row_cells_returns_correct_row() {
3035        let mut buf = Buffer::new(5, 3);
3036        buf.set(2, 1, Cell::from_char('R'));
3037
3038        let row = buf.row_cells(1);
3039        assert_eq!(row.len(), 5);
3040        assert_eq!(row[2].content.as_char(), Some('R'));
3041    }
3042
3043    #[test]
3044    fn row_cells_mut_span_marks_once_and_returns_slice() {
3045        let mut buf = Buffer::new(5, 3);
3046        buf.clear_dirty();
3047
3048        let row = buf
3049            .row_cells_mut_span(1, 1, 4)
3050            .expect("row span should be in bounds");
3051        assert_eq!(row.len(), 3);
3052        row[0] = Cell::from_char('A');
3053        row[1] = Cell::from_char('B');
3054        row[2] = Cell::from_char('C');
3055
3056        assert!(buf.is_row_dirty(1));
3057        let spans = buf.dirty_span_row(1).expect("dirty span row").spans();
3058        assert_eq!(spans, &[DirtySpan::new(1, 4)]);
3059        assert_eq!(buf.get(1, 1).unwrap().content.as_char(), Some('A'));
3060        assert_eq!(buf.get(2, 1).unwrap().content.as_char(), Some('B'));
3061        assert_eq!(buf.get(3, 1).unwrap().content.as_char(), Some('C'));
3062    }
3063
3064    #[test]
3065    fn row_cells_mut_span_clamps_to_buffer_width() {
3066        let mut buf = Buffer::new(5, 1);
3067        buf.clear_dirty();
3068
3069        let row = buf
3070            .row_cells_mut_span(0, 3, 99)
3071            .expect("row span should clamp");
3072        assert_eq!(row.len(), 2);
3073        row[0] = Cell::from_char('X');
3074        row[1] = Cell::from_char('Y');
3075
3076        let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
3077        assert_eq!(spans, &[DirtySpan::new(3, 5)]);
3078        assert_eq!(buf.get(3, 0).unwrap().content.as_char(), Some('X'));
3079        assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('Y'));
3080    }
3081
3082    #[test]
3083    fn row_cells_mut_span_rejects_reversed_ranges() {
3084        let mut buf = Buffer::new(5, 1);
3085        buf.clear_dirty();
3086
3087        assert!(buf.row_cells_mut_span(0, 4, 2).is_none());
3088        assert!(
3089            !buf.is_row_dirty(0),
3090            "reversed ranges should not mark rows dirty"
3091        );
3092        assert!(
3093            buf.dirty_span_row(0)
3094                .expect("dirty span row")
3095                .spans()
3096                .is_empty(),
3097            "reversed ranges should not add dirty spans"
3098        );
3099    }
3100
3101    #[test]
3102    #[should_panic]
3103    fn row_cells_out_of_bounds_panics() {
3104        let buf = Buffer::new(5, 3);
3105        let _ = buf.row_cells(5);
3106    }
3107
3108    // --- is_empty ---
3109
3110    #[test]
3111    fn buffer_is_not_empty() {
3112        let buf = Buffer::new(1, 1);
3113        assert!(!buf.is_empty());
3114    }
3115
3116    // --- set_raw out of bounds ---
3117
3118    #[test]
3119    fn set_raw_out_of_bounds_is_safe() {
3120        let mut buf = Buffer::new(5, 5);
3121        buf.set_raw(100, 100, Cell::from_char('X'));
3122        // Should not panic, just be ignored
3123    }
3124
3125    // --- copy_from with offset ---
3126
3127    #[test]
3128    fn copy_from_out_of_bounds_partial() {
3129        let mut src = Buffer::new(5, 5);
3130        src.set(0, 0, Cell::from_char('A'));
3131        src.set(4, 4, Cell::from_char('B'));
3132
3133        let mut dst = Buffer::new(5, 5);
3134        // Copy entire src with offset that puts part out of bounds
3135        dst.copy_from(&src, Rect::new(0, 0, 5, 5), 3, 3);
3136
3137        // (0,0) in src → (3,3) in dst = inside
3138        assert_eq!(dst.get(3, 3).unwrap().content.as_char(), Some('A'));
3139        // (4,4) in src → (7,7) in dst = outside, should be ignored
3140        assert!(dst.get(4, 4).unwrap().is_empty());
3141    }
3142
3143    // --- content_eq with different dimensions ---
3144
3145    #[test]
3146    fn content_eq_different_dimensions() {
3147        let buf1 = Buffer::new(5, 5);
3148        let buf2 = Buffer::new(10, 10);
3149        // Different dimensions should not be equal (different cell counts)
3150        assert!(!buf1.content_eq(&buf2));
3151    }
3152
3153    // ====== Property tests (proptest) ======
3154
3155    mod property {
3156        use super::*;
3157        use proptest::prelude::*;
3158
3159        proptest! {
3160            #[test]
3161            fn buffer_dimensions_are_preserved(width in 1u16..200, height in 1u16..200) {
3162                let buf = Buffer::new(width, height);
3163                prop_assert_eq!(buf.width(), width);
3164                prop_assert_eq!(buf.height(), height);
3165                prop_assert_eq!(buf.len(), width as usize * height as usize);
3166            }
3167
3168            #[test]
3169            fn buffer_get_in_bounds_always_succeeds(width in 1u16..100, height in 1u16..100) {
3170                let buf = Buffer::new(width, height);
3171                for x in 0..width {
3172                    for y in 0..height {
3173                        prop_assert!(buf.get(x, y).is_some(), "get({x},{y}) failed for {width}x{height} buffer");
3174                    }
3175                }
3176            }
3177
3178            #[test]
3179            fn buffer_get_out_of_bounds_returns_none(width in 1u16..50, height in 1u16..50) {
3180                let buf = Buffer::new(width, height);
3181                prop_assert!(buf.get(width, 0).is_none());
3182                prop_assert!(buf.get(0, height).is_none());
3183                prop_assert!(buf.get(width, height).is_none());
3184            }
3185
3186            #[test]
3187            fn buffer_set_get_roundtrip(
3188                width in 5u16..50,
3189                height in 5u16..50,
3190                x in 0u16..5,
3191                y in 0u16..5,
3192                ch_idx in 0u32..26,
3193            ) {
3194                let x = x % width;
3195                let y = y % height;
3196                let ch = char::from_u32('A' as u32 + ch_idx).unwrap();
3197                let mut buf = Buffer::new(width, height);
3198                buf.set(x, y, Cell::from_char(ch));
3199                let got = buf.get(x, y).unwrap();
3200                prop_assert_eq!(got.content.as_char(), Some(ch));
3201            }
3202
3203            #[test]
3204            fn scissor_push_pop_stack_depth(
3205                width in 10u16..50,
3206                height in 10u16..50,
3207                push_count in 1usize..10,
3208            ) {
3209                let mut buf = Buffer::new(width, height);
3210                prop_assert_eq!(buf.scissor_depth(), 1); // base
3211
3212                for i in 0..push_count {
3213                    buf.push_scissor(Rect::new(0, 0, width, height));
3214                    prop_assert_eq!(buf.scissor_depth(), i + 2);
3215                }
3216
3217                for i in (0..push_count).rev() {
3218                    buf.pop_scissor();
3219                    prop_assert_eq!(buf.scissor_depth(), i + 1);
3220                }
3221
3222                // Base cannot be popped
3223                buf.pop_scissor();
3224                prop_assert_eq!(buf.scissor_depth(), 1);
3225            }
3226
3227            #[test]
3228            fn scissor_monotonic_intersection(
3229                width in 20u16..60,
3230                height in 20u16..60,
3231            ) {
3232                // Scissor stack always shrinks or stays the same
3233                let mut buf = Buffer::new(width, height);
3234                let outer = Rect::new(2, 2, width - 4, height - 4);
3235                buf.push_scissor(outer);
3236                let s1 = buf.current_scissor();
3237
3238                let inner = Rect::new(5, 5, 10, 10);
3239                buf.push_scissor(inner);
3240                let s2 = buf.current_scissor();
3241
3242                // Inner scissor must be contained within or equal to outer
3243                prop_assert!(s2.width <= s1.width, "inner width {} > outer width {}", s2.width, s1.width);
3244                prop_assert!(s2.height <= s1.height, "inner height {} > outer height {}", s2.height, s1.height);
3245            }
3246
3247            #[test]
3248            fn opacity_push_pop_stack_depth(
3249                width in 5u16..20,
3250                height in 5u16..20,
3251                push_count in 1usize..10,
3252            ) {
3253                let mut buf = Buffer::new(width, height);
3254                prop_assert_eq!(buf.opacity_depth(), 1);
3255
3256                for i in 0..push_count {
3257                    buf.push_opacity(0.9);
3258                    prop_assert_eq!(buf.opacity_depth(), i + 2);
3259                }
3260
3261                for i in (0..push_count).rev() {
3262                    buf.pop_opacity();
3263                    prop_assert_eq!(buf.opacity_depth(), i + 1);
3264                }
3265
3266                buf.pop_opacity();
3267                prop_assert_eq!(buf.opacity_depth(), 1);
3268            }
3269
3270            #[test]
3271            fn opacity_multiplication_is_monotonic(
3272                opacity1 in 0.0f32..=1.0,
3273                opacity2 in 0.0f32..=1.0,
3274            ) {
3275                let mut buf = Buffer::new(5, 5);
3276                buf.push_opacity(opacity1);
3277                let after_first = buf.current_opacity();
3278                buf.push_opacity(opacity2);
3279                let after_second = buf.current_opacity();
3280
3281                // Effective opacity can only decrease (or stay same at 0 or 1)
3282                prop_assert!(after_second <= after_first + f32::EPSILON,
3283                    "opacity increased: {} -> {}", after_first, after_second);
3284            }
3285
3286            #[test]
3287            fn clear_resets_all_cells(width in 1u16..30, height in 1u16..30) {
3288                let mut buf = Buffer::new(width, height);
3289                // Write some data
3290                for x in 0..width {
3291                    buf.set_raw(x, 0, Cell::from_char('X'));
3292                }
3293                buf.clear();
3294                // All cells should be default (empty)
3295                for y in 0..height {
3296                    for x in 0..width {
3297                        prop_assert!(buf.get(x, y).unwrap().is_empty(),
3298                            "cell ({x},{y}) not empty after clear");
3299                    }
3300                }
3301            }
3302
3303            #[test]
3304            fn content_eq_is_reflexive(width in 1u16..30, height in 1u16..30) {
3305                let buf = Buffer::new(width, height);
3306                prop_assert!(buf.content_eq(&buf));
3307            }
3308
3309            #[test]
3310            fn content_eq_detects_single_change(
3311                width in 5u16..30,
3312                height in 5u16..30,
3313                x in 0u16..5,
3314                y in 0u16..5,
3315            ) {
3316                let x = x % width;
3317                let y = y % height;
3318                let buf1 = Buffer::new(width, height);
3319                let mut buf2 = Buffer::new(width, height);
3320                buf2.set_raw(x, y, Cell::from_char('Z'));
3321                prop_assert!(!buf1.content_eq(&buf2));
3322            }
3323
3324            // --- Executable Invariant Tests (bd-10i.13.2) ---
3325
3326            #[test]
3327            fn dimensions_immutable_through_operations(
3328                width in 5u16..30,
3329                height in 5u16..30,
3330            ) {
3331                let mut buf = Buffer::new(width, height);
3332
3333                // Operations that must not change dimensions
3334                buf.set(0, 0, Cell::from_char('A'));
3335                prop_assert_eq!(buf.width(), width);
3336                prop_assert_eq!(buf.height(), height);
3337                prop_assert_eq!(buf.len(), width as usize * height as usize);
3338
3339                buf.push_scissor(Rect::new(1, 1, 3, 3));
3340                prop_assert_eq!(buf.width(), width);
3341                prop_assert_eq!(buf.height(), height);
3342
3343                buf.push_opacity(0.5);
3344                prop_assert_eq!(buf.width(), width);
3345                prop_assert_eq!(buf.height(), height);
3346
3347                buf.pop_scissor();
3348                buf.pop_opacity();
3349                prop_assert_eq!(buf.width(), width);
3350                prop_assert_eq!(buf.height(), height);
3351
3352                buf.clear();
3353                prop_assert_eq!(buf.width(), width);
3354                prop_assert_eq!(buf.height(), height);
3355                prop_assert_eq!(buf.len(), width as usize * height as usize);
3356            }
3357
3358            #[test]
3359            fn scissor_area_never_increases_random_rects(
3360                width in 20u16..60,
3361                height in 20u16..60,
3362                rects in proptest::collection::vec(
3363                    (0u16..20, 0u16..20, 1u16..15, 1u16..15),
3364                    1..8
3365                ),
3366            ) {
3367                let mut buf = Buffer::new(width, height);
3368                let mut prev_area = (width as u32) * (height as u32);
3369
3370                for (x, y, w, h) in rects {
3371                    buf.push_scissor(Rect::new(x, y, w, h));
3372                    let s = buf.current_scissor();
3373                    let area = (s.width as u32) * (s.height as u32);
3374                    prop_assert!(area <= prev_area,
3375                        "scissor area increased: {} -> {} after push({},{},{},{})",
3376                        prev_area, area, x, y, w, h);
3377                    prev_area = area;
3378                }
3379            }
3380
3381            #[test]
3382            fn opacity_range_invariant_random_sequence(
3383                opacities in proptest::collection::vec(0.0f32..=1.0, 1..15),
3384            ) {
3385                let mut buf = Buffer::new(5, 5);
3386
3387                for &op in &opacities {
3388                    buf.push_opacity(op);
3389                    let current = buf.current_opacity();
3390                    prop_assert!(current >= 0.0, "opacity below 0: {}", current);
3391                    prop_assert!(current <= 1.0 + f32::EPSILON,
3392                        "opacity above 1: {}", current);
3393                }
3394
3395                // Pop everything and verify we get back to 1.0
3396                for _ in &opacities {
3397                    buf.pop_opacity();
3398                }
3399                // After popping all pushed, should be back to base (1.0)
3400                prop_assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
3401            }
3402
3403            #[test]
3404            fn opacity_clamp_out_of_range(
3405                neg in -100.0f32..0.0,
3406                over in 1.01f32..100.0,
3407            ) {
3408                let mut buf = Buffer::new(5, 5);
3409
3410                buf.push_opacity(neg);
3411                prop_assert!(buf.current_opacity() >= 0.0,
3412                    "negative opacity not clamped: {}", buf.current_opacity());
3413                buf.pop_opacity();
3414
3415                buf.push_opacity(over);
3416                prop_assert!(buf.current_opacity() <= 1.0 + f32::EPSILON,
3417                    "over-1 opacity not clamped: {}", buf.current_opacity());
3418            }
3419
3420            #[test]
3421            fn scissor_stack_always_has_base(
3422                pushes in 0usize..10,
3423                pops in 0usize..15,
3424            ) {
3425                let mut buf = Buffer::new(10, 10);
3426
3427                for _ in 0..pushes {
3428                    buf.push_scissor(Rect::new(0, 0, 5, 5));
3429                }
3430                for _ in 0..pops {
3431                    buf.pop_scissor();
3432                }
3433
3434                // Invariant: depth is always >= 1
3435                prop_assert!(buf.scissor_depth() >= 1,
3436                    "scissor depth dropped below 1 after {} pushes, {} pops",
3437                    pushes, pops);
3438            }
3439
3440            #[test]
3441            fn opacity_stack_always_has_base(
3442                pushes in 0usize..10,
3443                pops in 0usize..15,
3444            ) {
3445                let mut buf = Buffer::new(10, 10);
3446
3447                for _ in 0..pushes {
3448                    buf.push_opacity(0.5);
3449                }
3450                for _ in 0..pops {
3451                    buf.pop_opacity();
3452                }
3453
3454                // Invariant: depth is always >= 1
3455                prop_assert!(buf.opacity_depth() >= 1,
3456                    "opacity depth dropped below 1 after {} pushes, {} pops",
3457                    pushes, pops);
3458            }
3459
3460            #[test]
3461            fn cells_len_invariant_always_holds(
3462                width in 1u16..50,
3463                height in 1u16..50,
3464            ) {
3465                let mut buf = Buffer::new(width, height);
3466                let expected = width as usize * height as usize;
3467
3468                prop_assert_eq!(buf.cells().len(), expected);
3469
3470                // After mutations
3471                buf.set(0, 0, Cell::from_char('X'));
3472                prop_assert_eq!(buf.cells().len(), expected);
3473
3474                buf.clear();
3475                prop_assert_eq!(buf.cells().len(), expected);
3476            }
3477
3478            #[test]
3479            fn set_outside_scissor_is_noop(
3480                width in 10u16..30,
3481                height in 10u16..30,
3482            ) {
3483                let mut buf = Buffer::new(width, height);
3484                buf.push_scissor(Rect::new(2, 2, 3, 3));
3485
3486                // Write outside scissor region
3487                buf.set(0, 0, Cell::from_char('X'));
3488                // Should be unmodified (still empty)
3489                let cell = buf.get(0, 0).unwrap();
3490                prop_assert!(cell.is_empty(),
3491                    "cell (0,0) modified outside scissor region");
3492
3493                // Write inside scissor region should work
3494                buf.set(3, 3, Cell::from_char('Y'));
3495                let cell = buf.get(3, 3).unwrap();
3496                prop_assert_eq!(cell.content.as_char(), Some('Y'));
3497            }
3498
3499            // --- Wide Glyph Cleanup Property Tests ---
3500
3501            #[test]
3502            fn wide_char_overwrites_cleanup_tails(
3503                width in 10u16..30,
3504                x in 0u16..8,
3505            ) {
3506                let x = x % (width.saturating_sub(2).max(1));
3507                let mut buf = Buffer::new(width, 1);
3508
3509                // Write wide char
3510                buf.set(x, 0, Cell::from_char('中'));
3511
3512                // If it fit, check structure
3513                if x + 1 < width {
3514                    let head = buf.get(x, 0).unwrap();
3515                    let tail = buf.get(x + 1, 0).unwrap();
3516
3517                    if head.content.as_char() == Some('中') {
3518                        prop_assert!(tail.is_continuation(),
3519                            "tail at x+1={} should be continuation", x + 1);
3520
3521                        // Overwrite head with single char
3522                        buf.set(x, 0, Cell::from_char('A'));
3523                        let new_head = buf.get(x, 0).unwrap();
3524                        let cleared_tail = buf.get(x + 1, 0).unwrap();
3525
3526                        prop_assert_eq!(new_head.content.as_char(), Some('A'));
3527                        prop_assert!(cleared_tail.is_empty(),
3528                            "tail should be cleared after head overwrite");
3529                    }
3530                }
3531            }
3532
3533            #[test]
3534            fn wide_char_atomic_rejection_at_boundary(
3535                width in 3u16..20,
3536            ) {
3537                let mut buf = Buffer::new(width, 1);
3538
3539                // Try to write wide char at last position (needs x and x+1)
3540                let last_pos = width - 1;
3541                buf.set(last_pos, 0, Cell::from_char('中'));
3542
3543                // Should be rejected - cell should remain empty
3544                let cell = buf.get(last_pos, 0).unwrap();
3545                prop_assert!(cell.is_empty(),
3546                    "wide char at boundary position {} (width {}) should be rejected",
3547                    last_pos, width);
3548            }
3549
3550            // =====================================================================
3551            // DoubleBuffer property tests (bd-1rz0.4.4)
3552            // =====================================================================
3553
3554            #[test]
3555            fn double_buffer_swap_is_involution(ops in proptest::collection::vec(proptest::bool::ANY, 0..100)) {
3556                let mut db = DoubleBuffer::new(10, 10);
3557                let initial_idx = db.current_idx;
3558
3559                for do_swap in &ops {
3560                    if *do_swap {
3561                        db.swap();
3562                    }
3563                }
3564
3565                let swap_count = ops.iter().filter(|&&x| x).count();
3566                let expected_idx = if swap_count % 2 == 0 { initial_idx } else { 1 - initial_idx };
3567
3568                prop_assert_eq!(db.current_idx, expected_idx,
3569                    "After {} swaps, index should be {} but was {}",
3570                    swap_count, expected_idx, db.current_idx);
3571            }
3572
3573            #[test]
3574            fn double_buffer_resize_preserves_invariant(
3575                init_w in 1u16..200,
3576                init_h in 1u16..100,
3577                new_w in 1u16..200,
3578                new_h in 1u16..100,
3579            ) {
3580                let mut db = DoubleBuffer::new(init_w, init_h);
3581                db.resize(new_w, new_h);
3582
3583                prop_assert_eq!(db.width(), new_w);
3584                prop_assert_eq!(db.height(), new_h);
3585                prop_assert!(db.dimensions_match(new_w, new_h));
3586            }
3587
3588            #[test]
3589            fn double_buffer_current_previous_disjoint(
3590                width in 1u16..50,
3591                height in 1u16..50,
3592            ) {
3593                let mut db = DoubleBuffer::new(width, height);
3594
3595                // Write to current
3596                db.current_mut().set(0, 0, Cell::from_char('C'));
3597
3598                // Previous should be unaffected
3599                prop_assert!(db.previous().get(0, 0).unwrap().is_empty(),
3600                    "Previous buffer should not reflect changes to current");
3601
3602                // After swap, roles reverse
3603                db.swap();
3604                prop_assert_eq!(db.previous().get(0, 0).unwrap().content.as_char(), Some('C'),
3605                    "After swap, previous should have the 'C' we wrote");
3606            }
3607
3608            #[test]
3609            fn double_buffer_swap_content_semantics(
3610                width in 5u16..30,
3611                height in 5u16..30,
3612            ) {
3613                let mut db = DoubleBuffer::new(width, height);
3614
3615                // Write 'X' to current
3616                db.current_mut().set(0, 0, Cell::from_char('X'));
3617                db.swap();
3618
3619                // Write 'Y' to current (now the other buffer)
3620                db.current_mut().set(0, 0, Cell::from_char('Y'));
3621                db.swap();
3622
3623                // After two swaps, we're back to the buffer with 'X'
3624                prop_assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('X'));
3625                prop_assert_eq!(db.previous().get(0, 0).unwrap().content.as_char(), Some('Y'));
3626            }
3627
3628            #[test]
3629            fn double_buffer_resize_clears_both(
3630                w1 in 5u16..30,
3631                h1 in 5u16..30,
3632                w2 in 5u16..30,
3633                h2 in 5u16..30,
3634            ) {
3635                // Skip if dimensions are the same (resize returns early)
3636                prop_assume!(w1 != w2 || h1 != h2);
3637
3638                let mut db = DoubleBuffer::new(w1, h1);
3639
3640                // Populate both buffers
3641                db.current_mut().set(0, 0, Cell::from_char('A'));
3642                db.swap();
3643                db.current_mut().set(0, 0, Cell::from_char('B'));
3644
3645                // Resize
3646                db.resize(w2, h2);
3647
3648                // Both should be empty
3649                prop_assert!(db.current().get(0, 0).unwrap().is_empty(),
3650                    "Current buffer should be empty after resize");
3651                prop_assert!(db.previous().get(0, 0).unwrap().is_empty(),
3652                    "Previous buffer should be empty after resize");
3653            }
3654        }
3655    }
3656
3657    // ========== Dirty Row Tracking Tests (bd-4kq0.1.1) ==========
3658
3659    #[test]
3660    fn dirty_rows_start_dirty() {
3661        // All rows start dirty to ensure initial diffs see all content.
3662        let buf = Buffer::new(10, 5);
3663        assert_eq!(buf.dirty_row_count(), 5);
3664        for y in 0..5 {
3665            assert!(buf.is_row_dirty(y));
3666        }
3667    }
3668
3669    #[test]
3670    fn dirty_bitmap_starts_full() {
3671        let buf = Buffer::new(4, 3);
3672        assert!(buf.dirty_all());
3673        assert_eq!(buf.dirty_cell_count(), 12);
3674    }
3675
3676    #[test]
3677    fn dirty_bitmap_tracks_single_cell() {
3678        let mut buf = Buffer::new(4, 3);
3679        buf.clear_dirty();
3680        assert!(!buf.dirty_all());
3681        buf.set_raw(1, 1, Cell::from_char('X'));
3682        let idx = 1 + 4;
3683        assert_eq!(buf.dirty_cell_count(), 1);
3684        assert_eq!(buf.dirty_bits()[idx], 1);
3685    }
3686
3687    #[test]
3688    fn dirty_bitmap_dedupes_cells() {
3689        let mut buf = Buffer::new(4, 3);
3690        buf.clear_dirty();
3691        buf.set_raw(2, 2, Cell::from_char('A'));
3692        buf.set_raw(2, 2, Cell::from_char('B'));
3693        assert_eq!(buf.dirty_cell_count(), 1);
3694    }
3695
3696    #[test]
3697    fn set_marks_row_dirty() {
3698        let mut buf = Buffer::new(10, 5);
3699        buf.clear_dirty(); // Reset initial dirty state
3700        buf.set(3, 2, Cell::from_char('X'));
3701        assert!(buf.is_row_dirty(2));
3702        assert!(!buf.is_row_dirty(0));
3703        assert!(!buf.is_row_dirty(1));
3704        assert!(!buf.is_row_dirty(3));
3705        assert!(!buf.is_row_dirty(4));
3706    }
3707
3708    #[test]
3709    fn set_raw_marks_row_dirty() {
3710        let mut buf = Buffer::new(10, 5);
3711        buf.clear_dirty(); // Reset initial dirty state
3712        buf.set_raw(0, 4, Cell::from_char('Z'));
3713        assert!(buf.is_row_dirty(4));
3714        assert_eq!(buf.dirty_row_count(), 1);
3715    }
3716
3717    #[test]
3718    fn clear_marks_all_dirty() {
3719        let mut buf = Buffer::new(10, 5);
3720        buf.clear();
3721        assert_eq!(buf.dirty_row_count(), 5);
3722    }
3723
3724    #[test]
3725    fn clear_dirty_resets_flags() {
3726        let mut buf = Buffer::new(10, 5);
3727        // All rows start dirty; clear_dirty should reset all of them.
3728        assert_eq!(buf.dirty_row_count(), 5);
3729        buf.clear_dirty();
3730        assert_eq!(buf.dirty_row_count(), 0);
3731
3732        // Now mark specific rows dirty and verify clear_dirty resets again.
3733        buf.set(0, 0, Cell::from_char('A'));
3734        buf.set(0, 3, Cell::from_char('B'));
3735        assert_eq!(buf.dirty_row_count(), 2);
3736
3737        buf.clear_dirty();
3738        assert_eq!(buf.dirty_row_count(), 0);
3739    }
3740
3741    #[test]
3742    fn clear_dirty_resets_bitmap() {
3743        let mut buf = Buffer::new(4, 3);
3744        buf.clear();
3745        assert!(buf.dirty_all());
3746        buf.clear_dirty();
3747        assert!(!buf.dirty_all());
3748        assert_eq!(buf.dirty_cell_count(), 0);
3749        assert!(buf.dirty_bits().iter().all(|&b| b == 0));
3750    }
3751
3752    #[test]
3753    fn fill_with_wide_cells_leaves_no_stale_content() {
3754        let mut buf = Buffer::new(5, 1);
3755        for x in 0..5 {
3756            buf.set(x, 0, Cell::from_char('X'));
3757        }
3758        // A width-2 cell filled into a 5-wide rect: heads land at 0 and 2;
3759        // column 4 cannot hold a whole glyph, so `set` drops it there — the
3760        // pre-clear must still purge the old 'X'.
3761        let wide = Cell::from_char('世');
3762        assert_eq!(wide.content.width(), 2);
3763        buf.fill(Rect::new(0, 0, 5, 1), wide);
3764        let trailing = *buf.get(4, 0).expect("in bounds");
3765        assert_ne!(
3766            trailing,
3767            Cell::from_char('X'),
3768            "stale content survived fill"
3769        );
3770        assert_eq!(trailing, Cell::default());
3771        // The two whole glyphs are present.
3772        assert_eq!(*buf.get(0, 0).unwrap(), wide);
3773        assert_eq!(*buf.get(2, 0).unwrap(), wide);
3774    }
3775
3776    #[test]
3777    fn fill_marks_affected_rows_dirty() {
3778        let mut buf = Buffer::new(10, 10);
3779        buf.clear_dirty(); // Reset initial dirty state
3780        buf.fill(Rect::new(0, 2, 5, 3), Cell::from_char('.'));
3781        // Rows 2, 3, 4 should be dirty
3782        assert!(!buf.is_row_dirty(0));
3783        assert!(!buf.is_row_dirty(1));
3784        assert!(buf.is_row_dirty(2));
3785        assert!(buf.is_row_dirty(3));
3786        assert!(buf.is_row_dirty(4));
3787        assert!(!buf.is_row_dirty(5));
3788    }
3789
3790    #[test]
3791    fn get_mut_marks_row_dirty() {
3792        let mut buf = Buffer::new(10, 5);
3793        buf.clear_dirty(); // Reset initial dirty state
3794        if let Some(cell) = buf.get_mut(5, 3) {
3795            cell.fg = PackedRgba::rgb(255, 0, 0);
3796        }
3797        assert!(buf.is_row_dirty(3));
3798        assert_eq!(buf.dirty_row_count(), 1);
3799    }
3800
3801    #[test]
3802    fn cells_mut_marks_all_dirty() {
3803        let mut buf = Buffer::new(10, 5);
3804        let _ = buf.cells_mut();
3805        assert_eq!(buf.dirty_row_count(), 5);
3806    }
3807
3808    #[test]
3809    fn dirty_rows_slice_length_matches_height() {
3810        let buf = Buffer::new(10, 7);
3811        assert_eq!(buf.dirty_rows().len(), 7);
3812    }
3813
3814    #[test]
3815    fn out_of_bounds_set_does_not_dirty() {
3816        let mut buf = Buffer::new(10, 5);
3817        buf.clear_dirty(); // Reset initial dirty state
3818        buf.set(100, 100, Cell::from_char('X'));
3819        assert_eq!(buf.dirty_row_count(), 0);
3820    }
3821
3822    #[test]
3823    fn property_dirty_soundness() {
3824        // Randomized test: any mutation must mark its row.
3825        let mut buf = Buffer::new(20, 10);
3826        let positions = [(3, 0), (5, 2), (0, 9), (19, 5), (10, 7)];
3827        for &(x, y) in &positions {
3828            buf.set(x, y, Cell::from_char('*'));
3829        }
3830        for &(_, y) in &positions {
3831            assert!(
3832                buf.is_row_dirty(y),
3833                "Row {} should be dirty after set({}, {})",
3834                y,
3835                positions.iter().find(|(_, ry)| *ry == y).unwrap().0,
3836                y
3837            );
3838        }
3839    }
3840
3841    #[test]
3842    fn dirty_clear_between_frames() {
3843        // Simulates frame transition: render, diff, clear, render again.
3844        let mut buf = Buffer::new(10, 5);
3845
3846        // All rows start dirty (initial frame needs full diff).
3847        assert_eq!(buf.dirty_row_count(), 5);
3848
3849        // Diff consumes dirty state after initial frame.
3850        buf.clear_dirty();
3851        assert_eq!(buf.dirty_row_count(), 0);
3852
3853        // Frame 1: write to rows 0, 2
3854        buf.set(0, 0, Cell::from_char('A'));
3855        buf.set(0, 2, Cell::from_char('B'));
3856        assert_eq!(buf.dirty_row_count(), 2);
3857
3858        // Diff consumes dirty state
3859        buf.clear_dirty();
3860        assert_eq!(buf.dirty_row_count(), 0);
3861
3862        // Frame 2: write to row 4 only
3863        buf.set(0, 4, Cell::from_char('C'));
3864        assert_eq!(buf.dirty_row_count(), 1);
3865        assert!(buf.is_row_dirty(4));
3866        assert!(!buf.is_row_dirty(0));
3867    }
3868
3869    // ========== Dirty Span Tracking Tests (bd-3e1t.6.2) ==========
3870
3871    #[test]
3872    fn dirty_spans_start_full_dirty() {
3873        let buf = Buffer::new(10, 5);
3874        for y in 0..5 {
3875            let row = buf.dirty_span_row(y).unwrap();
3876            assert!(row.is_full(), "row {y} should start full-dirty");
3877            assert!(row.spans().is_empty(), "row {y} spans should start empty");
3878        }
3879    }
3880
3881    #[test]
3882    fn clear_dirty_resets_spans() {
3883        let mut buf = Buffer::new(10, 5);
3884        buf.clear_dirty();
3885        for y in 0..5 {
3886            let row = buf.dirty_span_row(y).unwrap();
3887            assert!(!row.is_full(), "row {y} should clear full-dirty");
3888            assert!(row.spans().is_empty(), "row {y} spans should be cleared");
3889        }
3890        assert_eq!(buf.dirty_span_overflows, 0);
3891    }
3892
3893    #[test]
3894    fn set_records_dirty_span() {
3895        let mut buf = Buffer::new(20, 2);
3896        buf.clear_dirty();
3897        buf.set(2, 0, Cell::from_char('A'));
3898        let row = buf.dirty_span_row(0).unwrap();
3899        assert_eq!(row.spans(), &[DirtySpan::new(2, 3)]);
3900        assert!(!row.is_full());
3901    }
3902
3903    #[test]
3904    fn set_merges_adjacent_spans() {
3905        let mut buf = Buffer::new(20, 2);
3906        buf.clear_dirty();
3907        buf.set(2, 0, Cell::from_char('A'));
3908        buf.set(3, 0, Cell::from_char('B')); // adjacent, should merge
3909        let row = buf.dirty_span_row(0).unwrap();
3910        assert_eq!(row.spans(), &[DirtySpan::new(2, 4)]);
3911    }
3912
3913    #[test]
3914    fn set_merges_close_spans() {
3915        let mut buf = Buffer::new(20, 2);
3916        buf.clear_dirty();
3917        buf.set(2, 0, Cell::from_char('A'));
3918        buf.set(4, 0, Cell::from_char('B')); // gap of 1, should merge
3919        let row = buf.dirty_span_row(0).unwrap();
3920        assert_eq!(row.spans(), &[DirtySpan::new(2, 5)]);
3921    }
3922
3923    #[test]
3924    fn span_overflow_sets_full_row() {
3925        let width = (DIRTY_SPAN_MAX_SPANS_PER_ROW as u16 + 2) * 3;
3926        let mut buf = Buffer::new(width, 1);
3927        buf.clear_dirty();
3928        for i in 0..(DIRTY_SPAN_MAX_SPANS_PER_ROW + 1) {
3929            let x = (i as u16) * 3;
3930            buf.set(x, 0, Cell::from_char('x'));
3931        }
3932        let row = buf.dirty_span_row(0).unwrap();
3933        assert!(row.is_full());
3934        assert!(row.spans().is_empty());
3935        assert_eq!(buf.dirty_span_overflows, 1);
3936    }
3937
3938    #[test]
3939    fn fill_full_row_marks_full_span() {
3940        let mut buf = Buffer::new(10, 3);
3941        buf.clear_dirty();
3942        let cell = Cell::from_char('x').with_bg(PackedRgba::rgb(0, 0, 0));
3943        buf.fill(Rect::new(0, 1, 10, 1), cell);
3944        let row = buf.dirty_span_row(1).unwrap();
3945        assert!(row.is_full());
3946        assert!(row.spans().is_empty());
3947    }
3948
3949    #[test]
3950    fn get_mut_records_dirty_span() {
3951        let mut buf = Buffer::new(10, 5);
3952        buf.clear_dirty();
3953        let _ = buf.get_mut(5, 3);
3954        let row = buf.dirty_span_row(3).unwrap();
3955        assert_eq!(row.spans(), &[DirtySpan::new(5, 6)]);
3956    }
3957
3958    #[test]
3959    fn cells_mut_marks_all_full_spans() {
3960        let mut buf = Buffer::new(10, 5);
3961        buf.clear_dirty();
3962        let _ = buf.cells_mut();
3963        for y in 0..5 {
3964            let row = buf.dirty_span_row(y).unwrap();
3965            assert!(row.is_full(), "row {y} should be full after cells_mut");
3966        }
3967    }
3968
3969    #[test]
3970    fn dirty_span_config_disabled_skips_rows() {
3971        let mut buf = Buffer::new(10, 1);
3972        buf.clear_dirty();
3973        buf.set_dirty_span_config(DirtySpanConfig::default().with_enabled(false));
3974        buf.set(5, 0, Cell::from_char('x'));
3975        assert!(buf.dirty_span_row(0).is_none());
3976        let stats = buf.dirty_span_stats();
3977        assert_eq!(stats.total_spans, 0);
3978        assert_eq!(stats.span_coverage_cells, 0);
3979    }
3980
3981    #[test]
3982    fn set_dirty_span_config_keeps_dirty_rows_full() {
3983        // Regression: changing the span config used to clear() every span
3984        // row — including the full-row overflow flag — without re-marking
3985        // dirty rows as full. A pre-existing mutation (or a fresh buffer's
3986        // implicit all-dirty state) then stopped being covered by any span,
3987        // and the diff (which scans only the recorded spans of a dirty row
3988        // once new spans exist) silently missed it: a permanent ghost cell.
3989        let mut buf = Buffer::new(10, 2);
3990        buf.clear_dirty();
3991        buf.set(7, 0, Cell::from_char('B')); // pre-config mutation, row 0 dirty
3992
3993        buf.set_dirty_span_config(DirtySpanConfig::default().with_merge_gap(3));
3994
3995        // Row 0 was dirty: it must be conservatively full, not span-less.
3996        let row = buf.dirty_span_row(0).expect("row 0 must have span state");
3997        assert!(
3998            row.is_full(),
3999            "dirty row must go full-row on config change, got spans {:?}",
4000            row.spans()
4001        );
4002        // Row 1 was clean: no span state required.
4003        assert!(!buf.is_row_dirty(1));
4004
4005        // New mutations after the change still record spans without
4006        // narrowing away the pre-config mutation (full-row wins).
4007        buf.set(2, 0, Cell::from_char('A'));
4008        let row = buf.dirty_span_row(0).unwrap();
4009        assert!(row.is_full(), "full-row flag must survive later marks");
4010    }
4011
4012    #[test]
4013    fn set_raw_rewriting_tail_preserves_other_tails_of_wide_glyph() {
4014        // Regression: set_raw of a continuation cell ran the orphan sweep
4015        // from x+1, whose "cannot be owned by x" premise is false for
4016        // continuation writes — rewriting the first tail of a width-3 glyph
4017        // cleared its second (legitimate) tail.
4018        let mut buf = Buffer::new(10, 1);
4019        // Manually assemble a width-3 glyph at x=2 (doc-endorsed pattern);
4020        // width is carried by the GraphemeId's embedded width bits.
4021        let head = Cell::new(CellContent::from_grapheme(GraphemeId::new(0, 0, 3)));
4022        buf.set_raw(2, 0, head);
4023        buf.set_raw(3, 0, Cell::CONTINUATION);
4024        buf.set_raw(4, 0, Cell::CONTINUATION);
4025        assert!(buf.get(4, 0).unwrap().is_continuation());
4026
4027        // Content no-op: rewrite the first tail in place.
4028        buf.set_raw(3, 0, Cell::CONTINUATION);
4029        assert!(
4030            buf.get(4, 0).unwrap().is_continuation(),
4031            "second tail of the width-3 glyph must survive a tail rewrite"
4032        );
4033
4034        // The sweep still clears tails beyond the owning head's extent:
4035        // rebuild as width-2 over the width-3 remains.
4036        let head2 = Cell::new(CellContent::from_grapheme(GraphemeId::new(1, 0, 2)));
4037        buf.set_raw(2, 0, head2);
4038        buf.set_raw(3, 0, Cell::CONTINUATION);
4039        assert!(
4040            !buf.get(4, 0).unwrap().is_continuation(),
4041            "stale tail beyond a narrower rebuilt glyph must be swept"
4042        );
4043    }
4044
4045    #[test]
4046    fn dirty_span_guard_band_expands_span_bounds() {
4047        let mut buf = Buffer::new(10, 1);
4048        buf.clear_dirty();
4049        buf.set_dirty_span_config(DirtySpanConfig::default().with_guard_band(2));
4050        buf.set(5, 0, Cell::from_char('x'));
4051        let row = buf.dirty_span_row(0).unwrap();
4052        assert_eq!(row.spans(), &[DirtySpan::new(3, 8)]);
4053    }
4054
4055    #[test]
4056    fn dirty_span_max_spans_overflow_triggers_full_row() {
4057        let mut buf = Buffer::new(10, 1);
4058        buf.clear_dirty();
4059        buf.set_dirty_span_config(
4060            DirtySpanConfig::default()
4061                .with_max_spans_per_row(1)
4062                .with_merge_gap(0),
4063        );
4064        buf.set(0, 0, Cell::from_char('a'));
4065        buf.set(4, 0, Cell::from_char('b'));
4066        let row = buf.dirty_span_row(0).unwrap();
4067        assert!(row.is_full());
4068        assert!(row.spans().is_empty());
4069        assert_eq!(buf.dirty_span_overflows, 1);
4070    }
4071
4072    #[test]
4073    fn dirty_span_stats_counts_full_rows_and_spans() {
4074        let mut buf = Buffer::new(6, 2);
4075        buf.clear_dirty();
4076        buf.set_dirty_span_config(DirtySpanConfig::default().with_merge_gap(0));
4077        buf.set(1, 0, Cell::from_char('a'));
4078        buf.set(4, 0, Cell::from_char('b'));
4079        buf.mark_dirty_row_full(1);
4080
4081        let stats = buf.dirty_span_stats();
4082        assert_eq!(stats.rows_full_dirty, 1);
4083        assert_eq!(stats.rows_with_spans, 1);
4084        assert_eq!(stats.total_spans, 2);
4085        assert_eq!(stats.max_span_len, 6);
4086        assert_eq!(stats.span_coverage_cells, 8);
4087    }
4088
4089    #[test]
4090    fn dirty_span_stats_reports_overflow_and_full_row() {
4091        let mut buf = Buffer::new(8, 1);
4092        buf.clear_dirty();
4093        buf.set_dirty_span_config(
4094            DirtySpanConfig::default()
4095                .with_max_spans_per_row(1)
4096                .with_merge_gap(0),
4097        );
4098        buf.set(0, 0, Cell::from_char('x'));
4099        buf.set(3, 0, Cell::from_char('y'));
4100
4101        let stats = buf.dirty_span_stats();
4102        assert_eq!(stats.overflows, 1);
4103        assert_eq!(stats.rows_full_dirty, 1);
4104        assert_eq!(stats.total_spans, 0);
4105        assert_eq!(stats.span_coverage_cells, 8);
4106    }
4107
4108    // =====================================================================
4109    // DoubleBuffer tests (bd-1rz0.4.4)
4110    // =====================================================================
4111
4112    #[test]
4113    fn double_buffer_new_has_matching_dimensions() {
4114        let db = DoubleBuffer::new(80, 24);
4115        assert_eq!(db.width(), 80);
4116        assert_eq!(db.height(), 24);
4117        assert!(db.dimensions_match(80, 24));
4118        assert!(!db.dimensions_match(120, 40));
4119    }
4120
4121    #[test]
4122    fn double_buffer_swap_is_o1() {
4123        let mut db = DoubleBuffer::new(80, 24);
4124
4125        // Write to current buffer
4126        db.current_mut().set(0, 0, Cell::from_char('A'));
4127        assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('A'));
4128
4129        // Swap — previous should now have 'A', current should be clean
4130        db.swap();
4131        assert_eq!(
4132            db.previous().get(0, 0).unwrap().content.as_char(),
4133            Some('A')
4134        );
4135        // Current was the old "previous" (empty by default)
4136        assert!(db.current().get(0, 0).unwrap().is_empty());
4137    }
4138
4139    #[test]
4140    fn double_buffer_swap_round_trip() {
4141        let mut db = DoubleBuffer::new(10, 5);
4142
4143        db.current_mut().set(0, 0, Cell::from_char('X'));
4144        db.swap();
4145        db.current_mut().set(0, 0, Cell::from_char('Y'));
4146        db.swap();
4147
4148        // After two swaps, we're back to the buffer that had 'X'
4149        assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('X'));
4150        assert_eq!(
4151            db.previous().get(0, 0).unwrap().content.as_char(),
4152            Some('Y')
4153        );
4154    }
4155
4156    #[test]
4157    fn double_buffer_resize_changes_dimensions() {
4158        let mut db = DoubleBuffer::new(80, 24);
4159        assert!(!db.resize(80, 24)); // No change
4160        assert!(db.resize(120, 40)); // Changed
4161        assert_eq!(db.width(), 120);
4162        assert_eq!(db.height(), 40);
4163        assert!(db.dimensions_match(120, 40));
4164    }
4165
4166    #[test]
4167    fn double_buffer_resize_clears_content() {
4168        let mut db = DoubleBuffer::new(10, 5);
4169        db.current_mut().set(0, 0, Cell::from_char('Z'));
4170        db.swap();
4171        db.current_mut().set(0, 0, Cell::from_char('W'));
4172
4173        db.resize(20, 10);
4174
4175        // Both buffers should be fresh/empty
4176        assert!(db.current().get(0, 0).unwrap().is_empty());
4177        assert!(db.previous().get(0, 0).unwrap().is_empty());
4178    }
4179
4180    #[test]
4181    fn double_buffer_current_and_previous_are_distinct() {
4182        let mut db = DoubleBuffer::new(10, 5);
4183        db.current_mut().set(0, 0, Cell::from_char('C'));
4184
4185        // Previous should not reflect changes to current
4186        assert!(db.previous().get(0, 0).unwrap().is_empty());
4187        assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('C'));
4188    }
4189
4190    // =====================================================================
4191    // AdaptiveDoubleBuffer tests (bd-1rz0.4.2)
4192    // =====================================================================
4193
4194    #[test]
4195    fn adaptive_buffer_new_has_over_allocation() {
4196        let adb = AdaptiveDoubleBuffer::new(80, 24);
4197
4198        // Logical dimensions match requested size
4199        assert_eq!(adb.width(), 80);
4200        assert_eq!(adb.height(), 24);
4201        assert!(adb.dimensions_match(80, 24));
4202
4203        // Capacity should be larger (1.25x growth factor, capped at 200)
4204        // 80 * 0.25 = 20, so capacity_width = 100
4205        // 24 * 0.25 = 6, so capacity_height = 30
4206        assert!(adb.capacity_width() > 80);
4207        assert!(adb.capacity_height() > 24);
4208        assert_eq!(adb.capacity_width(), 100); // 80 + 20
4209        assert_eq!(adb.capacity_height(), 30); // 24 + 6
4210    }
4211
4212    #[test]
4213    fn adaptive_buffer_resize_avoids_reallocation_when_within_capacity() {
4214        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4215
4216        // Small growth should be absorbed by over-allocation
4217        assert!(adb.resize(90, 28)); // Still within (100, 30) capacity
4218        assert_eq!(adb.width(), 90);
4219        assert_eq!(adb.height(), 28);
4220        assert_eq!(adb.stats().resize_avoided, 1);
4221        assert_eq!(adb.stats().resize_reallocated, 0);
4222        assert_eq!(adb.stats().resize_growth, 1);
4223    }
4224
4225    #[test]
4226    fn adaptive_buffer_resize_reallocates_on_growth_beyond_capacity() {
4227        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4228
4229        // Growth beyond capacity requires reallocation
4230        assert!(adb.resize(120, 40)); // Exceeds (100, 30) capacity
4231        assert_eq!(adb.width(), 120);
4232        assert_eq!(adb.height(), 40);
4233        assert_eq!(adb.stats().resize_reallocated, 1);
4234        assert_eq!(adb.stats().resize_avoided, 0);
4235
4236        // New capacity should have headroom
4237        assert!(adb.capacity_width() > 120);
4238        assert!(adb.capacity_height() > 40);
4239    }
4240
4241    #[test]
4242    fn adaptive_buffer_resize_reallocates_on_significant_shrink() {
4243        let mut adb = AdaptiveDoubleBuffer::new(100, 50);
4244
4245        // Shrink below 50% threshold should reallocate
4246        // Threshold: 100 * 0.5 = 50, 50 * 0.5 = 25
4247        assert!(adb.resize(40, 20)); // Below 50% of capacity
4248        assert_eq!(adb.width(), 40);
4249        assert_eq!(adb.height(), 20);
4250        assert_eq!(adb.stats().resize_reallocated, 1);
4251        assert_eq!(adb.stats().resize_shrink, 1);
4252    }
4253
4254    #[test]
4255    fn adaptive_buffer_resize_avoids_reallocation_on_minor_shrink() {
4256        let mut adb = AdaptiveDoubleBuffer::new(100, 50);
4257
4258        // Shrink above 50% threshold should reuse capacity
4259        // Threshold: capacity ~125 * 0.5 = 62.5 for width
4260        // 100 > 62.5, so no reallocation
4261        assert!(adb.resize(80, 40));
4262        assert_eq!(adb.width(), 80);
4263        assert_eq!(adb.height(), 40);
4264        assert_eq!(adb.stats().resize_avoided, 1);
4265        assert_eq!(adb.stats().resize_reallocated, 0);
4266        assert_eq!(adb.stats().resize_shrink, 1);
4267    }
4268
4269    #[test]
4270    fn adaptive_buffer_no_change_returns_false() {
4271        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4272
4273        assert!(!adb.resize(80, 24)); // No change
4274        assert_eq!(adb.stats().resize_avoided, 0);
4275        assert_eq!(adb.stats().resize_reallocated, 0);
4276        assert_eq!(adb.stats().resize_growth, 0);
4277        assert_eq!(adb.stats().resize_shrink, 0);
4278    }
4279
4280    #[test]
4281    fn adaptive_buffer_swap_works() {
4282        let mut adb = AdaptiveDoubleBuffer::new(10, 5);
4283
4284        adb.current_mut().set(0, 0, Cell::from_char('A'));
4285        assert_eq!(
4286            adb.current().get(0, 0).unwrap().content.as_char(),
4287            Some('A')
4288        );
4289
4290        adb.swap();
4291        assert_eq!(
4292            adb.previous().get(0, 0).unwrap().content.as_char(),
4293            Some('A')
4294        );
4295        assert!(adb.current().get(0, 0).unwrap().is_empty());
4296    }
4297
4298    #[test]
4299    fn adaptive_buffer_stats_reset() {
4300        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4301
4302        adb.resize(90, 28);
4303        adb.resize(120, 40);
4304        assert!(adb.stats().resize_avoided > 0 || adb.stats().resize_reallocated > 0);
4305
4306        adb.reset_stats();
4307        assert_eq!(adb.stats().resize_avoided, 0);
4308        assert_eq!(adb.stats().resize_reallocated, 0);
4309        assert_eq!(adb.stats().resize_growth, 0);
4310        assert_eq!(adb.stats().resize_shrink, 0);
4311    }
4312
4313    #[test]
4314    fn adaptive_buffer_memory_efficiency() {
4315        let adb = AdaptiveDoubleBuffer::new(80, 24);
4316
4317        let efficiency = adb.memory_efficiency();
4318        // 80*24 = 1920 logical cells
4319        // 100*30 = 3000 capacity cells
4320        // efficiency = 1920/3000 = 0.64
4321        assert!(efficiency > 0.5);
4322        assert!(efficiency < 1.0);
4323    }
4324
4325    #[test]
4326    fn adaptive_buffer_logical_bounds() {
4327        let adb = AdaptiveDoubleBuffer::new(80, 24);
4328
4329        let bounds = adb.logical_bounds();
4330        assert_eq!(bounds.x, 0);
4331        assert_eq!(bounds.y, 0);
4332        assert_eq!(bounds.width, 80);
4333        assert_eq!(bounds.height, 24);
4334    }
4335
4336    #[test]
4337    fn adaptive_buffer_capacity_clamped_for_large_sizes() {
4338        // Test that over-allocation is capped at ADAPTIVE_MAX_OVERAGE (200)
4339        let adb = AdaptiveDoubleBuffer::new(1000, 500);
4340
4341        // 1000 * 0.25 = 250, capped to 200
4342        // 500 * 0.25 = 125, not capped
4343        assert_eq!(adb.capacity_width(), 1000 + 200); // capped
4344        assert_eq!(adb.capacity_height(), 500 + 125); // not capped
4345    }
4346
4347    #[test]
4348    fn adaptive_capacity_saturates_at_u16_max() {
4349        // The growth headroom must clamp, not overflow, at extreme sizes;
4350        // checked on the pure computation, without allocating the cells.
4351        assert_eq!(
4352            AdaptiveDoubleBuffer::compute_capacity(u16::MAX, u16::MAX),
4353            (u16::MAX, u16::MAX)
4354        );
4355        let half = u16::MAX / 2;
4356        assert_eq!(
4357            AdaptiveDoubleBuffer::compute_capacity(half, half),
4358            (half + ADAPTIVE_MAX_OVERAGE, half + ADAPTIVE_MAX_OVERAGE)
4359        );
4360        assert_eq!(
4361            AdaptiveDoubleBuffer::compute_capacity(u16::MAX - 10, 1),
4362            (u16::MAX, 1)
4363        );
4364    }
4365
4366    #[test]
4367    fn adaptive_stats_avoidance_ratio() {
4368        let mut stats = AdaptiveStats::default();
4369
4370        // Empty stats should return 1.0 (perfect avoidance)
4371        assert!((stats.avoidance_ratio() - 1.0).abs() < f64::EPSILON);
4372
4373        // 3 avoided, 1 reallocated = 75% avoidance
4374        stats.resize_avoided = 3;
4375        stats.resize_reallocated = 1;
4376        assert!((stats.avoidance_ratio() - 0.75).abs() < f64::EPSILON);
4377
4378        // All reallocations = 0% avoidance
4379        stats.resize_avoided = 0;
4380        stats.resize_reallocated = 5;
4381        assert!((stats.avoidance_ratio() - 0.0).abs() < f64::EPSILON);
4382    }
4383
4384    #[test]
4385    fn adaptive_buffer_resize_storm_simulation() {
4386        // Simulate a resize storm (rapid size changes)
4387        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4388
4389        // Simulate user resizing terminal in small increments
4390        for i in 1..=10 {
4391            adb.resize(80 + i, 24 + (i / 2));
4392        }
4393
4394        // Most resizes should have avoided reallocation due to over-allocation
4395        let ratio = adb.stats().avoidance_ratio();
4396        assert!(
4397            ratio > 0.5,
4398            "Expected >50% avoidance ratio, got {:.2}",
4399            ratio
4400        );
4401    }
4402
4403    #[test]
4404    fn adaptive_buffer_width_only_growth() {
4405        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4406
4407        // Grow only width, within capacity
4408        assert!(adb.resize(95, 24)); // 95 < 100 capacity
4409        assert_eq!(adb.stats().resize_avoided, 1);
4410        assert_eq!(adb.stats().resize_growth, 1);
4411    }
4412
4413    #[test]
4414    fn adaptive_buffer_height_only_growth() {
4415        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4416
4417        // Grow only height, within capacity
4418        assert!(adb.resize(80, 28)); // 28 < 30 capacity
4419        assert_eq!(adb.stats().resize_avoided, 1);
4420        assert_eq!(adb.stats().resize_growth, 1);
4421    }
4422
4423    #[test]
4424    fn adaptive_buffer_one_dimension_exceeds_capacity() {
4425        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4426
4427        // One dimension exceeds capacity, should reallocate
4428        assert!(adb.resize(105, 24)); // 105 > 100 capacity, 24 < 30
4429        assert_eq!(adb.stats().resize_reallocated, 1);
4430    }
4431
4432    #[test]
4433    fn adaptive_buffer_current_and_previous_distinct() {
4434        let mut adb = AdaptiveDoubleBuffer::new(10, 5);
4435        adb.current_mut().set(0, 0, Cell::from_char('X'));
4436
4437        // Previous should not reflect changes to current
4438        assert!(adb.previous().get(0, 0).unwrap().is_empty());
4439        assert_eq!(
4440            adb.current().get(0, 0).unwrap().content.as_char(),
4441            Some('X')
4442        );
4443    }
4444
4445    #[test]
4446    fn adaptive_buffer_resize_within_capacity_clears_previous() {
4447        let mut adb = AdaptiveDoubleBuffer::new(10, 5);
4448        adb.current_mut().set(9, 4, Cell::from_char('X'));
4449        adb.swap();
4450
4451        // Shrink within capacity (no reallocation expected)
4452        assert!(adb.resize(8, 4));
4453
4454        // Previous buffer should be cleared to avoid stale content outside bounds.
4455        assert!(adb.previous().get(9, 4).unwrap().is_empty());
4456    }
4457
4458    // Property tests for AdaptiveDoubleBuffer invariants
4459    #[test]
4460    fn adaptive_buffer_invariant_capacity_geq_logical() {
4461        // Test across various sizes that capacity always >= logical
4462        for width in [1u16, 10, 80, 200, 1000, 5000] {
4463            for height in [1u16, 10, 24, 100, 500, 2000] {
4464                let adb = AdaptiveDoubleBuffer::new(width, height);
4465                assert!(
4466                    adb.capacity_width() >= adb.width(),
4467                    "capacity_width {} < logical_width {} for ({}, {})",
4468                    adb.capacity_width(),
4469                    adb.width(),
4470                    width,
4471                    height
4472                );
4473                assert!(
4474                    adb.capacity_height() >= adb.height(),
4475                    "capacity_height {} < logical_height {} for ({}, {})",
4476                    adb.capacity_height(),
4477                    adb.height(),
4478                    width,
4479                    height
4480                );
4481            }
4482        }
4483    }
4484
4485    #[test]
4486    fn adaptive_buffer_invariant_resize_dimensions_correct() {
4487        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4488
4489        // After any resize, logical dimensions should match requested
4490        let test_sizes = [
4491            (100, 50),
4492            (40, 20),
4493            (80, 24),
4494            (200, 100),
4495            (10, 5),
4496            (1000, 500),
4497        ];
4498        for (w, h) in test_sizes {
4499            adb.resize(w, h);
4500            assert_eq!(adb.width(), w, "width mismatch for ({}, {})", w, h);
4501            assert_eq!(adb.height(), h, "height mismatch for ({}, {})", w, h);
4502            assert!(
4503                adb.capacity_width() >= w,
4504                "capacity_width < width for ({}, {})",
4505                w,
4506                h
4507            );
4508            assert!(
4509                adb.capacity_height() >= h,
4510                "capacity_height < height for ({}, {})",
4511                w,
4512                h
4513            );
4514        }
4515    }
4516
4517    // Property test: no-ghosting on shrink
4518    // When buffer shrinks without reallocation, the current buffer is cleared
4519    // to prevent stale content from appearing in the visible area.
4520    #[test]
4521    fn adaptive_buffer_no_ghosting_on_shrink() {
4522        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4523
4524        // Fill the entire logical area with content
4525        for y in 0..adb.height() {
4526            for x in 0..adb.width() {
4527                adb.current_mut().set(x, y, Cell::from_char('X'));
4528            }
4529        }
4530
4531        // Shrink to a smaller size (still above 50% threshold, so no reallocation)
4532        // 80 * 0.5 = 40, so 60 > 40 means no reallocation
4533        adb.resize(60, 20);
4534
4535        // Verify current buffer is cleared after shrink (no stale 'X' visible)
4536        // The current buffer should be empty because resize() calls clear()
4537        for y in 0..adb.height() {
4538            for x in 0..adb.width() {
4539                let cell = adb.current().get(x, y).unwrap();
4540                assert!(
4541                    cell.is_empty(),
4542                    "Ghost content at ({}, {}): expected empty, got {:?}",
4543                    x,
4544                    y,
4545                    cell.content
4546                );
4547            }
4548        }
4549    }
4550
4551    // Property test: shrink-reallocation clears all content
4552    // When buffer shrinks below threshold (requiring reallocation), both buffers
4553    // should be fresh/empty.
4554    #[test]
4555    fn adaptive_buffer_no_ghosting_on_reallocation_shrink() {
4556        let mut adb = AdaptiveDoubleBuffer::new(100, 50);
4557
4558        // Fill both buffers with content
4559        for y in 0..adb.height() {
4560            for x in 0..adb.width() {
4561                adb.current_mut().set(x, y, Cell::from_char('A'));
4562            }
4563        }
4564        adb.swap();
4565        for y in 0..adb.height() {
4566            for x in 0..adb.width() {
4567                adb.current_mut().set(x, y, Cell::from_char('B'));
4568            }
4569        }
4570
4571        // Shrink below 50% threshold, forcing reallocation
4572        adb.resize(30, 15);
4573        assert_eq!(adb.stats().resize_reallocated, 1);
4574
4575        // Both buffers should be fresh/empty
4576        for y in 0..adb.height() {
4577            for x in 0..adb.width() {
4578                assert!(
4579                    adb.current().get(x, y).unwrap().is_empty(),
4580                    "Ghost in current at ({}, {})",
4581                    x,
4582                    y
4583                );
4584                assert!(
4585                    adb.previous().get(x, y).unwrap().is_empty(),
4586                    "Ghost in previous at ({}, {})",
4587                    x,
4588                    y
4589                );
4590            }
4591        }
4592    }
4593
4594    // Property test: growth preserves no-ghosting guarantee
4595    // When buffer grows beyond capacity (requiring reallocation), the new
4596    // capacity area should be empty.
4597    #[test]
4598    fn adaptive_buffer_no_ghosting_on_growth_reallocation() {
4599        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4600
4601        // Fill current buffer
4602        for y in 0..adb.height() {
4603            for x in 0..adb.width() {
4604                adb.current_mut().set(x, y, Cell::from_char('Z'));
4605            }
4606        }
4607
4608        // Grow beyond capacity (100, 30) to force reallocation
4609        adb.resize(150, 60);
4610        assert_eq!(adb.stats().resize_reallocated, 1);
4611
4612        // Entire new buffer should be empty
4613        for y in 0..adb.height() {
4614            for x in 0..adb.width() {
4615                assert!(
4616                    adb.current().get(x, y).unwrap().is_empty(),
4617                    "Ghost at ({}, {}) after growth reallocation",
4618                    x,
4619                    y
4620                );
4621            }
4622        }
4623    }
4624
4625    // Property test: idempotence - same resize is no-op
4626    #[test]
4627    fn adaptive_buffer_resize_idempotent() {
4628        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4629        adb.current_mut().set(5, 5, Cell::from_char('K'));
4630
4631        // Resize to same dimensions should be no-op
4632        let changed = adb.resize(80, 24);
4633        assert!(!changed);
4634
4635        // Content should be preserved
4636        assert_eq!(
4637            adb.current().get(5, 5).unwrap().content.as_char(),
4638            Some('K')
4639        );
4640    }
4641
4642    // =========================================================================
4643    // Dirty Span Tests (bd-3e1t.6.4)
4644    // =========================================================================
4645
4646    #[test]
4647    fn dirty_span_merge_adjacent() {
4648        let mut buf = Buffer::new(100, 1);
4649        buf.clear_dirty(); // Start clean
4650
4651        // Mark [10, 20) dirty
4652        buf.mark_dirty_span(0, 10, 20);
4653        let spans = buf.dirty_span_row(0).unwrap().spans();
4654        assert_eq!(spans.len(), 1);
4655        assert_eq!(spans[0], DirtySpan::new(10, 20));
4656
4657        // Mark [20, 30) dirty (adjacent) -> merge
4658        buf.mark_dirty_span(0, 20, 30);
4659        let spans = buf.dirty_span_row(0).unwrap().spans();
4660        assert_eq!(spans.len(), 1);
4661        assert_eq!(spans[0], DirtySpan::new(10, 30));
4662    }
4663
4664    #[test]
4665    fn dirty_span_merge_overlapping() {
4666        let mut buf = Buffer::new(100, 1);
4667        buf.clear_dirty();
4668
4669        // Mark [10, 20)
4670        buf.mark_dirty_span(0, 10, 20);
4671        // Mark [15, 25) -> merge to [10, 25)
4672        buf.mark_dirty_span(0, 15, 25);
4673
4674        let spans = buf.dirty_span_row(0).unwrap().spans();
4675        assert_eq!(spans.len(), 1);
4676        assert_eq!(spans[0], DirtySpan::new(10, 25));
4677    }
4678
4679    #[test]
4680    fn dirty_span_merge_with_gap() {
4681        let mut buf = Buffer::new(100, 1);
4682        buf.clear_dirty();
4683
4684        // DIRTY_SPAN_MERGE_GAP is 1
4685        // Mark [10, 20)
4686        buf.mark_dirty_span(0, 10, 20);
4687        // Mark [21, 30) -> gap is 1 (index 20) -> merge to [10, 30)
4688        buf.mark_dirty_span(0, 21, 30);
4689
4690        let spans = buf.dirty_span_row(0).unwrap().spans();
4691        assert_eq!(spans.len(), 1);
4692        assert_eq!(spans[0], DirtySpan::new(10, 30));
4693    }
4694
4695    #[test]
4696    fn dirty_span_no_merge_large_gap() {
4697        let mut buf = Buffer::new(100, 1);
4698        buf.clear_dirty();
4699
4700        // Mark [10, 20)
4701        buf.mark_dirty_span(0, 10, 20);
4702        // Mark [22, 30) -> gap is 2 (indices 20, 21) -> no merge
4703        buf.mark_dirty_span(0, 22, 30);
4704
4705        let spans = buf.dirty_span_row(0).unwrap().spans();
4706        assert_eq!(spans.len(), 2);
4707        assert_eq!(spans[0], DirtySpan::new(10, 20));
4708        assert_eq!(spans[1], DirtySpan::new(22, 30));
4709    }
4710
4711    #[test]
4712    fn dirty_span_overflow_to_full() {
4713        let mut buf = Buffer::new(1000, 1);
4714        buf.clear_dirty();
4715
4716        // Create > 64 small spans separated by gaps
4717        for i in 0..DIRTY_SPAN_MAX_SPANS_PER_ROW + 10 {
4718            let start = (i * 4) as u16;
4719            buf.mark_dirty_span(0, start, start + 1);
4720        }
4721
4722        let row = buf.dirty_span_row(0).unwrap();
4723        assert!(row.is_full(), "Row should overflow to full scan");
4724        assert!(
4725            row.spans().is_empty(),
4726            "Spans should be cleared on overflow"
4727        );
4728    }
4729
4730    #[test]
4731    fn dirty_span_bounds_clamping() {
4732        let mut buf = Buffer::new(10, 1);
4733        buf.clear_dirty();
4734
4735        // Mark out of bounds
4736        buf.mark_dirty_span(0, 15, 20);
4737        let spans = buf.dirty_span_row(0).unwrap().spans();
4738        assert!(spans.is_empty());
4739
4740        // Mark crossing bounds
4741        buf.mark_dirty_span(0, 8, 15);
4742        let spans = buf.dirty_span_row(0).unwrap().spans();
4743        assert_eq!(spans.len(), 1);
4744        assert_eq!(spans[0], DirtySpan::new(8, 10)); // Clamped to width
4745    }
4746
4747    #[test]
4748    fn dirty_span_guard_band_clamps_bounds() {
4749        let mut buf = Buffer::new(10, 1);
4750        buf.clear_dirty();
4751        buf.set_dirty_span_config(DirtySpanConfig::default().with_guard_band(5));
4752
4753        buf.mark_dirty_span(0, 2, 3);
4754        let spans = buf.dirty_span_row(0).unwrap().spans();
4755        assert_eq!(spans.len(), 1);
4756        assert_eq!(spans[0], DirtySpan::new(0, 8));
4757
4758        buf.clear_dirty();
4759        buf.mark_dirty_span(0, 8, 10);
4760        let spans = buf.dirty_span_row(0).unwrap().spans();
4761        assert_eq!(spans.len(), 1);
4762        assert_eq!(spans[0], DirtySpan::new(3, 10));
4763    }
4764
4765    #[test]
4766    fn dirty_span_empty_span_is_ignored() {
4767        let mut buf = Buffer::new(10, 1);
4768        buf.clear_dirty();
4769        buf.mark_dirty_span(0, 5, 5);
4770        let spans = buf.dirty_span_row(0).unwrap().spans();
4771        assert!(spans.is_empty());
4772    }
4773
4774    #[test]
4775    fn dirty_all_skips_redundant_bookkeeping_while_preserving_exact_state() {
4776        let mut buf = Buffer::new(16, 4);
4777        assert!(buf.dirty_all());
4778        assert!(buf.is_dirty_witness_consistent());
4779        let gen0 = buf.mutation_gen();
4780
4781        // Out-of-bounds and empty spans when dirty_all=true do not advance mutation_gen.
4782        buf.mark_dirty_span(4, 0, 2);
4783        buf.mark_dirty_span(0, 16, 18);
4784        buf.mark_dirty_span(0, 5, 5);
4785        assert_eq!(buf.mutation_gen(), gen0);
4786
4787        // In-bounds mutations when dirty_all=true advance mutation_gen and preserve full dirty state.
4788        buf.set(3, 1, Cell::from_char('A'));
4789        buf.fill(Rect::new(0, 2, 8, 1), Cell::from_char('B'));
4790        let gen1 = buf.mutation_gen();
4791        assert_ne!(gen1, gen0);
4792        assert!(buf.dirty_all());
4793        assert_eq!(buf.dirty_row_count(), 4);
4794        assert_eq!(buf.dirty_cell_count(), 64);
4795        assert_eq!(buf.dirty_span_stats().rows_full_dirty, 4);
4796        assert_eq!(buf.dirty_span_stats().overflows, 0);
4797        assert!(buf.is_dirty_witness_consistent());
4798
4799        // Clear dirty and perform sparse writes (false branch of dirty_all).
4800        buf.clear_dirty();
4801        assert!(!buf.dirty_all());
4802        assert_eq!(buf.dirty_baseline_gen(), Some(gen1));
4803        assert_eq!(buf.dirty_row_count(), 0);
4804        assert_eq!(buf.dirty_cell_count(), 0);
4805
4806        buf.set(5, 2, Cell::from_char('C'));
4807        assert!(!buf.dirty_all());
4808        assert_eq!(buf.dirty_row_count(), 1);
4809        assert_eq!(buf.dirty_cell_count(), 1);
4810        assert_eq!(
4811            buf.dirty_span_row(2).unwrap().spans(),
4812            &[DirtySpan::new(5, 6)]
4813        );
4814        assert!(buf.is_dirty_witness_consistent());
4815
4816        // Transition back to dirty_all via clear() and verify config toggle + subsequent sparse writes.
4817        buf.clear();
4818        assert!(buf.dirty_all());
4819        assert!(buf.is_dirty_witness_consistent());
4820        buf.set_dirty_span_config(DirtySpanConfig::default().with_enabled(false));
4821        buf.set(1, 0, Cell::from_char('D'));
4822        assert!(buf.dirty_all());
4823        assert!(buf.is_dirty_witness_consistent());
4824        buf.set_dirty_span_config(DirtySpanConfig::default().with_enabled(true));
4825        assert_eq!(buf.dirty_span_stats().rows_full_dirty, 4);
4826        assert!(buf.is_dirty_witness_consistent());
4827    }
4828
4829    #[test]
4830    fn buffer_fill_wide_char_clipping() {
4831        // Regression test for wide character clipping during fill.
4832        // Verifies that wide characters are not written if they would be clipped,
4833        // and that previous wide characters are cleared correctly.
4834        let mut buf = Buffer::new(10, 5);
4835        let wide_cell = Cell::from_char('🦀'); // Width 2
4836
4837        // 1. Fill with wide char
4838        buf.fill(Rect::new(0, 0, 10, 5), wide_cell);
4839
4840        // Verify head and tail
4841        let head = buf.get(0, 0).unwrap();
4842        assert_eq!(head.content.as_char(), Some('🦀'));
4843        assert_eq!(head.content.width(), 2);
4844
4845        let tail = buf.get(1, 0).unwrap();
4846        assert!(tail.is_continuation());
4847
4848        // 2. Overwrite with clipping
4849        // Push a scissor that splits the wide char at (0,0)
4850        buf.push_scissor(Rect::new(0, 0, 1, 5));
4851        // Fill with 'X'
4852        let x_cell = Cell::from_char('X');
4853        buf.fill(Rect::new(0, 0, 10, 5), x_cell);
4854
4855        // (0,0) should be 'X'. (1,0) should be cleared (orphaned tail).
4856        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('X'));
4857        assert!(buf.get(1, 0).unwrap().is_empty()); // Should be default/empty, not continuation
4858
4859        buf.pop_scissor();
4860    }
4861
4862    #[test]
4863    fn buffer_checksum_known_vector() {
4864        let mut empty = Buffer::new(1, 1);
4865        empty.cells.clear();
4866        assert_eq!(buffer_checksum(&empty), BUFFER_CHECKSUM_FNV_OFFSET_BASIS);
4867        assert_eq!(buffer_cells_checksum(&[]), BUFFER_CHECKSUM_FNV_OFFSET_BASIS);
4868
4869        let mut buf = Buffer::new(2, 1);
4870        buf.set_raw(0, 0, Cell::from_char('a'));
4871        buf.set_raw(1, 0, Cell::from_char('b'));
4872        let expected: u64 = 0x5cda_4da4_1d73_449e;
4873        assert_eq!(buffer_checksum(&buf), expected);
4874        assert_eq!(buf.checksum(), expected);
4875
4876        let mut changed = buf.clone();
4877        changed.set_raw(1, 0, Cell::from_char('c'));
4878        assert_ne!(buffer_checksum(&changed), expected);
4879    }
4880
4881    proptest::proptest! {
4882        #[test]
4883        fn buffer_checksum_row_major_order_sensitive(
4884            c1 in proptest::prelude::any::<char>(),
4885            c2 in proptest::prelude::any::<char>(),
4886            fg1 in proptest::prelude::any::<u32>(),
4887            fg2 in proptest::prelude::any::<u32>(),
4888        ) {
4889            let cell1 = Cell::from_char(c1).with_fg(PackedRgba(fg1));
4890            let cell2 = Cell::from_char(c2).with_fg(PackedRgba(fg2));
4891            proptest::prop_assume!(cell1 != cell2);
4892
4893            let mut buf_ab = Buffer::new(2, 2);
4894            buf_ab.set_raw(1, 0, cell1);
4895            buf_ab.set_raw(0, 1, cell2);
4896
4897            let mut buf_ba = Buffer::new(2, 2);
4898            buf_ba.set_raw(1, 0, cell2);
4899            buf_ba.set_raw(0, 1, cell1);
4900
4901            proptest::prop_assert_ne!(buffer_checksum(&buf_ab), buffer_checksum(&buf_ba));
4902        }
4903    }
4904}