1#![forbid(unsafe_code)]
2
3use smallvec::SmallVec;
56
57use crate::budget::DegradationLevel;
58use crate::cell::{Cell, GraphemeId};
59use ftui_core::geometry::Rect;
60
61const DIRTY_SPAN_MAX_SPANS_PER_ROW: usize = 64;
63const DIRTY_SPAN_MERGE_GAP: u16 = 1;
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct DirtySpanConfig {
69 pub enabled: bool,
71 pub max_spans_per_row: usize,
73 pub merge_gap: u16,
75 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 #[must_use]
93 pub fn with_enabled(mut self, enabled: bool) -> Self {
94 self.enabled = enabled;
95 self
96 }
97
98 #[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 #[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 #[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#[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub struct DirtySpanStats {
181 pub rows_full_dirty: usize,
183 pub rows_with_spans: usize,
185 pub total_spans: usize,
187 pub overflows: usize,
189 pub span_coverage_cells: usize,
191 pub max_span_len: usize,
193 pub max_spans_per_row: usize,
195}
196
197#[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 pub degradation: DegradationLevel,
221 dirty_rows: Vec<bool>,
228 dirty_spans: Vec<DirtySpanRow>,
230 dirty_span_config: DirtySpanConfig,
232 dirty_span_overflows: usize,
234 dirty_bits: Vec<u8>,
236 dirty_cells: usize,
238 dirty_all: bool,
240}
241
242impl Buffer {
243 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 dirty_rows: vec![true; height as usize],
274 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 #[inline]
286 pub const fn width(&self) -> u16 {
287 self.width
288 }
289
290 #[inline]
292 pub const fn height(&self) -> u16 {
293 self.height
294 }
295
296 #[inline]
298 pub fn len(&self) -> usize {
299 self.cells.len()
300 }
301
302 #[inline]
304 pub fn is_empty(&self) -> bool {
305 self.cells.is_empty()
306 }
307
308 #[inline]
310 pub const fn bounds(&self) -> Rect {
311 Rect::from_size(self.width, self.height)
312 }
313
314 #[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 #[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 #[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 #[inline]
376 fn mark_dirty_bits_row(&mut self, y: u16) {
377 self.mark_dirty_bits_range(y, 0, self.width);
378 }
379
380 #[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 #[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 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 #[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 #[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 #[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 #[inline]
501 pub fn dirty_rows(&self) -> &[bool] {
502 &self.dirty_rows
503 }
504
505 #[inline]
507 pub fn dirty_row_count(&self) -> usize {
508 self.dirty_rows.iter().filter(|&&d| d).count()
509 }
510
511 #[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 #[inline]
524 #[allow(dead_code)]
525 pub(crate) fn dirty_bits(&self) -> &[u8] {
526 &self.dirty_bits
527 }
528
529 #[inline]
531 #[allow(dead_code)]
532 pub(crate) fn dirty_cell_count(&self) -> usize {
533 self.dirty_cells
534 }
535
536 #[inline]
538 #[allow(dead_code)]
539 pub(crate) fn dirty_all(&self) -> bool {
540 self.dirty_all
541 }
542
543 #[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 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 #[inline]
603 pub fn dirty_span_config(&self) -> DirtySpanConfig {
604 self.dirty_span_config
605 }
606
607 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 #[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 #[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 #[inline]
662 pub(crate) fn cell_mut_unchecked(&mut self, idx: usize) -> &mut Cell {
663 &mut self.cells[idx]
664 }
665
666 #[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 #[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 #[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 #[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 if current.content.width() > 1 {
712 let width = current.content.width();
713 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 else if current.is_continuation() && !new_cell.is_continuation() {
733 let mut back_x = x;
734 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 let width = h_cell.content.width();
745 if (back_x as usize + width) > x as usize {
746 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 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 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 #[inline]
791 fn cleanup_orphaned_tails(&mut self, start_x: u16, y: u16) {
792 if start_x >= self.width {
793 return;
794 }
795
796 let Some(idx) = self.index(start_x, y) else {
798 return;
799 };
800 if !self.cells[idx].is_continuation() {
801 return;
802 }
803
804 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 self.mark_dirty_span(y, start_x, max_x.saturating_add(1));
819 }
820
821 #[inline]
836 pub fn set_fast(&mut self, x: u16, y: u16, cell: Cell) {
837 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 if self.scissor_stack.len() != 1 || self.opacity_stack.len() != 1 {
850 return self.set(x, y, cell);
851 }
852
853 let Some(idx) = self.index(x, y) else {
855 return;
856 };
857
858 let existing = self.cells[idx];
862 if existing.content.width() > 1 || existing.is_continuation() {
863 return self.set(x, y, cell);
864 }
865
866 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 #[inline]
893 pub fn set(&mut self, x: u16, y: u16, cell: Cell) {
894 let width = cell.content.width();
895
896 if width <= 1 {
898 let Some(idx) = self.index(x, y) else {
900 return;
901 };
902
903 if !self.current_scissor().contains(x, y) {
905 return;
906 }
907
908 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 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 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 if cx >= self.width || y >= self.height {
947 return;
948 }
949 if !scissor.contains(cx, y) {
951 return;
952 }
953 }
954
955 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 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 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 final_cell.bg = final_cell.bg.over(old_cell.bg);
988
989 self.cells[idx] = final_cell;
990
991 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 #[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 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 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 #[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 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 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 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 if width > 1 && hx + width > x_start {
1125 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 {
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 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 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 for x in clipped.x..clipped.right() {
1190 self.mark_dirty_span(y, x, x.saturating_add(1));
1191 }
1192 continue;
1193 }
1194 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 #[inline]
1214 pub fn clear(&mut self) {
1215 self.cells.fill(Cell::default());
1216 self.mark_all_dirty();
1217 }
1218
1219 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 #[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 #[inline]
1278 pub fn cells(&self) -> &[Cell] {
1279 &self.cells
1280 }
1281
1282 #[inline]
1286 pub fn cells_mut(&mut self) -> &mut [Cell] {
1287 self.mark_all_dirty();
1288 &mut self.cells
1289 }
1290
1291 #[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 #[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 #[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 #[inline]
1351 pub fn pop_scissor(&mut self) {
1352 if self.scissor_stack.len() > 1 {
1353 self.scissor_stack.pop();
1354 }
1355 }
1356
1357 #[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 #[inline]
1368 pub fn scissor_depth(&self) -> usize {
1369 self.scissor_stack.len()
1370 }
1371
1372 #[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 #[inline]
1389 pub fn pop_opacity(&mut self) {
1390 if self.opacity_stack.len() > 1 {
1391 self.opacity_stack.pop();
1392 }
1393 }
1394
1395 #[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 #[inline]
1406 pub fn opacity_depth(&self) -> usize {
1407 self.opacity_stack.len()
1408 }
1409
1410 pub fn copy_from(&mut self, src: &Buffer, src_rect: Rect, dst_x: u16, dst_y: u16) {
1417 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 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 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 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 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 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 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 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 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#[derive(Debug)]
1538pub struct DoubleBuffer {
1539 buffers: [Buffer; 2],
1540 current_idx: u8,
1542}
1543
1544const ADAPTIVE_GROWTH_FACTOR: f32 = 1.25;
1550
1551const ADAPTIVE_SHRINK_THRESHOLD: f32 = 0.50;
1554
1555const ADAPTIVE_MAX_OVERAGE: u16 = 200;
1557
1558#[derive(Debug)]
1590pub struct AdaptiveDoubleBuffer {
1591 inner: DoubleBuffer,
1593 logical_width: u16,
1595 logical_height: u16,
1597 capacity_width: u16,
1599 capacity_height: u16,
1601 stats: AdaptiveStats,
1603}
1604
1605#[derive(Debug, Clone, Default)]
1607pub struct AdaptiveStats {
1608 pub resize_avoided: u64,
1610 pub resize_reallocated: u64,
1612 pub resize_growth: u64,
1614 pub resize_shrink: u64,
1616}
1617
1618impl AdaptiveStats {
1619 pub fn reset(&mut self) {
1621 *self = Self::default();
1622 }
1623
1624 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 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 #[inline]
1652 pub fn swap(&mut self) {
1653 self.current_idx = 1 - self.current_idx;
1654 }
1655
1656 #[inline]
1658 pub fn current(&self) -> &Buffer {
1659 &self.buffers[self.current_idx as usize]
1660 }
1661
1662 #[inline]
1664 pub fn current_mut(&mut self) -> &mut Buffer {
1665 &mut self.buffers[self.current_idx as usize]
1666 }
1667
1668 #[inline]
1670 pub fn previous(&self) -> &Buffer {
1671 &self.buffers[(1 - self.current_idx) as usize]
1672 }
1673
1674 #[inline]
1676 pub fn previous_mut(&mut self) -> &mut Buffer {
1677 &mut self.buffers[(1 - self.current_idx) as usize]
1678 }
1679
1680 #[inline]
1682 pub fn width(&self) -> u16 {
1683 self.buffers[0].width()
1684 }
1685
1686 #[inline]
1688 pub fn height(&self) -> u16 {
1689 self.buffers[0].height()
1690 }
1691
1692 pub fn resize(&mut self, width: u16, height: u16) -> bool {
1697 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 #[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
1718impl AdaptiveDoubleBuffer {
1723 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 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 fn needs_reallocation(&self, width: u16, height: u16) -> bool {
1758 if width > self.capacity_width || height > self.capacity_height {
1760 return true;
1761 }
1762
1763 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 #[inline]
1775 pub fn swap(&mut self) {
1776 self.inner.swap();
1777 }
1778
1779 #[inline]
1784 pub fn current(&self) -> &Buffer {
1785 self.inner.current()
1786 }
1787
1788 #[inline]
1790 pub fn current_mut(&mut self) -> &mut Buffer {
1791 self.inner.current_mut()
1792 }
1793
1794 #[inline]
1796 pub fn previous(&self) -> &Buffer {
1797 self.inner.previous()
1798 }
1799
1800 #[inline]
1802 pub fn width(&self) -> u16 {
1803 self.logical_width
1804 }
1805
1806 #[inline]
1808 pub fn height(&self) -> u16 {
1809 self.logical_height
1810 }
1811
1812 #[inline]
1814 pub fn capacity_width(&self) -> u16 {
1815 self.capacity_width
1816 }
1817
1818 #[inline]
1820 pub fn capacity_height(&self) -> u16 {
1821 self.capacity_height
1822 }
1823
1824 #[inline]
1826 pub fn stats(&self) -> &AdaptiveStats {
1827 &self.stats
1828 }
1829
1830 pub fn reset_stats(&mut self) {
1832 self.stats.reset();
1833 }
1834
1835 pub fn resize(&mut self, width: u16, height: u16) -> bool {
1847 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 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 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 #[inline]
1881 pub fn dimensions_match(&self, width: u16, height: u16) -> bool {
1882 self.logical_width == width && self.logical_height == height
1883 }
1884
1885 #[inline]
1887 pub fn logical_bounds(&self) -> Rect {
1888 Rect::from_size(self.logical_width, self.logical_height)
1889 }
1890
1891 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 let red = PackedRgba::rgb(255, 0, 0);
1914 buf.set(0, 0, Cell::default().with_bg(red));
1915
1916 let cell = Cell::from_char('X'); 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)); assert!(r.contains(14, 14)); assert!(!r.contains(4, 5)); assert!(!r.contains(15, 5)); assert!(!r.contains(5, 15)); }
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 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')); 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 assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
2075 assert_eq!(buf.scissor_depth(), 1);
2076
2077 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 buf.set(7, 7, Cell::from_char('I'));
2084 assert_eq!(buf.get(7, 7).unwrap().content.as_char(), Some('I'));
2085
2086 buf.set(0, 0, Cell::from_char('O'));
2088 assert!(buf.get(0, 0).unwrap().is_empty());
2089
2090 buf.pop_scissor();
2092 assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
2093 assert_eq!(buf.scissor_depth(), 1);
2094
2095 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 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(); assert_eq!(buf.scissor_depth(), 1);
2116 buf.pop_scissor(); 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 assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
2126 assert_eq!(buf.opacity_depth(), 1);
2127
2128 buf.push_opacity(0.5);
2130 assert!((buf.current_opacity() - 0.5).abs() < f32::EPSILON);
2131 assert_eq!(buf.opacity_depth(), 2);
2132
2133 buf.push_opacity(0.5);
2135 assert!((buf.current_opacity() - 0.25).abs() < f32::EPSILON);
2136 assert_eq!(buf.opacity_depth(), 3);
2137
2138 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 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); assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
2177
2178 buf.push_opacity(-1.0); 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(); 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 assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('#'));
2197
2198 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 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 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 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 src.set(0, 0, Cell::from_char('中'));
2337
2338 let mut dst = Buffer::new(10, 1);
2339 dst.copy_from(&src, Rect::new(0, 0, 1, 1), 0, 0);
2342
2343 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 buf.set(0, 0, Cell::from_char('S'));
2392 assert!(buf.get(0, 0).unwrap().is_empty());
2393
2394 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 buf.set(0, 0, Cell::from_char('中'));
2405
2406 let head = buf.get(0, 0).unwrap();
2408 assert_eq!(head.content.as_char(), Some('中'));
2409
2410 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)); buf.set(0, 0, Cell::from_char('中'));
2424
2425 assert!(buf.get(0, 0).unwrap().is_empty());
2427 assert!(buf.get(1, 0).unwrap().is_empty());
2429 }
2430
2431 #[test]
2434 fn overwrite_wide_head_with_single_clears_tails() {
2435 let mut buf = Buffer::new(10, 1);
2436
2437 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 buf.set(0, 0, Cell::from_char('A'));
2444
2445 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2447 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 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 buf.set(1, 0, Cell::from_char('B'));
2504
2505 assert!(
2507 buf.get(0, 0).unwrap().is_empty(),
2508 "Head at x=0 should be cleared when its continuation is overwritten"
2509 );
2510 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 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 buf.set(0, 0, Cell::from_char('日'));
2525
2526 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 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 buf.set(1, 0, Cell::from_char('X'));
2549
2550 assert!(
2552 buf.get(0, 0).unwrap().is_empty(),
2553 "Head of first wide char should be cleared"
2554 );
2555 assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('X'));
2557 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 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 buf.set(1, 0, Cell::from_char('日'));
2573
2574 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 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 buf.set(4, 0, Cell::from_char('中'));
2590
2591 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 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 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 buf.set(3, 0, Cell::from_char('M'));
2617
2618 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('一'));
2620 assert!(buf.get(1, 0).unwrap().is_continuation());
2621 assert!(buf.get(2, 0).unwrap().is_empty());
2623 assert_eq!(buf.get(3, 0).unwrap().content.as_char(), Some('M'));
2625 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 buf.set(5, 0, Cell::from_char('X'));
2636
2637 assert_eq!(buf.get(5, 0).unwrap().content.as_char(), Some('X'));
2638 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 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 buf.set(0, 0, Cell::from_char('中'));
2653
2654 buf.push_opacity(0.5);
2656 buf.set(0, 0, Cell::from_char('A'));
2657 buf.pop_opacity();
2658
2659 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2661 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 buf.set(0, 0, Cell::from_char('中'));
2671
2672 let cont = buf.get(1, 0).unwrap();
2674 assert!(cont.is_continuation());
2675 assert_eq!(cont.content.width(), 0);
2676
2677 buf.set(1, 0, Cell::from_char('日'));
2679
2680 assert!(buf.get(0, 0).unwrap().is_empty());
2682 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 let wide_cell = Cell::from_char('中');
2694 buf.fill(Rect::new(0, 0, 4, 2), wide_cell);
2695
2696 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 #[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 #[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 #[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 #[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 #[test]
2877 fn buffer_is_not_empty() {
2878 let buf = Buffer::new(1, 1);
2879 assert!(!buf.is_empty());
2880 }
2881
2882 #[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 }
2890
2891 #[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 dst.copy_from(&src, Rect::new(0, 0, 5, 5), 3, 3);
2902
2903 assert_eq!(dst.get(3, 3).unwrap().content.as_char(), Some('A'));
2905 assert!(dst.get(4, 4).unwrap().is_empty());
2907 }
2908
2909 #[test]
2912 fn content_eq_different_dimensions() {
2913 let buf1 = Buffer::new(5, 5);
2914 let buf2 = Buffer::new(10, 10);
2915 assert!(!buf1.content_eq(&buf2));
2917 }
2918
2919 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); 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 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 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 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 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 for x in 0..width {
3057 buf.set_raw(x, 0, Cell::from_char('X'));
3058 }
3059 buf.clear();
3060 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 #[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 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 for _ in &opacities {
3163 buf.pop_opacity();
3164 }
3165 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 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 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 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 buf.set(0, 0, Cell::from_char('X'));
3254 let cell = buf.get(0, 0).unwrap();
3256 prop_assert!(cell.is_empty(),
3257 "cell (0,0) modified outside scissor region");
3258
3259 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 #[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 buf.set(x, 0, Cell::from_char('中'));
3277
3278 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 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 let last_pos = width - 1;
3307 buf.set(last_pos, 0, Cell::from_char('中'));
3308
3309 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 #[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 db.current_mut().set(0, 0, Cell::from_char('C'));
3363
3364 prop_assert!(db.previous().get(0, 0).unwrap().is_empty(),
3366 "Previous buffer should not reflect changes to current");
3367
3368 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 db.current_mut().set(0, 0, Cell::from_char('X'));
3383 db.swap();
3384
3385 db.current_mut().set(0, 0, Cell::from_char('Y'));
3387 db.swap();
3388
3389 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 prop_assume!(w1 != w2 || h1 != h2);
3403
3404 let mut db = DoubleBuffer::new(w1, h1);
3405
3406 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 db.resize(w2, h2);
3413
3414 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 #[test]
3426 fn dirty_rows_start_dirty() {
3427 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(); 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(); 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 assert_eq!(buf.dirty_row_count(), 5);
3495 buf.clear_dirty();
3496 assert_eq!(buf.dirty_row_count(), 0);
3497
3498 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 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 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(); buf.fill(Rect::new(0, 2, 5, 3), Cell::from_char('.'));
3547 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(); 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(); 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 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 let mut buf = Buffer::new(10, 5);
3611
3612 assert_eq!(buf.dirty_row_count(), 5);
3614
3615 buf.clear_dirty();
3617 assert_eq!(buf.dirty_row_count(), 0);
3618
3619 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 buf.clear_dirty();
3626 assert_eq!(buf.dirty_row_count(), 0);
3627
3628 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 #[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')); 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')); 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 let mut buf = Buffer::new(10, 2);
3756 buf.clear_dirty();
3757 buf.set(7, 0, Cell::from_char('B')); buf.set_dirty_span_config(DirtySpanConfig::default().with_merge_gap(3));
3760
3761 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 assert!(!buf.is_row_dirty(1));
3770
3771 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 let mut buf = Buffer::new(10, 1);
3785 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 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 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 #[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 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 db.swap();
3897 assert_eq!(
3898 db.previous().get(0, 0).unwrap().content.as_char(),
3899 Some('A')
3900 );
3901 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 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)); assert!(db.resize(120, 40)); 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 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 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 #[test]
3961 fn adaptive_buffer_new_has_over_allocation() {
3962 let adb = AdaptiveDoubleBuffer::new(80, 24);
3963
3964 assert_eq!(adb.width(), 80);
3966 assert_eq!(adb.height(), 24);
3967 assert!(adb.dimensions_match(80, 24));
3968
3969 assert!(adb.capacity_width() > 80);
3973 assert!(adb.capacity_height() > 24);
3974 assert_eq!(adb.capacity_width(), 100); assert_eq!(adb.capacity_height(), 30); }
3977
3978 #[test]
3979 fn adaptive_buffer_resize_avoids_reallocation_when_within_capacity() {
3980 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
3981
3982 assert!(adb.resize(90, 28)); 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 assert!(adb.resize(120, 40)); 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 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 assert!(adb.resize(40, 20)); 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 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)); 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 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 let adb = AdaptiveDoubleBuffer::new(1000, 500);
4106
4107 assert_eq!(adb.capacity_width(), 1000 + 200); assert_eq!(adb.capacity_height(), 500 + 125); }
4112
4113 #[test]
4114 fn adaptive_stats_avoidance_ratio() {
4115 let mut stats = AdaptiveStats::default();
4116
4117 assert!((stats.avoidance_ratio() - 1.0).abs() < f64::EPSILON);
4119
4120 stats.resize_avoided = 3;
4122 stats.resize_reallocated = 1;
4123 assert!((stats.avoidance_ratio() - 0.75).abs() < f64::EPSILON);
4124
4125 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 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4135
4136 for i in 1..=10 {
4138 adb.resize(80 + i, 24 + (i / 2));
4139 }
4140
4141 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 assert!(adb.resize(95, 24)); 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 assert!(adb.resize(80, 28)); 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 assert!(adb.resize(105, 24)); 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 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 assert!(adb.resize(8, 4));
4200
4201 assert!(adb.previous().get(9, 4).unwrap().is_empty());
4203 }
4204
4205 #[test]
4207 fn adaptive_buffer_invariant_capacity_geq_logical() {
4208 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 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 #[test]
4268 fn adaptive_buffer_no_ghosting_on_shrink() {
4269 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4270
4271 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 adb.resize(60, 20);
4281
4282 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 #[test]
4302 fn adaptive_buffer_no_ghosting_on_reallocation_shrink() {
4303 let mut adb = AdaptiveDoubleBuffer::new(100, 50);
4304
4305 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 adb.resize(30, 15);
4320 assert_eq!(adb.stats().resize_reallocated, 1);
4321
4322 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 #[test]
4345 fn adaptive_buffer_no_ghosting_on_growth_reallocation() {
4346 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4347
4348 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 adb.resize(150, 60);
4357 assert_eq!(adb.stats().resize_reallocated, 1);
4358
4359 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 #[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 let changed = adb.resize(80, 24);
4380 assert!(!changed);
4381
4382 assert_eq!(
4384 adb.current().get(5, 5).unwrap().content.as_char(),
4385 Some('K')
4386 );
4387 }
4388
4389 #[test]
4394 fn dirty_span_merge_adjacent() {
4395 let mut buf = Buffer::new(100, 1);
4396 buf.clear_dirty(); 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 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 buf.mark_dirty_span(0, 10, 20);
4418 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 buf.mark_dirty_span(0, 10, 20);
4434 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 buf.mark_dirty_span(0, 10, 20);
4449 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 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 buf.mark_dirty_span(0, 15, 20);
4484 let spans = buf.dirty_span_row(0).unwrap().spans();
4485 assert!(spans.is_empty());
4486
4487 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)); }
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 let mut buf = Buffer::new(10, 5);
4527 let wide_cell = Cell::from_char('🦀'); buf.fill(Rect::new(0, 0, 10, 5), wide_cell);
4531
4532 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 buf.push_scissor(Rect::new(0, 0, 1, 5));
4543 let x_cell = Cell::from_char('X');
4545 buf.fill(Rect::new(0, 0, 10, 5), x_cell);
4546
4547 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('X'));
4549 assert!(buf.get(1, 0).unwrap().is_empty()); buf.pop_scissor();
4552 }
4553}