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