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(always)]
168 pub(crate) fn spans(&self) -> &[DirtySpan] {
169 &self.spans
170 }
171
172 #[inline(always)]
173 pub(crate) fn is_full(&self) -> bool {
174 self.overflow
175 }
176
177 #[inline(always)]
178 pub(crate) fn is_dirty(&self) -> bool {
179 self.overflow || !self.spans.is_empty()
180 }
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct DirtySpanStats {
186 pub rows_full_dirty: usize,
188 pub rows_with_spans: usize,
190 pub total_spans: usize,
192 pub overflows: usize,
194 pub span_coverage_cells: usize,
196 pub max_span_len: usize,
198 pub max_spans_per_row: usize,
200}
201
202#[derive(Clone)]
215pub struct Buffer {
216 width: u16,
217 height: u16,
218 cells: Vec<Cell>,
219 scissor_stack: Vec<Rect>,
220 opacity_stack: Vec<f32>,
221 pub degradation: DegradationLevel,
226 dirty_rows: Vec<bool>,
233 dirty_spans: Vec<DirtySpanRow>,
235 dirty_span_config: DirtySpanConfig,
237 dirty_span_overflows: usize,
239 dirty_bits: Vec<u8>,
241 dirty_cells: usize,
243 dirty_all: bool,
245 mutation_gen: u64,
247 dirty_baseline_gen: Option<u64>,
249}
250
251impl std::fmt::Debug for Buffer {
252 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253 f.debug_struct("Buffer")
254 .field("width", &self.width)
255 .field("height", &self.height)
256 .field("cells", &self.cells)
257 .field("scissor_stack", &self.scissor_stack)
258 .field("opacity_stack", &self.opacity_stack)
259 .field("degradation", &self.degradation)
260 .field("dirty_rows", &self.dirty_rows)
261 .field("dirty_spans", &self.dirty_spans)
262 .field("dirty_span_config", &self.dirty_span_config)
263 .field("dirty_span_overflows", &self.dirty_span_overflows)
264 .field("dirty_bits", &self.dirty_bits)
265 .field("dirty_cells", &self.dirty_cells)
266 .field("dirty_all", &self.dirty_all)
267 .finish()
268 }
269}
270
271impl Buffer {
272 pub fn new(width: u16, height: u16) -> Self {
280 let width = width.max(1);
281 let height = height.max(1);
282
283 let size = width as usize * height as usize;
284 let cells = vec![Cell::default(); size];
285
286 let dirty_spans = (0..height)
287 .map(|_| DirtySpanRow::new_full())
288 .collect::<Vec<_>>();
289 let dirty_bits = vec![0u8; size];
290 let dirty_cells = size;
291 let dirty_all = true;
292
293 Self {
294 width,
295 height,
296 cells,
297 scissor_stack: vec![Rect::from_size(width, height)],
298 opacity_stack: vec![1.0],
299 degradation: DegradationLevel::Full,
300 dirty_rows: vec![true; height as usize],
303 dirty_spans,
305 dirty_span_config: DirtySpanConfig::default(),
306 dirty_span_overflows: 0,
307 dirty_bits,
308 dirty_cells,
309 dirty_all,
310 mutation_gen: 0,
311 dirty_baseline_gen: None,
312 }
313 }
314
315 #[inline]
317 pub const fn width(&self) -> u16 {
318 self.width
319 }
320
321 #[inline]
323 pub const fn height(&self) -> u16 {
324 self.height
325 }
326
327 #[inline]
329 pub fn len(&self) -> usize {
330 self.cells.len()
331 }
332
333 #[inline]
335 pub fn is_empty(&self) -> bool {
336 self.cells.is_empty()
337 }
338
339 #[inline]
341 pub const fn bounds(&self) -> Rect {
342 Rect::from_size(self.width, self.height)
343 }
344
345 #[inline]
350 pub fn content_height(&self) -> u16 {
351 let default_cell = Cell::default();
352 let width = self.width as usize;
353 for y in (0..self.height).rev() {
354 let row_start = y as usize * width;
355 let row_end = row_start + width;
356 if self.cells[row_start..row_end]
357 .iter()
358 .any(|cell| *cell != default_cell)
359 {
360 return y + 1;
361 }
362 }
363 0
364 }
365
366 #[inline]
371 #[must_use]
372 pub fn checksum(&self) -> u64 {
373 buffer_checksum(self)
374 }
375
376 #[inline]
379 fn advance_mutation_gen(&mut self, token: u64) {
380 self.mutation_gen = self
381 .mutation_gen
382 .wrapping_add(token.wrapping_add(0x9E37_79B9_7F4A_7C15))
383 .wrapping_mul(0xBF58_476D_1CE4_E5B9);
384 }
385
386 #[inline]
391 fn mark_dirty_row(&mut self, y: u16) {
392 if let Some(slot) = self.dirty_rows.get_mut(y as usize) {
393 *slot = true;
394 }
395 }
396
397 #[inline]
399 fn mark_dirty_bits_range(&mut self, y: u16, start: u16, end: u16) {
400 if self.dirty_all {
401 return;
402 }
403 if y >= self.height {
404 return;
405 }
406
407 let width = self.width;
408 if start >= width {
409 return;
410 }
411 let end = end.min(width);
412 if start >= end {
413 return;
414 }
415
416 let row_start = y as usize * width as usize;
417 let slice = &mut self.dirty_bits[row_start + start as usize..row_start + end as usize];
418 let newly_dirty = slice.iter().filter(|&&b| b == 0).count();
419 slice.fill(1);
420 self.dirty_cells = self.dirty_cells.saturating_add(newly_dirty);
421 }
422
423 #[inline]
425 fn mark_dirty_bits_row(&mut self, y: u16) {
426 self.mark_dirty_bits_range(y, 0, self.width);
427 }
428
429 #[inline]
431 fn mark_dirty_row_full(&mut self, y: u16) {
432 if y >= self.height {
433 return;
434 }
435 let sample = self
436 .cells
437 .get(y as usize * self.width as usize)
438 .map_or(0, |c| {
439 u64::from(c.content.raw()) ^ (u64::from(c.fg.0) << 32)
440 });
441 self.advance_mutation_gen((u64::from(y) << 48) | (u64::from(self.width) << 32) ^ sample);
442 if self.dirty_all {
443 return;
444 }
445 self.mark_dirty_row(y);
446 if self.dirty_span_config.enabled
447 && let Some(row) = self.dirty_spans.get_mut(y as usize)
448 {
449 row.set_full();
450 }
451 self.mark_dirty_bits_row(y);
452 }
453
454 #[inline]
456 pub(crate) fn mark_dirty_span(&mut self, y: u16, x0: u16, x1: u16) {
457 if y >= self.height {
458 return;
459 }
460 let width = self.width;
461 let (start, mut end) = if x0 <= x1 { (x0, x1) } else { (x1, x0) };
462 if start >= width {
463 return;
464 }
465 if end > width {
466 end = width;
467 }
468 if start >= end {
469 return;
470 }
471
472 let sample = self
473 .cells
474 .get(y as usize * width as usize + start as usize)
475 .map_or(0, |c| {
476 u64::from(c.content.raw()) ^ (u64::from(c.fg.0) << 32)
477 });
478 self.advance_mutation_gen(
479 ((u64::from(y) << 48) | (u64::from(start) << 32) | u64::from(end)) ^ sample,
480 );
481 if self.dirty_all {
482 return;
483 }
484 self.mark_dirty_row(y);
485 self.mark_dirty_bits_range(y, start, end);
486
487 if !self.dirty_span_config.enabled {
488 return;
489 }
490
491 let guard_band = self.dirty_span_config.guard_band;
492 let span_start = start.saturating_sub(guard_band);
493 let mut span_end = end.saturating_add(guard_band);
494 if span_end > width {
495 span_end = width;
496 }
497 if span_start >= span_end {
498 return;
499 }
500
501 let Some(row) = self.dirty_spans.get_mut(y as usize) else {
502 return;
503 };
504
505 if row.is_full() {
506 return;
507 }
508
509 let new_span = DirtySpan::new(span_start, span_end);
510 let spans = &mut row.spans;
511 let insert_at = spans.partition_point(|span| span.x0 <= new_span.x0);
512 spans.insert(insert_at, new_span);
513
514 let merge_gap = self.dirty_span_config.merge_gap;
516 let mut i = if insert_at > 0 { insert_at - 1 } else { 0 };
517 while i + 1 < spans.len() {
518 let current = spans[i];
519 let next = spans[i + 1];
520 let merge_limit = current.x1.saturating_add(merge_gap);
521 if merge_limit >= next.x0 {
522 spans[i].x1 = current.x1.max(next.x1);
523 spans.remove(i + 1);
524 continue;
525 }
526 i += 1;
527 }
528
529 if spans.len() > self.dirty_span_config.max_spans_per_row {
530 row.set_full();
531 self.dirty_span_overflows = self.dirty_span_overflows.saturating_add(1);
532 }
533 }
534
535 #[inline]
537 pub fn mark_all_dirty(&mut self) {
538 self.advance_mutation_gen((u64::from(self.height) << 32) | u64::from(self.width));
539 self.dirty_rows.fill(true);
540 if self.dirty_span_config.enabled {
541 for row in &mut self.dirty_spans {
542 row.set_full();
543 }
544 } else {
545 for row in &mut self.dirty_spans {
546 row.clear();
547 }
548 }
549 self.dirty_all = true;
550 self.dirty_cells = self.cells.len();
551 self.dirty_baseline_gen = None;
552 }
553
554 #[inline]
558 pub fn clear_dirty(&mut self) {
559 self.dirty_rows.fill(false);
560 for row in &mut self.dirty_spans {
561 row.clear();
562 }
563 self.dirty_span_overflows = 0;
564 self.dirty_bits.fill(0);
565 self.dirty_cells = 0;
566 self.dirty_all = false;
567 self.dirty_baseline_gen = Some(self.mutation_gen);
568 }
569
570 #[inline]
572 pub fn is_row_dirty(&self, y: u16) -> bool {
573 self.dirty_rows.get(y as usize).copied().unwrap_or(false)
574 }
575
576 #[inline]
581 pub fn dirty_rows(&self) -> &[bool] {
582 &self.dirty_rows
583 }
584
585 #[inline]
587 pub fn dirty_row_count(&self) -> usize {
588 self.dirty_rows.iter().filter(|&&d| d).count()
589 }
590
591 #[must_use]
594 pub fn dirty_row_indices(&self) -> Vec<u16> {
595 self.dirty_rows
596 .iter()
597 .enumerate()
598 .filter_map(|(y, &dirty)| dirty.then_some(y as u16))
599 .collect()
600 }
601
602 #[inline]
604 #[must_use]
605 pub const fn mutation_gen(&self) -> u64 {
606 self.mutation_gen
607 }
608
609 #[inline]
612 #[must_use]
613 pub const fn dirty_baseline_gen(&self) -> Option<u64> {
614 self.dirty_baseline_gen
615 }
616
617 #[must_use]
621 pub fn dirty_span_row_count(&self) -> usize {
622 if !self.dirty_span_config.enabled {
623 return self.dirty_row_count();
624 }
625 self.dirty_spans.iter().filter(|row| row.is_dirty()).count()
626 }
627
628 #[must_use]
630 pub fn is_dirty_witness_consistent(&self) -> bool {
631 let height = self.height as usize;
632 if self.dirty_rows.len() != height || self.dirty_spans.len() != height {
633 return false;
634 }
635 let dirty_row_count = self.dirty_row_count();
636 if dirty_row_count == 0 {
637 if self.dirty_all || self.dirty_cells != 0 {
638 return false;
639 }
640 if self.dirty_span_config.enabled && self.dirty_spans.iter().any(DirtySpanRow::is_dirty)
641 {
642 return false;
643 }
644 return true;
645 }
646 if self.dirty_cells < dirty_row_count {
647 return false;
648 }
649 if self.dirty_all && (dirty_row_count != height || self.dirty_cells != self.cells.len()) {
650 return false;
651 }
652 if self.dirty_span_config.enabled {
653 for (y, &row_dirty) in self.dirty_rows.iter().enumerate() {
654 if row_dirty != self.dirty_spans[y].is_dirty() {
655 return false;
656 }
657 }
658 }
659 true
660 }
661
662 #[must_use]
668 pub fn is_dirty_witness_valid_for(&self, old: &Buffer) -> bool {
669 if self.width != old.width || self.height != old.height {
670 return false;
671 }
672 if !self.is_dirty_witness_consistent() {
673 return false;
674 }
675 match self.dirty_baseline_gen {
676 Some(base_gen) => base_gen == old.mutation_gen || base_gen == 0,
677 None => self.dirty_all && self.dirty_row_count() == self.height as usize,
678 }
679 }
680
681 #[inline]
683 pub(crate) fn collect_dirty_witness_for(&self, old: &Buffer) -> (usize, usize, bool, Vec<u16>) {
684 let height = self.height as usize;
685 let span_enabled = self.dirty_span_config.enabled;
686 let mut dirty_rows = Vec::new();
687 let mut span_dirty_rows = 0usize;
688
689 for y in 0..height {
690 let row_dirty = self.dirty_rows.get(y).copied().unwrap_or(false);
691 if row_dirty {
692 dirty_rows.push(y as u16);
693 }
694 if span_enabled {
695 if self.dirty_spans.get(y).is_some_and(DirtySpanRow::is_dirty) {
696 span_dirty_rows += 1;
697 }
698 } else if row_dirty {
699 span_dirty_rows += 1;
700 }
701 }
702
703 let dirty_row_count = dirty_rows.len();
704 let consistent = self.width == old.width
705 && self.height == old.height
706 && self.dirty_rows.len() == height
707 && self.dirty_spans.len() == height
708 && span_dirty_rows == dirty_row_count
709 && if dirty_row_count == 0 {
710 !self.dirty_all && self.dirty_cells == 0
711 } else {
712 self.dirty_cells >= dirty_row_count
713 && (!self.dirty_all
714 || (dirty_row_count == height && self.dirty_cells == self.cells.len()))
715 };
716
717 let baseline_valid = consistent
718 && match self.dirty_baseline_gen {
719 Some(base_gen) => base_gen == old.mutation_gen || base_gen == 0,
720 None => self.dirty_all && dirty_row_count == height,
721 };
722
723 (dirty_row_count, span_dirty_rows, baseline_valid, dirty_rows)
724 }
725
726 #[inline]
728 #[allow(dead_code)]
729 pub(crate) fn dirty_bits(&self) -> &[u8] {
730 &self.dirty_bits
731 }
732
733 #[inline]
735 #[allow(dead_code)]
736 pub(crate) fn dirty_cell_count(&self) -> usize {
737 self.dirty_cells
738 }
739
740 #[inline]
742 #[allow(dead_code)]
743 pub(crate) fn dirty_all(&self) -> bool {
744 self.dirty_all
745 }
746
747 #[inline(always)]
749 #[allow(dead_code)]
750 pub(crate) fn dirty_span_row(&self, y: u16) -> Option<&DirtySpanRow> {
751 if !self.dirty_span_config.enabled {
752 return None;
753 }
754 self.dirty_spans.get(y as usize)
755 }
756
757 pub fn dirty_span_stats(&self) -> DirtySpanStats {
759 if !self.dirty_span_config.enabled {
760 return DirtySpanStats {
761 rows_full_dirty: 0,
762 rows_with_spans: 0,
763 total_spans: 0,
764 overflows: 0,
765 span_coverage_cells: 0,
766 max_span_len: 0,
767 max_spans_per_row: self.dirty_span_config.max_spans_per_row,
768 };
769 }
770
771 let mut rows_full_dirty = 0usize;
772 let mut rows_with_spans = 0usize;
773 let mut total_spans = 0usize;
774 let mut span_coverage_cells = 0usize;
775 let mut max_span_len = 0usize;
776
777 for row in &self.dirty_spans {
778 if row.is_full() {
779 rows_full_dirty += 1;
780 span_coverage_cells += self.width as usize;
781 max_span_len = max_span_len.max(self.width as usize);
782 continue;
783 }
784 if !row.spans().is_empty() {
785 rows_with_spans += 1;
786 }
787 total_spans += row.spans().len();
788 for span in row.spans() {
789 span_coverage_cells += span.len();
790 max_span_len = max_span_len.max(span.len());
791 }
792 }
793
794 DirtySpanStats {
795 rows_full_dirty,
796 rows_with_spans,
797 total_spans,
798 overflows: self.dirty_span_overflows,
799 span_coverage_cells,
800 max_span_len,
801 max_spans_per_row: self.dirty_span_config.max_spans_per_row,
802 }
803 }
804
805 #[inline]
807 pub fn dirty_span_config(&self) -> DirtySpanConfig {
808 self.dirty_span_config
809 }
810
811 pub fn set_dirty_span_config(&mut self, config: DirtySpanConfig) {
821 if self.dirty_span_config == config {
822 return;
823 }
824 self.dirty_span_config = config;
825 for (y, row) in self.dirty_spans.iter_mut().enumerate() {
826 if self.dirty_rows.get(y).copied().unwrap_or(false) {
827 row.set_full();
828 } else {
829 row.clear();
830 }
831 }
832 self.dirty_span_overflows = 0;
833 }
834
835 #[inline]
841 fn index(&self, x: u16, y: u16) -> Option<usize> {
842 if x < self.width && y < self.height {
843 Some(y as usize * self.width as usize + x as usize)
844 } else {
845 None
846 }
847 }
848
849 #[inline]
855 pub(crate) fn index_unchecked(&self, x: u16, y: u16) -> usize {
856 debug_assert!(x < self.width && y < self.height);
857 y as usize * self.width as usize + x as usize
858 }
859
860 #[inline]
866 pub(crate) fn cell_mut_unchecked(&mut self, idx: usize) -> &mut Cell {
867 &mut self.cells[idx]
868 }
869
870 #[inline]
874 #[must_use]
875 pub fn get(&self, x: u16, y: u16) -> Option<&Cell> {
876 self.index(x, y).map(|i| &self.cells[i])
877 }
878
879 #[inline]
884 #[must_use]
885 pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut Cell> {
886 let idx = self.index(x, y)?;
887 self.mark_dirty_span(y, x, x.saturating_add(1));
888 Some(&mut self.cells[idx])
889 }
890
891 #[inline]
898 pub fn get_unchecked(&self, x: u16, y: u16) -> &Cell {
899 let i = self.index_unchecked(x, y);
900 &self.cells[i]
901 }
902
903 #[inline]
907 fn cleanup_overlap(&mut self, x: u16, y: u16, new_cell: &Cell) -> Option<DirtySpan> {
908 let idx = self.index(x, y)?;
909 let current = self.cells[idx];
910 let mut touched = false;
911 let mut min_x = x;
912 let mut max_x = x;
913
914 if current.content.width() > 1 {
916 let width = current.content.width();
917 for i in 1..width {
922 let Some(cx) = x.checked_add(i as u16) else {
923 break;
924 };
925 if let Some(tail_idx) = self.index(cx, y)
926 && self.cells[tail_idx].is_continuation()
927 {
928 self.cells[tail_idx] = Cell::default();
929 touched = true;
930 min_x = min_x.min(cx);
931 max_x = max_x.max(cx);
932 }
933 }
934 }
935 else if current.is_continuation() && !new_cell.is_continuation() {
937 let mut back_x = x;
938 let limit = x.saturating_sub(GraphemeId::MAX_WIDTH as u16);
941
942 while back_x > limit {
943 back_x -= 1;
944 if let Some(h_idx) = self.index(back_x, y) {
945 let h_cell = self.cells[h_idx];
946 if !h_cell.is_continuation() {
947 let width = h_cell.content.width();
949 if (back_x as usize + width) > x as usize {
950 self.cells[h_idx] = Cell::default();
953 touched = true;
954 min_x = min_x.min(back_x);
955 max_x = max_x.max(back_x);
956
957 for i in 1..width {
960 let Some(cx) = back_x.checked_add(i as u16) else {
961 break;
962 };
963 if let Some(tail_idx) = self.index(cx, y) {
964 if self.cells[tail_idx].is_continuation() {
967 self.cells[tail_idx] = Cell::default();
968 touched = true;
969 min_x = min_x.min(cx);
970 max_x = max_x.max(cx);
971 }
972 }
973 }
974 }
975 break;
976 }
977 }
978 }
979 }
980
981 if touched {
982 Some(DirtySpan::new(min_x, max_x.saturating_add(1)))
983 } else {
984 None
985 }
986 }
987
988 #[inline]
995 fn cleanup_orphaned_tails(&mut self, start_x: u16, y: u16) {
996 if start_x >= self.width {
997 return;
998 }
999
1000 let Some(idx) = self.index(start_x, y) else {
1002 return;
1003 };
1004 if !self.cells[idx].is_continuation() {
1005 return;
1006 }
1007
1008 let mut x = start_x;
1010 let mut max_x = x;
1011 let row_end_idx = (y as usize * self.width as usize) + self.width as usize;
1012 let mut curr_idx = idx;
1013
1014 while curr_idx < row_end_idx && self.cells[curr_idx].is_continuation() {
1015 self.cells[curr_idx] = Cell::default();
1016 max_x = x;
1017 x = x.saturating_add(1);
1018 curr_idx += 1;
1019 }
1020
1021 self.mark_dirty_span(y, start_x, max_x.saturating_add(1));
1023 }
1024
1025 #[inline]
1040 pub fn set_fast(&mut self, x: u16, y: u16, cell: Cell) {
1041 let bg_a = cell.bg.a();
1048 if cell.content.width() > 1 || cell.is_continuation() || (bg_a != 255 && bg_a != 0) {
1049 return self.set(x, y, cell);
1050 }
1051
1052 if self.scissor_stack.len() != 1 || self.opacity_stack.len() != 1 {
1054 return self.set(x, y, cell);
1055 }
1056
1057 let Some(idx) = self.index(x, y) else {
1059 return;
1060 };
1061
1062 let existing = self.cells[idx];
1066 if existing.content.width() > 1 || existing.is_continuation() {
1067 return self.set(x, y, cell);
1068 }
1069
1070 let mut final_cell = cell;
1076 if bg_a == 0 {
1077 final_cell.bg = existing.bg;
1078 }
1079
1080 self.cells[idx] = final_cell;
1081 self.mark_dirty_span(y, x, x.saturating_add(1));
1082 self.cleanup_orphaned_tails(x.saturating_add(1), y);
1083 }
1084
1085 #[inline]
1097 pub fn set(&mut self, x: u16, y: u16, cell: Cell) {
1098 let width = cell.content.width();
1099
1100 if width <= 1 {
1102 let Some(idx) = self.index(x, y) else {
1104 return;
1105 };
1106
1107 if !self.current_scissor().contains(x, y) {
1109 return;
1110 }
1111
1112 let mut span_start = x;
1114 let mut span_end = x.saturating_add(1);
1115 if let Some(span) = self.cleanup_overlap(x, y, &cell) {
1116 span_start = span_start.min(span.x0);
1117 span_end = span_end.max(span.x1);
1118 }
1119
1120 let existing_bg = self.cells[idx].bg;
1121
1122 let mut final_cell = if self.current_opacity() < 1.0 {
1124 let opacity = self.current_opacity();
1125 Cell {
1126 fg: cell.fg.with_opacity(opacity),
1127 bg: cell.bg.with_opacity(opacity),
1128 ..cell
1129 }
1130 } else {
1131 cell
1132 };
1133
1134 final_cell.bg = final_cell.bg.over(existing_bg);
1135
1136 self.cells[idx] = final_cell;
1137 self.mark_dirty_span(y, span_start, span_end);
1138 self.cleanup_orphaned_tails(x.saturating_add(1), y);
1139 return;
1140 }
1141
1142 let scissor = self.current_scissor();
1145 for i in 0..width {
1146 let Some(cx) = x.checked_add(i as u16) else {
1147 return;
1148 };
1149 if cx >= self.width || y >= self.height {
1151 return;
1152 }
1153 if !scissor.contains(cx, y) {
1155 return;
1156 }
1157 }
1158
1159 let mut span_start = x;
1163 let mut span_end = x.saturating_add(width as u16);
1164 if let Some(span) = self.cleanup_overlap(x, y, &cell) {
1165 span_start = span_start.min(span.x0);
1166 span_end = span_end.max(span.x1);
1167 }
1168 for i in 1..width {
1169 if let Some(span) = self.cleanup_overlap(x + i as u16, y, &Cell::CONTINUATION) {
1171 span_start = span_start.min(span.x0);
1172 span_end = span_end.max(span.x1);
1173 }
1174 }
1175
1176 let idx = self.index_unchecked(x, y);
1178 let old_cell = self.cells[idx];
1179 let mut final_cell = if self.current_opacity() < 1.0 {
1180 let opacity = self.current_opacity();
1181 Cell {
1182 fg: cell.fg.with_opacity(opacity),
1183 bg: cell.bg.with_opacity(opacity),
1184 ..cell
1185 }
1186 } else {
1187 cell
1188 };
1189
1190 final_cell.bg = final_cell.bg.over(old_cell.bg);
1192
1193 self.cells[idx] = final_cell;
1194
1195 for i in 1..width {
1198 let idx = self.index_unchecked(x + i as u16, y);
1199 self.cells[idx] = Cell::CONTINUATION;
1200 }
1201 self.mark_dirty_span(y, span_start, span_end);
1202 self.cleanup_orphaned_tails(x.saturating_add(width as u16), y);
1203 }
1204
1205 #[inline]
1218 pub fn set_raw(&mut self, x: u16, y: u16, cell: Cell) {
1219 if let Some(idx) = self.index(x, y) {
1220 let mut span = DirtySpan::new(x, x.saturating_add(1));
1221 let raw_wide_head = cell.content.width() > 1 && !cell.is_continuation();
1222
1223 if !raw_wide_head && let Some(cleanup_span) = self.cleanup_overlap(x, y, &cell) {
1224 span = DirtySpan::new(span.x0.min(cleanup_span.x0), span.x1.max(cleanup_span.x1));
1225 }
1226 self.cells[idx] = cell;
1227 self.mark_dirty_span(y, span.x0, span.x1);
1228 if !raw_wide_head {
1229 let sweep_from = if cell.is_continuation() {
1238 self.continuation_owner_extent(x, y)
1239 .unwrap_or_else(|| x.saturating_add(1))
1240 } else {
1241 x.saturating_add(1)
1242 };
1243 self.cleanup_orphaned_tails(sweep_from, y);
1244 }
1245 }
1246 }
1247
1248 fn continuation_owner_extent(&self, x: u16, y: u16) -> Option<u16> {
1252 let limit = x.saturating_sub(GraphemeId::MAX_WIDTH as u16);
1253 let mut back_x = x;
1254 while back_x > limit {
1255 back_x -= 1;
1256 let idx = self.index(back_x, y)?;
1257 let cell = self.cells[idx];
1258 if !cell.is_continuation() {
1259 let end = back_x.saturating_add(cell.content.width() as u16);
1260 return (end > x).then_some(end);
1261 }
1262 }
1263 None
1264 }
1265
1266 #[inline]
1270 pub fn fill(&mut self, rect: Rect, cell: Cell) {
1271 let clipped = self.current_scissor().intersection(&rect);
1272 if clipped.is_empty() {
1273 return;
1274 }
1275
1276 let cell_width = cell.content.width();
1279 if cell_width <= 1
1280 && !cell.is_continuation()
1281 && self.current_opacity() >= 1.0
1282 && cell.bg.a() == 255
1283 && clipped.x == 0
1284 && clipped.width == self.width
1285 {
1286 let row_width = self.width as usize;
1287 for y in clipped.y..clipped.bottom() {
1288 let row_start = y as usize * row_width;
1289 let row_end = row_start + row_width;
1290 self.cells[row_start..row_end].fill(cell);
1291 self.mark_dirty_row_full(y);
1292 }
1293 return;
1294 }
1295
1296 if cell_width <= 1
1300 && !cell.is_continuation()
1301 && self.current_opacity() >= 1.0
1302 && cell.bg.a() == 255
1303 && self.scissor_stack.len() == 1
1304 {
1305 let row_width = self.width as usize;
1306 let x_start = clipped.x as usize;
1307 let x_end = clipped.right() as usize;
1308 for y in clipped.y..clipped.bottom() {
1309 let row_start = y as usize * row_width;
1310 let mut dirty_left = clipped.x;
1311 let mut dirty_right = clipped.right();
1312
1313 if x_start > 0 && self.cells[row_start + x_start].is_continuation() {
1316 let mut head_found = None;
1317 for hx in (0..x_start).rev() {
1318 if !self.cells[row_start + hx].is_continuation() {
1319 head_found = Some(hx);
1320 break;
1321 }
1322 }
1323
1324 if let Some(hx) = head_found {
1325 let c = self.cells[row_start + hx];
1326 let width = c.content.width();
1327 if width > 1 && hx + width > x_start {
1329 for cx in hx..x_start {
1332 self.cells[row_start + cx] = Cell::default();
1333 }
1334 dirty_left = hx as u16;
1335 }
1336 }
1337 }
1338
1339 {
1342 let mut cx = x_end;
1343 while cx < row_width && self.cells[row_start + cx].is_continuation() {
1344 self.cells[row_start + cx] = Cell::default();
1345 dirty_right = (cx as u16).saturating_add(1);
1346 cx += 1;
1347 }
1348 }
1349
1350 self.cells[row_start + x_start..row_start + x_end].fill(cell);
1351 self.mark_dirty_span(y, dirty_left, dirty_right);
1352 }
1353 return;
1354 }
1355
1356 self.push_scissor(clipped);
1358
1359 let step = cell.content.width().max(1) as u16;
1360 let opacity = self.current_opacity();
1361 let single_cell = cell_width <= 1 && !cell.is_continuation();
1362 let fill_cell = if opacity < 1.0 {
1363 Cell {
1364 fg: cell.fg.with_opacity(opacity),
1365 bg: cell.bg.with_opacity(opacity),
1366 ..cell
1367 }
1368 } else {
1369 cell
1370 };
1371 for y in clipped.y..clipped.bottom() {
1372 let row_start = y as usize * self.width as usize;
1373 let start = row_start + clipped.x as usize;
1374 let end = row_start + clipped.right() as usize;
1375 if single_cell
1380 && (clipped.right() == self.width || !self.cells[end].is_continuation())
1381 && self.cells[start..end]
1382 .iter()
1383 .all(|old| !old.is_continuation() && old.content.width() <= 1)
1384 {
1385 for old in &mut self.cells[start..end] {
1386 *old = Cell {
1387 bg: fill_cell.bg.over(old.bg),
1388 ..fill_cell
1389 };
1390 }
1391 for x in clipped.x..clipped.right() {
1394 self.mark_dirty_span(y, x, x.saturating_add(1));
1395 }
1396 continue;
1397 }
1398 for x in clipped.x..clipped.right() {
1404 self.set(x, y, Cell::default());
1405 }
1406 let mut x = clipped.x;
1407 while x < clipped.right() {
1408 self.set(x, y, cell);
1409 x = x.saturating_add(step);
1410 }
1411 }
1412
1413 self.pop_scissor();
1414 }
1415
1416 #[inline]
1418 pub fn clear(&mut self) {
1419 self.cells.fill(Cell::default());
1420 self.mark_all_dirty();
1421 self.mutation_gen = 0;
1422 }
1423
1424 pub fn reset_for_frame(&mut self) {
1429 self.scissor_stack.truncate(1);
1430 if let Some(base) = self.scissor_stack.first_mut() {
1431 *base = Rect::from_size(self.width, self.height);
1432 } else {
1433 self.scissor_stack
1434 .push(Rect::from_size(self.width, self.height));
1435 }
1436
1437 self.opacity_stack.truncate(1);
1438 if let Some(base) = self.opacity_stack.first_mut() {
1439 *base = 1.0;
1440 } else {
1441 self.opacity_stack.push(1.0);
1442 }
1443
1444 self.clear();
1445 }
1446
1447 #[inline]
1449 pub fn clear_with(&mut self, cell: Cell) {
1450 if cell.is_continuation() {
1451 self.clear();
1452 return;
1453 }
1454
1455 let width = cell.content.width();
1456 if width <= 1 {
1457 self.cells.fill(cell);
1458 self.mark_all_dirty();
1459 return;
1460 }
1461
1462 self.cells.fill(Cell::default());
1463 let step = width as u16;
1464 for y in 0..self.height {
1465 let row_start = y as usize * self.width as usize;
1466 let mut x = 0u16;
1467 while x.saturating_add(step) <= self.width {
1468 let head_idx = row_start + x as usize;
1469 self.cells[head_idx] = cell;
1470 for off in 1..step {
1471 self.cells[head_idx + off as usize] = Cell::CONTINUATION;
1472 }
1473 x = x.saturating_add(step);
1474 }
1475 }
1476 self.mark_all_dirty();
1477 }
1478
1479 #[inline]
1483 pub fn cells(&self) -> &[Cell] {
1484 &self.cells
1485 }
1486
1487 #[inline]
1491 pub fn cells_mut(&mut self) -> &mut [Cell] {
1492 self.mark_all_dirty();
1493 &mut self.cells
1494 }
1495
1496 #[inline]
1502 pub fn row_cells(&self, y: u16) -> &[Cell] {
1503 let start = y as usize * self.width as usize;
1504 &self.cells[start..start + self.width as usize]
1505 }
1506
1507 #[inline]
1517 pub fn row_cells_mut_span(&mut self, y: u16, x0: u16, x1: u16) -> Option<&mut [Cell]> {
1518 if y >= self.height {
1519 return None;
1520 }
1521 if x0 >= x1 {
1522 return None;
1523 }
1524
1525 let start = x0.min(self.width);
1526 let end = x1.min(self.width);
1527 if start >= end {
1528 return None;
1529 }
1530
1531 self.mark_dirty_span(y, start, end);
1532
1533 let row_start = y as usize * self.width as usize;
1534 let slice_start = row_start + start as usize;
1535 let slice_end = row_start + end as usize;
1536 Some(&mut self.cells[slice_start..slice_end])
1537 }
1538
1539 #[inline]
1546 pub fn push_scissor(&mut self, rect: Rect) {
1547 let current = self.current_scissor();
1548 let intersected = current.intersection(&rect);
1549 self.scissor_stack.push(intersected);
1550 }
1551
1552 #[inline]
1556 pub fn pop_scissor(&mut self) {
1557 if self.scissor_stack.len() > 1 {
1558 self.scissor_stack.pop();
1559 }
1560 }
1561
1562 #[inline]
1564 pub fn current_scissor(&self) -> Rect {
1565 *self
1566 .scissor_stack
1567 .last()
1568 .expect("scissor stack always has at least one element")
1569 }
1570
1571 #[inline]
1573 pub fn scissor_depth(&self) -> usize {
1574 self.scissor_stack.len()
1575 }
1576
1577 #[inline]
1584 pub fn push_opacity(&mut self, opacity: f32) {
1585 let clamped = opacity.clamp(0.0, 1.0);
1586 let current = self.current_opacity();
1587 self.opacity_stack.push(current * clamped);
1588 }
1589
1590 #[inline]
1594 pub fn pop_opacity(&mut self) {
1595 if self.opacity_stack.len() > 1 {
1596 self.opacity_stack.pop();
1597 }
1598 }
1599
1600 #[inline]
1602 pub fn current_opacity(&self) -> f32 {
1603 *self
1604 .opacity_stack
1605 .last()
1606 .expect("opacity stack always has at least one element")
1607 }
1608
1609 #[inline]
1611 pub fn opacity_depth(&self) -> usize {
1612 self.opacity_stack.len()
1613 }
1614
1615 pub fn copy_from(&mut self, src: &Buffer, src_rect: Rect, dst_x: u16, dst_y: u16) {
1622 let copy_bounds = Rect::new(dst_x, dst_y, src_rect.width, src_rect.height);
1625 self.push_scissor(copy_bounds);
1626 let clip = self.current_scissor();
1627
1628 for dy in 0..src_rect.height {
1629 let Some(target_y) = dst_y.checked_add(dy) else {
1631 continue;
1632 };
1633 let Some(sy) = src_rect.y.checked_add(dy) else {
1634 continue;
1635 };
1636
1637 let mut dx = 0u16;
1638 while dx < src_rect.width {
1639 let Some(target_x) = dst_x.checked_add(dx) else {
1641 dx = dx.saturating_add(1);
1642 continue;
1643 };
1644 let Some(sx) = src_rect.x.checked_add(dx) else {
1645 dx = dx.saturating_add(1);
1646 continue;
1647 };
1648
1649 if let Some(cell) = src.get(sx, sy) {
1650 if cell.is_continuation() {
1654 self.set(target_x, target_y, Cell::default());
1655 dx = dx.saturating_add(1);
1656 continue;
1657 }
1658
1659 let width = cell.content.width();
1660 let target_right = target_x.saturating_add(width as u16);
1661
1662 let src_clipped = width > 1 && dx.saturating_add(width as u16) > src_rect.width;
1671 let dst_clipped = target_right > clip.right()
1672 || (width > 1 && target_x < clip.left() && target_right > clip.left());
1673
1674 if src_clipped || dst_clipped {
1675 let valid_width = (clip.right().saturating_sub(target_x)).min(width as u16);
1681 for i in 0..valid_width {
1682 self.set(target_x + i, target_y, Cell::default());
1683 }
1684 } else {
1685 self.set(target_x, target_y, *cell);
1686 }
1687
1688 if width > 1 {
1690 dx = dx.saturating_add(width as u16);
1691 } else {
1692 dx = dx.saturating_add(1);
1693 }
1694 } else {
1695 dx = dx.saturating_add(1);
1696 }
1697 }
1698 }
1699
1700 self.pop_scissor();
1701 }
1702
1703 pub fn content_eq(&self, other: &Buffer) -> bool {
1705 self.width == other.width && self.height == other.height && self.cells == other.cells
1706 }
1707}
1708
1709impl Default for Buffer {
1710 fn default() -> Self {
1712 Self::new(1, 1)
1713 }
1714}
1715
1716impl PartialEq for Buffer {
1717 fn eq(&self, other: &Self) -> bool {
1718 self.content_eq(other)
1719 }
1720}
1721
1722impl Eq for Buffer {}
1723
1724#[derive(Debug)]
1743pub struct DoubleBuffer {
1744 buffers: [Buffer; 2],
1745 current_idx: u8,
1747}
1748
1749const ADAPTIVE_GROWTH_FACTOR: f32 = 1.25;
1755
1756const ADAPTIVE_SHRINK_THRESHOLD: f32 = 0.50;
1759
1760const ADAPTIVE_MAX_OVERAGE: u16 = 200;
1762
1763#[derive(Debug)]
1795pub struct AdaptiveDoubleBuffer {
1796 inner: DoubleBuffer,
1798 logical_width: u16,
1800 logical_height: u16,
1802 capacity_width: u16,
1804 capacity_height: u16,
1806 stats: AdaptiveStats,
1808}
1809
1810#[derive(Debug, Clone, Default)]
1812pub struct AdaptiveStats {
1813 pub resize_avoided: u64,
1815 pub resize_reallocated: u64,
1817 pub resize_growth: u64,
1819 pub resize_shrink: u64,
1821}
1822
1823impl AdaptiveStats {
1824 pub fn reset(&mut self) {
1826 *self = Self::default();
1827 }
1828
1829 pub fn avoidance_ratio(&self) -> f64 {
1831 let total = self.resize_avoided + self.resize_reallocated;
1832 if total == 0 {
1833 1.0
1834 } else {
1835 self.resize_avoided as f64 / total as f64
1836 }
1837 }
1838}
1839
1840impl DoubleBuffer {
1841 pub fn new(width: u16, height: u16) -> Self {
1846 Self {
1847 buffers: [Buffer::new(width, height), Buffer::new(width, height)],
1848 current_idx: 0,
1849 }
1850 }
1851
1852 #[inline]
1857 pub fn swap(&mut self) {
1858 self.current_idx = 1 - self.current_idx;
1859 }
1860
1861 #[inline]
1863 pub fn current(&self) -> &Buffer {
1864 &self.buffers[self.current_idx as usize]
1865 }
1866
1867 #[inline]
1869 pub fn current_mut(&mut self) -> &mut Buffer {
1870 &mut self.buffers[self.current_idx as usize]
1871 }
1872
1873 #[inline]
1875 pub fn previous(&self) -> &Buffer {
1876 &self.buffers[(1 - self.current_idx) as usize]
1877 }
1878
1879 #[inline]
1881 pub fn previous_mut(&mut self) -> &mut Buffer {
1882 &mut self.buffers[(1 - self.current_idx) as usize]
1883 }
1884
1885 #[inline]
1887 pub fn width(&self) -> u16 {
1888 self.buffers[0].width()
1889 }
1890
1891 #[inline]
1893 pub fn height(&self) -> u16 {
1894 self.buffers[0].height()
1895 }
1896
1897 pub fn resize(&mut self, width: u16, height: u16) -> bool {
1902 let width = width.max(1);
1906 let height = height.max(1);
1907 if self.buffers[0].width() == width && self.buffers[0].height() == height {
1908 return false;
1909 }
1910 self.buffers = [Buffer::new(width, height), Buffer::new(width, height)];
1911 self.current_idx = 0;
1912 true
1913 }
1914
1915 #[inline]
1918 pub fn dimensions_match(&self, width: u16, height: u16) -> bool {
1919 self.buffers[0].width() == width.max(1) && self.buffers[0].height() == height.max(1)
1920 }
1921}
1922
1923impl AdaptiveDoubleBuffer {
1928 pub fn new(width: u16, height: u16) -> Self {
1933 let (cap_w, cap_h) = Self::compute_capacity(width, height);
1934 Self {
1935 inner: DoubleBuffer::new(cap_w, cap_h),
1936 logical_width: width,
1937 logical_height: height,
1938 capacity_width: cap_w,
1939 capacity_height: cap_h,
1940 stats: AdaptiveStats::default(),
1941 }
1942 }
1943
1944 fn compute_capacity(width: u16, height: u16) -> (u16, u16) {
1948 let extra_w =
1949 ((width as f32 * (ADAPTIVE_GROWTH_FACTOR - 1.0)) as u16).min(ADAPTIVE_MAX_OVERAGE);
1950 let extra_h =
1951 ((height as f32 * (ADAPTIVE_GROWTH_FACTOR - 1.0)) as u16).min(ADAPTIVE_MAX_OVERAGE);
1952
1953 let cap_w = width.saturating_add(extra_w);
1954 let cap_h = height.saturating_add(extra_h);
1955
1956 (cap_w, cap_h)
1957 }
1958
1959 fn needs_reallocation(&self, width: u16, height: u16) -> bool {
1963 if width > self.capacity_width || height > self.capacity_height {
1965 return true;
1966 }
1967
1968 let shrink_threshold_w = (self.capacity_width as f32 * ADAPTIVE_SHRINK_THRESHOLD) as u16;
1970 let shrink_threshold_h = (self.capacity_height as f32 * ADAPTIVE_SHRINK_THRESHOLD) as u16;
1971
1972 width < shrink_threshold_w || height < shrink_threshold_h
1973 }
1974
1975 #[inline]
1980 pub fn swap(&mut self) {
1981 self.inner.swap();
1982 }
1983
1984 #[inline]
1989 pub fn current(&self) -> &Buffer {
1990 self.inner.current()
1991 }
1992
1993 #[inline]
1995 pub fn current_mut(&mut self) -> &mut Buffer {
1996 self.inner.current_mut()
1997 }
1998
1999 #[inline]
2001 pub fn previous(&self) -> &Buffer {
2002 self.inner.previous()
2003 }
2004
2005 #[inline]
2007 pub fn width(&self) -> u16 {
2008 self.logical_width
2009 }
2010
2011 #[inline]
2013 pub fn height(&self) -> u16 {
2014 self.logical_height
2015 }
2016
2017 #[inline]
2019 pub fn capacity_width(&self) -> u16 {
2020 self.capacity_width
2021 }
2022
2023 #[inline]
2025 pub fn capacity_height(&self) -> u16 {
2026 self.capacity_height
2027 }
2028
2029 #[inline]
2031 pub fn stats(&self) -> &AdaptiveStats {
2032 &self.stats
2033 }
2034
2035 pub fn reset_stats(&mut self) {
2037 self.stats.reset();
2038 }
2039
2040 pub fn resize(&mut self, width: u16, height: u16) -> bool {
2052 if width == self.logical_width && height == self.logical_height {
2054 return false;
2055 }
2056
2057 let is_growth = width > self.logical_width || height > self.logical_height;
2058 if is_growth {
2059 self.stats.resize_growth += 1;
2060 } else {
2061 self.stats.resize_shrink += 1;
2062 }
2063
2064 if self.needs_reallocation(width, height) {
2065 let (cap_w, cap_h) = Self::compute_capacity(width, height);
2067 self.inner = DoubleBuffer::new(cap_w, cap_h);
2068 self.capacity_width = cap_w;
2069 self.capacity_height = cap_h;
2070 self.stats.resize_reallocated += 1;
2071 } else {
2072 self.inner.current_mut().clear();
2075 self.inner.previous_mut().clear();
2076 self.stats.resize_avoided += 1;
2077 }
2078
2079 self.logical_width = width;
2080 self.logical_height = height;
2081 true
2082 }
2083
2084 #[inline]
2086 pub fn dimensions_match(&self, width: u16, height: u16) -> bool {
2087 self.logical_width == width && self.logical_height == height
2088 }
2089
2090 #[inline]
2092 pub fn logical_bounds(&self) -> Rect {
2093 Rect::from_size(self.logical_width, self.logical_height)
2094 }
2095
2096 pub fn memory_efficiency(&self) -> f64 {
2098 let logical = self.logical_width as u64 * self.logical_height as u64;
2099 let capacity = self.capacity_width as u64 * self.capacity_height as u64;
2100 if capacity == 0 {
2101 1.0
2102 } else {
2103 logical as f64 / capacity as f64
2104 }
2105 }
2106}
2107
2108pub const BUFFER_CHECKSUM_FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
2110pub const BUFFER_CHECKSUM_FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
2112
2113#[inline]
2115#[must_use]
2116pub fn buffer_cells_checksum(cells: &[Cell]) -> u64 {
2117 let mut hash = BUFFER_CHECKSUM_FNV_OFFSET_BASIS;
2118 for cell in cells {
2119 for byte in cell.to_le_bytes() {
2120 hash ^= u64::from(byte);
2121 hash = hash.wrapping_mul(BUFFER_CHECKSUM_FNV_PRIME);
2122 }
2123 }
2124 hash
2125}
2126
2127#[inline]
2132#[must_use]
2133pub fn buffer_checksum(buf: &Buffer) -> u64 {
2134 buffer_cells_checksum(&buf.cells)
2135}
2136
2137#[cfg(test)]
2138mod tests {
2139 use super::*;
2140 use crate::cell::{CellContent, PackedRgba};
2141
2142 #[test]
2143 fn set_composites_background() {
2144 let mut buf = Buffer::new(1, 1);
2145
2146 let red = PackedRgba::rgb(255, 0, 0);
2148 buf.set(0, 0, Cell::default().with_bg(red));
2149
2150 let cell = Cell::from_char('X'); buf.set(0, 0, cell);
2153
2154 let result = buf.get(0, 0).unwrap();
2155 assert_eq!(result.content.as_char(), Some('X'));
2156 assert_eq!(
2157 result.bg, red,
2158 "Background should be preserved (composited)"
2159 );
2160 }
2161
2162 #[test]
2163 fn set_fast_matches_set_for_transparent_bg() {
2164 let red = PackedRgba::rgb(255, 0, 0);
2165 let cell = Cell::from_char('X').with_fg(PackedRgba::rgb(0, 255, 0));
2166
2167 let mut a = Buffer::new(1, 1);
2168 a.set(0, 0, Cell::default().with_bg(red));
2169 a.set(0, 0, cell);
2170
2171 let mut b = Buffer::new(1, 1);
2172 b.set(0, 0, Cell::default().with_bg(red));
2173 b.set_fast(0, 0, cell);
2174
2175 assert_eq!(a.get(0, 0), b.get(0, 0));
2176 }
2177
2178 #[test]
2179 fn set_fast_matches_set_for_opaque_bg() {
2180 let cell = Cell::from_char('X')
2181 .with_fg(PackedRgba::rgb(0, 255, 0))
2182 .with_bg(PackedRgba::rgb(255, 0, 0));
2183
2184 let mut a = Buffer::new(1, 1);
2185 a.set(0, 0, cell);
2186
2187 let mut b = Buffer::new(1, 1);
2188 b.set_fast(0, 0, cell);
2189
2190 assert_eq!(a.get(0, 0), b.get(0, 0));
2191 }
2192
2193 #[test]
2194 fn set_fast_clears_orphaned_tail_like_set() {
2195 let mut slow = Buffer::new(3, 1);
2196 slow.set_raw(0, 0, Cell::from_char('A'));
2197 slow.set_raw(1, 0, Cell::CONTINUATION);
2198 slow.clear_dirty();
2199
2200 let mut fast = slow.clone();
2201
2202 slow.set(0, 0, Cell::from_char('X'));
2203 fast.set_fast(0, 0, Cell::from_char('X'));
2204
2205 assert_eq!(slow.cells(), fast.cells());
2206 assert_eq!(fast.get(1, 0), Some(&Cell::default()));
2207
2208 let spans = fast.dirty_span_row(0).expect("dirty span row").spans();
2209 assert_eq!(spans, &[DirtySpan::new(0, 2)]);
2210 }
2211
2212 #[test]
2213 fn rect_contains() {
2214 let r = Rect::new(5, 5, 10, 10);
2215 assert!(r.contains(5, 5)); assert!(r.contains(14, 14)); assert!(!r.contains(4, 5)); assert!(!r.contains(15, 5)); assert!(!r.contains(5, 15)); }
2221
2222 #[test]
2223 fn rect_intersection() {
2224 let a = Rect::new(0, 0, 10, 10);
2225 let b = Rect::new(5, 5, 10, 10);
2226 let i = a.intersection(&b);
2227 assert_eq!(i, Rect::new(5, 5, 5, 5));
2228
2229 let c = Rect::new(20, 20, 5, 5);
2231 assert_eq!(a.intersection(&c), Rect::default());
2232 }
2233
2234 #[test]
2235 fn buffer_creation() {
2236 let buf = Buffer::new(80, 24);
2237 assert_eq!(buf.width(), 80);
2238 assert_eq!(buf.height(), 24);
2239 assert_eq!(buf.len(), 80 * 24);
2240 }
2241
2242 #[test]
2243 fn content_height_empty_is_zero() {
2244 let buf = Buffer::new(8, 4);
2245 assert_eq!(buf.content_height(), 0);
2246 }
2247
2248 #[test]
2249 fn content_height_tracks_last_non_empty_row() {
2250 let mut buf = Buffer::new(5, 4);
2251 buf.set(0, 0, Cell::from_char('A'));
2252 assert_eq!(buf.content_height(), 1);
2253
2254 buf.set(2, 3, Cell::from_char('Z'));
2255 assert_eq!(buf.content_height(), 4);
2256 }
2257
2258 #[test]
2259 fn buffer_zero_width_clamped_to_one() {
2260 let buf = Buffer::new(0, 24);
2261 assert_eq!(buf.width(), 1);
2262 assert_eq!(buf.height(), 24);
2263 }
2264
2265 #[test]
2266 fn buffer_zero_height_clamped_to_one() {
2267 let buf = Buffer::new(80, 0);
2268 assert_eq!(buf.width(), 80);
2269 assert_eq!(buf.height(), 1);
2270 }
2271
2272 #[test]
2273 fn buffer_get_and_set() {
2274 let mut buf = Buffer::new(10, 10);
2275 let cell = Cell::from_char('X');
2276 buf.set(5, 5, cell);
2277 assert_eq!(buf.get(5, 5).unwrap().content.as_char(), Some('X'));
2278 }
2279
2280 #[test]
2281 fn buffer_out_of_bounds_get() {
2282 let buf = Buffer::new(10, 10);
2283 assert!(buf.get(10, 0).is_none());
2284 assert!(buf.get(0, 10).is_none());
2285 assert!(buf.get(100, 100).is_none());
2286 }
2287
2288 #[test]
2289 fn buffer_out_of_bounds_set_ignored() {
2290 let mut buf = Buffer::new(10, 10);
2291 buf.set(100, 100, Cell::from_char('X')); assert_eq!(buf.cells().iter().filter(|c| !c.is_empty()).count(), 0);
2293 }
2294
2295 #[test]
2296 fn buffer_clear() {
2297 let mut buf = Buffer::new(10, 10);
2298 buf.set(5, 5, Cell::from_char('X'));
2299 buf.clear();
2300 assert!(buf.get(5, 5).unwrap().is_empty());
2301 }
2302
2303 #[test]
2304 fn scissor_stack_basic() {
2305 let mut buf = Buffer::new(20, 20);
2306
2307 assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
2309 assert_eq!(buf.scissor_depth(), 1);
2310
2311 buf.push_scissor(Rect::new(5, 5, 10, 10));
2313 assert_eq!(buf.current_scissor(), Rect::new(5, 5, 10, 10));
2314 assert_eq!(buf.scissor_depth(), 2);
2315
2316 buf.set(7, 7, Cell::from_char('I'));
2318 assert_eq!(buf.get(7, 7).unwrap().content.as_char(), Some('I'));
2319
2320 buf.set(0, 0, Cell::from_char('O'));
2322 assert!(buf.get(0, 0).unwrap().is_empty());
2323
2324 buf.pop_scissor();
2326 assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
2327 assert_eq!(buf.scissor_depth(), 1);
2328
2329 buf.set(0, 0, Cell::from_char('N'));
2331 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('N'));
2332 }
2333
2334 #[test]
2335 fn scissor_intersection() {
2336 let mut buf = Buffer::new(20, 20);
2337 buf.push_scissor(Rect::new(5, 5, 10, 10));
2338 buf.push_scissor(Rect::new(8, 8, 10, 10));
2339
2340 assert_eq!(buf.current_scissor(), Rect::new(8, 8, 7, 7));
2343 }
2344
2345 #[test]
2346 fn scissor_base_cannot_be_popped() {
2347 let mut buf = Buffer::new(10, 10);
2348 buf.pop_scissor(); assert_eq!(buf.scissor_depth(), 1);
2350 buf.pop_scissor(); assert_eq!(buf.scissor_depth(), 1);
2352 }
2353
2354 #[test]
2355 fn opacity_stack_basic() {
2356 let mut buf = Buffer::new(10, 10);
2357
2358 assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
2360 assert_eq!(buf.opacity_depth(), 1);
2361
2362 buf.push_opacity(0.5);
2364 assert!((buf.current_opacity() - 0.5).abs() < f32::EPSILON);
2365 assert_eq!(buf.opacity_depth(), 2);
2366
2367 buf.push_opacity(0.5);
2369 assert!((buf.current_opacity() - 0.25).abs() < f32::EPSILON);
2370 assert_eq!(buf.opacity_depth(), 3);
2371
2372 buf.pop_opacity();
2374 assert!((buf.current_opacity() - 0.5).abs() < f32::EPSILON);
2375 }
2376
2377 #[test]
2378 fn opacity_applied_to_cells() {
2379 let mut buf = Buffer::new(10, 10);
2380 buf.push_opacity(0.5);
2381
2382 let cell = Cell::from_char('X').with_fg(PackedRgba::rgba(100, 100, 100, 255));
2383 buf.set(5, 5, cell);
2384
2385 let stored = buf.get(5, 5).unwrap();
2386 assert_eq!(stored.fg.a(), 128);
2388 }
2389
2390 #[test]
2391 fn opacity_composites_background_before_storage() {
2392 let mut buf = Buffer::new(1, 1);
2393
2394 let red = PackedRgba::rgb(255, 0, 0);
2395 let blue = PackedRgba::rgb(0, 0, 255);
2396
2397 buf.set(0, 0, Cell::default().with_bg(red));
2398 buf.push_opacity(0.5);
2399 buf.set(0, 0, Cell::default().with_bg(blue));
2400
2401 let stored = buf.get(0, 0).unwrap();
2402 let expected = blue.with_opacity(0.5).over(red);
2403 assert_eq!(stored.bg, expected);
2404 }
2405
2406 #[test]
2407 fn opacity_clamped() {
2408 let mut buf = Buffer::new(10, 10);
2409 buf.push_opacity(2.0); assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
2411
2412 buf.push_opacity(-1.0); assert!((buf.current_opacity() - 0.0).abs() < f32::EPSILON);
2414 }
2415
2416 #[test]
2417 fn opacity_base_cannot_be_popped() {
2418 let mut buf = Buffer::new(10, 10);
2419 buf.pop_opacity(); assert_eq!(buf.opacity_depth(), 1);
2421 }
2422
2423 #[test]
2424 fn buffer_fill() {
2425 let mut buf = Buffer::new(10, 10);
2426 let cell = Cell::from_char('#');
2427 buf.fill(Rect::new(2, 2, 5, 5), cell);
2428
2429 assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('#'));
2431
2432 assert!(buf.get(0, 0).unwrap().is_empty());
2434 }
2435
2436 #[test]
2437 fn buffer_fill_respects_scissor() {
2438 let mut buf = Buffer::new(10, 10);
2439 buf.push_scissor(Rect::new(3, 3, 4, 4));
2440
2441 let cell = Cell::from_char('#');
2442 buf.fill(Rect::new(0, 0, 10, 10), cell);
2443
2444 assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('#'));
2446 assert!(buf.get(0, 0).unwrap().is_empty());
2447 assert!(buf.get(7, 7).unwrap().is_empty());
2448 }
2449
2450 #[test]
2451 fn fill_single_width_matches_scalar_reference() {
2452 fn scalar_fill(buffer: &mut Buffer, area: Rect, cell: Cell) {
2455 let clipped = buffer.current_scissor().intersection(&area);
2456 if clipped.is_empty() {
2457 return;
2458 }
2459 buffer.push_scissor(clipped);
2460 for y in clipped.y..clipped.bottom() {
2461 for x in clipped.x..clipped.right() {
2462 buffer.set(x, y, Cell::default());
2463 }
2464 for x in clipped.x..clipped.right() {
2465 buffer.set(x, y, cell);
2466 }
2467 }
2468 buffer.pop_scissor();
2469 }
2470
2471 let mut cases = 0usize;
2472 let mut fingerprint = 0xcbf2_9ce4_8422_2325u64;
2473 for layout in 0..4 {
2474 for dirty_mode in 0..3 {
2475 for opacity in [0.0, 0.375, 1.0] {
2476 for alpha in [0, 96, 255] {
2477 for ch in [' ', '#', '\u{301}'] {
2478 for area in [
2479 Rect::new(0, 0, 10, 4),
2480 Rect::new(2, 1, 5, 2),
2481 Rect::new(6, 0, 8, 4),
2482 Rect::new(0, 2, 0, 1),
2483 Rect::new(12, 0, 1, 1),
2484 ] {
2485 let mut initial = Buffer::new(10, 4);
2486 for y in 0..4 {
2487 for x in 0..10 {
2488 let old = Cell::from_char(if layout == 3 {
2489 '\u{301}'
2490 } else {
2491 'a'
2492 })
2493 .with_bg(PackedRgba::rgba(
2494 x as u8 * 20,
2495 y as u8 * 30,
2496 70,
2497 [0, 128, 255][x as usize % 3],
2498 ));
2499 initial.set_raw(x, y, old);
2500 }
2501 }
2502 if layout == 1 {
2503 initial.set(0, 0, Cell::from_char('中'));
2504 initial.set(8, 1, Cell::from_char('中'));
2505 initial.set(4, 2, Cell::from_char('中'));
2506 } else if layout == 2 {
2507 initial.set_raw(2, 0, Cell::CONTINUATION);
2508 initial.set_raw(7, 1, Cell::CONTINUATION);
2509 initial.set_raw(9, 1, Cell::CONTINUATION);
2510 }
2511 initial.set_dirty_span_config(
2512 DirtySpanConfig::default().with_max_spans_per_row(2),
2513 );
2514 if dirty_mode != 0 {
2515 initial.clear_dirty();
2516 }
2517 if dirty_mode == 2 {
2518 for y in 0..4 {
2519 initial.mark_dirty_span(y, 0, 1);
2520 initial.mark_dirty_span(y, 9, 10);
2521 }
2522 }
2523 initial.push_scissor(Rect::new(1, 0, 8, 4));
2524 initial.push_scissor(Rect::new(0, 0, 10, 3));
2525 initial.push_opacity(opacity);
2526 let cell = Cell::from_char(ch)
2527 .with_fg(PackedRgba::rgba(80, 91, 123, 180))
2528 .with_bg(PackedRgba::rgba(19, 40, 66, alpha))
2529 .with_attrs(crate::cell::CellAttrs::new(
2530 crate::cell::StyleFlags::BOLD,
2531 73,
2532 ));
2533 let mut actual = initial.clone();
2534 let mut expected = initial;
2535 actual.fill(area, cell);
2536 scalar_fill(&mut expected, area, cell);
2537 let actual_state = format!("{actual:?}");
2538 let expected_state = format!("{expected:?}");
2539 assert_eq!(actual_state, expected_state, "case {cases}");
2540 for byte in actual_state.bytes() {
2541 fingerprint ^= u64::from(byte);
2542 fingerprint = fingerprint.wrapping_mul(0x100_0000_01b3);
2543 }
2544 cases += 1;
2545 }
2546 }
2547 }
2548 }
2549 }
2550 }
2551 eprintln!("FILL_GOLDEN cases={cases} hash={fingerprint:016x}");
2552 }
2553
2554 #[test]
2555 fn buffer_copy_from() {
2556 let mut src = Buffer::new(10, 10);
2557 src.set(2, 2, Cell::from_char('S'));
2558
2559 let mut dst = Buffer::new(10, 10);
2560 dst.copy_from(&src, Rect::new(0, 0, 5, 5), 3, 3);
2561
2562 assert_eq!(dst.get(5, 5).unwrap().content.as_char(), Some('S'));
2564 }
2565
2566 #[test]
2567 fn copy_from_clips_wide_char_at_boundary() {
2568 let mut src = Buffer::new(10, 1);
2569 src.set(0, 0, Cell::from_char('中'));
2571
2572 let mut dst = Buffer::new(10, 1);
2573 dst.copy_from(&src, Rect::new(0, 0, 1, 1), 0, 0);
2576
2577 assert!(
2586 dst.get(0, 0).unwrap().is_empty(),
2587 "Wide char head should not be written if tail is clipped"
2588 );
2589 assert!(
2590 dst.get(1, 0).unwrap().is_empty(),
2591 "Wide char tail should not be leaked outside copy region"
2592 );
2593 }
2594
2595 #[test]
2596 fn buffer_content_eq() {
2597 let mut buf1 = Buffer::new(10, 10);
2598 let mut buf2 = Buffer::new(10, 10);
2599
2600 assert!(buf1.content_eq(&buf2));
2601
2602 buf1.set(0, 0, Cell::from_char('X'));
2603 assert!(!buf1.content_eq(&buf2));
2604
2605 buf2.set(0, 0, Cell::from_char('X'));
2606 assert!(buf1.content_eq(&buf2));
2607 }
2608
2609 #[test]
2610 fn buffer_bounds() {
2611 let buf = Buffer::new(80, 24);
2612 let bounds = buf.bounds();
2613 assert_eq!(bounds.x, 0);
2614 assert_eq!(bounds.y, 0);
2615 assert_eq!(bounds.width, 80);
2616 assert_eq!(bounds.height, 24);
2617 }
2618
2619 #[test]
2620 fn buffer_set_raw_bypasses_scissor() {
2621 let mut buf = Buffer::new(10, 10);
2622 buf.push_scissor(Rect::new(5, 5, 5, 5));
2623
2624 buf.set(0, 0, Cell::from_char('S'));
2626 assert!(buf.get(0, 0).unwrap().is_empty());
2627
2628 buf.set_raw(0, 0, Cell::from_char('R'));
2630 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('R'));
2631 }
2632
2633 #[test]
2634 fn set_handles_wide_chars() {
2635 let mut buf = Buffer::new(10, 10);
2636
2637 buf.set(0, 0, Cell::from_char('中'));
2639
2640 let head = buf.get(0, 0).unwrap();
2642 assert_eq!(head.content.as_char(), Some('中'));
2643
2644 let cont = buf.get(1, 0).unwrap();
2646 assert!(cont.is_continuation());
2647 assert!(!cont.is_empty());
2648 }
2649
2650 #[test]
2651 fn set_handles_wide_chars_clipped() {
2652 let mut buf = Buffer::new(10, 10);
2653 buf.push_scissor(Rect::new(0, 0, 1, 10)); buf.set(0, 0, Cell::from_char('中'));
2658
2659 assert!(buf.get(0, 0).unwrap().is_empty());
2661 assert!(buf.get(1, 0).unwrap().is_empty());
2663 }
2664
2665 #[test]
2668 fn overwrite_wide_head_with_single_clears_tails() {
2669 let mut buf = Buffer::new(10, 1);
2670
2671 buf.set(0, 0, Cell::from_char('中'));
2673 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2674 assert!(buf.get(1, 0).unwrap().is_continuation());
2675
2676 buf.set(0, 0, Cell::from_char('A'));
2678
2679 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2681 assert!(
2683 buf.get(1, 0).unwrap().is_empty(),
2684 "Continuation at x=1 should be cleared when head is overwritten"
2685 );
2686 }
2687
2688 #[test]
2689 fn set_raw_overwrite_wide_head_with_single_clears_tails() {
2690 let mut buf = Buffer::new(10, 1);
2691
2692 buf.set(0, 0, Cell::from_char('中'));
2693 assert!(buf.get(1, 0).unwrap().is_continuation());
2694 buf.clear_dirty();
2695
2696 buf.set_raw(0, 0, Cell::from_char('A'));
2697
2698 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2699 assert!(
2700 buf.get(1, 0).unwrap().is_empty(),
2701 "set_raw should clear stale continuation tails when overwriting a wide head"
2702 );
2703 let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
2704 assert_eq!(spans, &[DirtySpan::new(0, 2)]);
2705 }
2706
2707 #[test]
2708 fn set_raw_wide_head_preserves_manual_tail_cells() {
2709 let mut buf = Buffer::new(10, 1);
2710
2711 buf.set_raw(0, 0, Cell::from_char('中'));
2712 buf.set_raw(1, 0, Cell::CONTINUATION);
2713 assert!(buf.get(1, 0).unwrap().is_continuation());
2714 buf.clear_dirty();
2715
2716 buf.set_raw(0, 0, Cell::from_char('日'));
2717
2718 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('日'));
2719 assert!(
2720 buf.get(1, 0).unwrap().is_continuation(),
2721 "set_raw wide-head replacement should not clear caller-managed tails"
2722 );
2723 let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
2724 assert_eq!(spans, &[DirtySpan::new(0, 1)]);
2725 }
2726
2727 #[test]
2728 fn overwrite_continuation_with_single_clears_head_and_tails() {
2729 let mut buf = Buffer::new(10, 1);
2730
2731 buf.set(0, 0, Cell::from_char('中'));
2733 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2734 assert!(buf.get(1, 0).unwrap().is_continuation());
2735
2736 buf.set(1, 0, Cell::from_char('B'));
2738
2739 assert!(
2741 buf.get(0, 0).unwrap().is_empty(),
2742 "Head at x=0 should be cleared when its continuation is overwritten"
2743 );
2744 assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('B'));
2746 }
2747
2748 #[test]
2749 fn overwrite_wide_with_another_wide() {
2750 let mut buf = Buffer::new(10, 1);
2751
2752 buf.set(0, 0, Cell::from_char('中'));
2754 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2755 assert!(buf.get(1, 0).unwrap().is_continuation());
2756
2757 buf.set(0, 0, Cell::from_char('日'));
2759
2760 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('日'));
2762 assert!(
2763 buf.get(1, 0).unwrap().is_continuation(),
2764 "Continuation should still exist for new wide char"
2765 );
2766 }
2767
2768 #[test]
2769 fn overwrite_continuation_middle_of_wide_sequence() {
2770 let mut buf = Buffer::new(10, 1);
2771
2772 buf.set(0, 0, Cell::from_char('中'));
2774 buf.set(2, 0, Cell::from_char('日'));
2775
2776 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2777 assert!(buf.get(1, 0).unwrap().is_continuation());
2778 assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('日'));
2779 assert!(buf.get(3, 0).unwrap().is_continuation());
2780
2781 buf.set(1, 0, Cell::from_char('X'));
2783
2784 assert!(
2786 buf.get(0, 0).unwrap().is_empty(),
2787 "Head of first wide char should be cleared"
2788 );
2789 assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('X'));
2791 assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('日'));
2793 assert!(buf.get(3, 0).unwrap().is_continuation());
2794 }
2795
2796 #[test]
2797 fn wide_char_overlapping_previous_wide_char() {
2798 let mut buf = Buffer::new(10, 1);
2799
2800 buf.set(0, 0, Cell::from_char('中'));
2802 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2803 assert!(buf.get(1, 0).unwrap().is_continuation());
2804
2805 buf.set(1, 0, Cell::from_char('日'));
2807
2808 assert!(
2810 buf.get(0, 0).unwrap().is_empty(),
2811 "First wide char head should be cleared when continuation is overwritten by new wide"
2812 );
2813 assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('日'));
2815 assert!(buf.get(2, 0).unwrap().is_continuation());
2816 }
2817
2818 #[test]
2819 fn wide_char_at_end_of_buffer_atomic_reject() {
2820 let mut buf = Buffer::new(5, 1);
2821
2822 buf.set(4, 0, Cell::from_char('中'));
2824
2825 assert!(
2827 buf.get(4, 0).unwrap().is_empty(),
2828 "Wide char should be rejected when tail would be out of bounds"
2829 );
2830 }
2831
2832 #[test]
2833 fn three_wide_chars_sequential_cleanup() {
2834 let mut buf = Buffer::new(10, 1);
2835
2836 buf.set(0, 0, Cell::from_char('一'));
2838 buf.set(2, 0, Cell::from_char('二'));
2839 buf.set(4, 0, Cell::from_char('三'));
2840
2841 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('一'));
2843 assert!(buf.get(1, 0).unwrap().is_continuation());
2844 assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('二'));
2845 assert!(buf.get(3, 0).unwrap().is_continuation());
2846 assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('三'));
2847 assert!(buf.get(5, 0).unwrap().is_continuation());
2848
2849 buf.set(3, 0, Cell::from_char('M'));
2851
2852 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('一'));
2854 assert!(buf.get(1, 0).unwrap().is_continuation());
2855 assert!(buf.get(2, 0).unwrap().is_empty());
2857 assert_eq!(buf.get(3, 0).unwrap().content.as_char(), Some('M'));
2859 assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('三'));
2861 assert!(buf.get(5, 0).unwrap().is_continuation());
2862 }
2863
2864 #[test]
2865 fn overwrite_empty_cell_no_cleanup_needed() {
2866 let mut buf = Buffer::new(10, 1);
2867
2868 buf.set(5, 0, Cell::from_char('X'));
2870
2871 assert_eq!(buf.get(5, 0).unwrap().content.as_char(), Some('X'));
2872 assert!(buf.get(4, 0).unwrap().is_empty());
2874 assert!(buf.get(6, 0).unwrap().is_empty());
2875 }
2876
2877 #[test]
2878 fn wide_char_cleanup_with_opacity() {
2879 let mut buf = Buffer::new(10, 1);
2880
2881 buf.set(0, 0, Cell::default().with_bg(PackedRgba::rgb(255, 0, 0)));
2883 buf.set(1, 0, Cell::default().with_bg(PackedRgba::rgb(0, 255, 0)));
2884
2885 buf.set(0, 0, Cell::from_char('中'));
2887
2888 buf.push_opacity(0.5);
2890 buf.set(0, 0, Cell::from_char('A'));
2891 buf.pop_opacity();
2892
2893 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
2895 assert!(buf.get(1, 0).unwrap().is_empty());
2897 }
2898
2899 #[test]
2900 fn wide_char_continuation_not_treated_as_head() {
2901 let mut buf = Buffer::new(10, 1);
2902
2903 buf.set(0, 0, Cell::from_char('中'));
2905
2906 let cont = buf.get(1, 0).unwrap();
2908 assert!(cont.is_continuation());
2909 assert_eq!(cont.content.width(), 0);
2910
2911 buf.set(1, 0, Cell::from_char('日'));
2913
2914 assert!(buf.get(0, 0).unwrap().is_empty());
2916 assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('日'));
2918 assert!(buf.get(2, 0).unwrap().is_continuation());
2919 }
2920
2921 #[test]
2922 fn wide_char_fill_region() {
2923 let mut buf = Buffer::new(10, 3);
2924
2925 let wide_cell = Cell::from_char('中');
2928 buf.fill(Rect::new(0, 0, 4, 2), wide_cell);
2929
2930 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
2932 assert!(buf.get(1, 0).unwrap().is_continuation());
2933 assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('中'));
2934 assert!(buf.get(3, 0).unwrap().is_continuation());
2935 }
2936
2937 #[test]
2938 fn default_buffer_dimensions() {
2939 let buf = Buffer::default();
2940 assert_eq!(buf.width(), 1);
2941 assert_eq!(buf.height(), 1);
2942 assert_eq!(buf.len(), 1);
2943 }
2944
2945 #[test]
2946 fn buffer_partial_eq_impl() {
2947 let buf1 = Buffer::new(5, 5);
2948 let buf2 = Buffer::new(5, 5);
2949 let mut buf3 = Buffer::new(5, 5);
2950 buf3.set(0, 0, Cell::from_char('X'));
2951
2952 assert_eq!(buf1, buf2);
2953 assert_ne!(buf1, buf3);
2954 }
2955
2956 #[test]
2957 fn degradation_level_accessible() {
2958 let mut buf = Buffer::new(10, 10);
2959 assert_eq!(buf.degradation, DegradationLevel::Full);
2960
2961 buf.degradation = DegradationLevel::SimpleBorders;
2962 assert_eq!(buf.degradation, DegradationLevel::SimpleBorders);
2963 }
2964
2965 #[test]
2968 fn get_mut_modifies_cell() {
2969 let mut buf = Buffer::new(10, 10);
2970 buf.set(3, 3, Cell::from_char('A'));
2971
2972 if let Some(cell) = buf.get_mut(3, 3) {
2973 *cell = Cell::from_char('B');
2974 }
2975
2976 assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('B'));
2977 }
2978
2979 #[test]
2980 fn get_mut_out_of_bounds() {
2981 let mut buf = Buffer::new(5, 5);
2982 assert!(buf.get_mut(10, 10).is_none());
2983 }
2984
2985 #[test]
2988 fn clear_with_fills_all_cells() {
2989 let mut buf = Buffer::new(5, 3);
2990 let fill_cell = Cell::from_char('*');
2991 buf.clear_with(fill_cell);
2992
2993 for y in 0..3 {
2994 for x in 0..5 {
2995 assert_eq!(buf.get(x, y).unwrap().content.as_char(), Some('*'));
2996 }
2997 }
2998 }
2999
3000 #[test]
3001 fn clear_with_wide_cell_preserves_head_tail_invariant() {
3002 let mut buf = Buffer::new(5, 2);
3003 buf.clear_with(Cell::from_char('中'));
3004
3005 for y in 0..2 {
3006 assert_eq!(buf.get(0, y).unwrap().content.as_char(), Some('中'));
3007 assert!(buf.get(1, y).unwrap().is_continuation());
3008 assert_eq!(buf.get(2, y).unwrap().content.as_char(), Some('中'));
3009 assert!(buf.get(3, y).unwrap().is_continuation());
3010 assert!(buf.get(4, y).unwrap().is_empty());
3011 }
3012 }
3013
3014 #[test]
3017 fn cells_slice_has_correct_length() {
3018 let buf = Buffer::new(10, 5);
3019 assert_eq!(buf.cells().len(), 50);
3020 }
3021
3022 #[test]
3023 fn cells_mut_allows_direct_modification() {
3024 let mut buf = Buffer::new(3, 2);
3025 let cells = buf.cells_mut();
3026 cells[0] = Cell::from_char('Z');
3027
3028 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('Z'));
3029 }
3030
3031 #[test]
3034 fn row_cells_returns_correct_row() {
3035 let mut buf = Buffer::new(5, 3);
3036 buf.set(2, 1, Cell::from_char('R'));
3037
3038 let row = buf.row_cells(1);
3039 assert_eq!(row.len(), 5);
3040 assert_eq!(row[2].content.as_char(), Some('R'));
3041 }
3042
3043 #[test]
3044 fn row_cells_mut_span_marks_once_and_returns_slice() {
3045 let mut buf = Buffer::new(5, 3);
3046 buf.clear_dirty();
3047
3048 let row = buf
3049 .row_cells_mut_span(1, 1, 4)
3050 .expect("row span should be in bounds");
3051 assert_eq!(row.len(), 3);
3052 row[0] = Cell::from_char('A');
3053 row[1] = Cell::from_char('B');
3054 row[2] = Cell::from_char('C');
3055
3056 assert!(buf.is_row_dirty(1));
3057 let spans = buf.dirty_span_row(1).expect("dirty span row").spans();
3058 assert_eq!(spans, &[DirtySpan::new(1, 4)]);
3059 assert_eq!(buf.get(1, 1).unwrap().content.as_char(), Some('A'));
3060 assert_eq!(buf.get(2, 1).unwrap().content.as_char(), Some('B'));
3061 assert_eq!(buf.get(3, 1).unwrap().content.as_char(), Some('C'));
3062 }
3063
3064 #[test]
3065 fn row_cells_mut_span_clamps_to_buffer_width() {
3066 let mut buf = Buffer::new(5, 1);
3067 buf.clear_dirty();
3068
3069 let row = buf
3070 .row_cells_mut_span(0, 3, 99)
3071 .expect("row span should clamp");
3072 assert_eq!(row.len(), 2);
3073 row[0] = Cell::from_char('X');
3074 row[1] = Cell::from_char('Y');
3075
3076 let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
3077 assert_eq!(spans, &[DirtySpan::new(3, 5)]);
3078 assert_eq!(buf.get(3, 0).unwrap().content.as_char(), Some('X'));
3079 assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('Y'));
3080 }
3081
3082 #[test]
3083 fn row_cells_mut_span_rejects_reversed_ranges() {
3084 let mut buf = Buffer::new(5, 1);
3085 buf.clear_dirty();
3086
3087 assert!(buf.row_cells_mut_span(0, 4, 2).is_none());
3088 assert!(
3089 !buf.is_row_dirty(0),
3090 "reversed ranges should not mark rows dirty"
3091 );
3092 assert!(
3093 buf.dirty_span_row(0)
3094 .expect("dirty span row")
3095 .spans()
3096 .is_empty(),
3097 "reversed ranges should not add dirty spans"
3098 );
3099 }
3100
3101 #[test]
3102 #[should_panic]
3103 fn row_cells_out_of_bounds_panics() {
3104 let buf = Buffer::new(5, 3);
3105 let _ = buf.row_cells(5);
3106 }
3107
3108 #[test]
3111 fn buffer_is_not_empty() {
3112 let buf = Buffer::new(1, 1);
3113 assert!(!buf.is_empty());
3114 }
3115
3116 #[test]
3119 fn set_raw_out_of_bounds_is_safe() {
3120 let mut buf = Buffer::new(5, 5);
3121 buf.set_raw(100, 100, Cell::from_char('X'));
3122 }
3124
3125 #[test]
3128 fn copy_from_out_of_bounds_partial() {
3129 let mut src = Buffer::new(5, 5);
3130 src.set(0, 0, Cell::from_char('A'));
3131 src.set(4, 4, Cell::from_char('B'));
3132
3133 let mut dst = Buffer::new(5, 5);
3134 dst.copy_from(&src, Rect::new(0, 0, 5, 5), 3, 3);
3136
3137 assert_eq!(dst.get(3, 3).unwrap().content.as_char(), Some('A'));
3139 assert!(dst.get(4, 4).unwrap().is_empty());
3141 }
3142
3143 #[test]
3146 fn content_eq_different_dimensions() {
3147 let buf1 = Buffer::new(5, 5);
3148 let buf2 = Buffer::new(10, 10);
3149 assert!(!buf1.content_eq(&buf2));
3151 }
3152
3153 mod property {
3156 use super::*;
3157 use proptest::prelude::*;
3158
3159 proptest! {
3160 #[test]
3161 fn buffer_dimensions_are_preserved(width in 1u16..200, height in 1u16..200) {
3162 let buf = Buffer::new(width, height);
3163 prop_assert_eq!(buf.width(), width);
3164 prop_assert_eq!(buf.height(), height);
3165 prop_assert_eq!(buf.len(), width as usize * height as usize);
3166 }
3167
3168 #[test]
3169 fn buffer_get_in_bounds_always_succeeds(width in 1u16..100, height in 1u16..100) {
3170 let buf = Buffer::new(width, height);
3171 for x in 0..width {
3172 for y in 0..height {
3173 prop_assert!(buf.get(x, y).is_some(), "get({x},{y}) failed for {width}x{height} buffer");
3174 }
3175 }
3176 }
3177
3178 #[test]
3179 fn buffer_get_out_of_bounds_returns_none(width in 1u16..50, height in 1u16..50) {
3180 let buf = Buffer::new(width, height);
3181 prop_assert!(buf.get(width, 0).is_none());
3182 prop_assert!(buf.get(0, height).is_none());
3183 prop_assert!(buf.get(width, height).is_none());
3184 }
3185
3186 #[test]
3187 fn buffer_set_get_roundtrip(
3188 width in 5u16..50,
3189 height in 5u16..50,
3190 x in 0u16..5,
3191 y in 0u16..5,
3192 ch_idx in 0u32..26,
3193 ) {
3194 let x = x % width;
3195 let y = y % height;
3196 let ch = char::from_u32('A' as u32 + ch_idx).unwrap();
3197 let mut buf = Buffer::new(width, height);
3198 buf.set(x, y, Cell::from_char(ch));
3199 let got = buf.get(x, y).unwrap();
3200 prop_assert_eq!(got.content.as_char(), Some(ch));
3201 }
3202
3203 #[test]
3204 fn scissor_push_pop_stack_depth(
3205 width in 10u16..50,
3206 height in 10u16..50,
3207 push_count in 1usize..10,
3208 ) {
3209 let mut buf = Buffer::new(width, height);
3210 prop_assert_eq!(buf.scissor_depth(), 1); for i in 0..push_count {
3213 buf.push_scissor(Rect::new(0, 0, width, height));
3214 prop_assert_eq!(buf.scissor_depth(), i + 2);
3215 }
3216
3217 for i in (0..push_count).rev() {
3218 buf.pop_scissor();
3219 prop_assert_eq!(buf.scissor_depth(), i + 1);
3220 }
3221
3222 buf.pop_scissor();
3224 prop_assert_eq!(buf.scissor_depth(), 1);
3225 }
3226
3227 #[test]
3228 fn scissor_monotonic_intersection(
3229 width in 20u16..60,
3230 height in 20u16..60,
3231 ) {
3232 let mut buf = Buffer::new(width, height);
3234 let outer = Rect::new(2, 2, width - 4, height - 4);
3235 buf.push_scissor(outer);
3236 let s1 = buf.current_scissor();
3237
3238 let inner = Rect::new(5, 5, 10, 10);
3239 buf.push_scissor(inner);
3240 let s2 = buf.current_scissor();
3241
3242 prop_assert!(s2.width <= s1.width, "inner width {} > outer width {}", s2.width, s1.width);
3244 prop_assert!(s2.height <= s1.height, "inner height {} > outer height {}", s2.height, s1.height);
3245 }
3246
3247 #[test]
3248 fn opacity_push_pop_stack_depth(
3249 width in 5u16..20,
3250 height in 5u16..20,
3251 push_count in 1usize..10,
3252 ) {
3253 let mut buf = Buffer::new(width, height);
3254 prop_assert_eq!(buf.opacity_depth(), 1);
3255
3256 for i in 0..push_count {
3257 buf.push_opacity(0.9);
3258 prop_assert_eq!(buf.opacity_depth(), i + 2);
3259 }
3260
3261 for i in (0..push_count).rev() {
3262 buf.pop_opacity();
3263 prop_assert_eq!(buf.opacity_depth(), i + 1);
3264 }
3265
3266 buf.pop_opacity();
3267 prop_assert_eq!(buf.opacity_depth(), 1);
3268 }
3269
3270 #[test]
3271 fn opacity_multiplication_is_monotonic(
3272 opacity1 in 0.0f32..=1.0,
3273 opacity2 in 0.0f32..=1.0,
3274 ) {
3275 let mut buf = Buffer::new(5, 5);
3276 buf.push_opacity(opacity1);
3277 let after_first = buf.current_opacity();
3278 buf.push_opacity(opacity2);
3279 let after_second = buf.current_opacity();
3280
3281 prop_assert!(after_second <= after_first + f32::EPSILON,
3283 "opacity increased: {} -> {}", after_first, after_second);
3284 }
3285
3286 #[test]
3287 fn clear_resets_all_cells(width in 1u16..30, height in 1u16..30) {
3288 let mut buf = Buffer::new(width, height);
3289 for x in 0..width {
3291 buf.set_raw(x, 0, Cell::from_char('X'));
3292 }
3293 buf.clear();
3294 for y in 0..height {
3296 for x in 0..width {
3297 prop_assert!(buf.get(x, y).unwrap().is_empty(),
3298 "cell ({x},{y}) not empty after clear");
3299 }
3300 }
3301 }
3302
3303 #[test]
3304 fn content_eq_is_reflexive(width in 1u16..30, height in 1u16..30) {
3305 let buf = Buffer::new(width, height);
3306 prop_assert!(buf.content_eq(&buf));
3307 }
3308
3309 #[test]
3310 fn content_eq_detects_single_change(
3311 width in 5u16..30,
3312 height in 5u16..30,
3313 x in 0u16..5,
3314 y in 0u16..5,
3315 ) {
3316 let x = x % width;
3317 let y = y % height;
3318 let buf1 = Buffer::new(width, height);
3319 let mut buf2 = Buffer::new(width, height);
3320 buf2.set_raw(x, y, Cell::from_char('Z'));
3321 prop_assert!(!buf1.content_eq(&buf2));
3322 }
3323
3324 #[test]
3327 fn dimensions_immutable_through_operations(
3328 width in 5u16..30,
3329 height in 5u16..30,
3330 ) {
3331 let mut buf = Buffer::new(width, height);
3332
3333 buf.set(0, 0, Cell::from_char('A'));
3335 prop_assert_eq!(buf.width(), width);
3336 prop_assert_eq!(buf.height(), height);
3337 prop_assert_eq!(buf.len(), width as usize * height as usize);
3338
3339 buf.push_scissor(Rect::new(1, 1, 3, 3));
3340 prop_assert_eq!(buf.width(), width);
3341 prop_assert_eq!(buf.height(), height);
3342
3343 buf.push_opacity(0.5);
3344 prop_assert_eq!(buf.width(), width);
3345 prop_assert_eq!(buf.height(), height);
3346
3347 buf.pop_scissor();
3348 buf.pop_opacity();
3349 prop_assert_eq!(buf.width(), width);
3350 prop_assert_eq!(buf.height(), height);
3351
3352 buf.clear();
3353 prop_assert_eq!(buf.width(), width);
3354 prop_assert_eq!(buf.height(), height);
3355 prop_assert_eq!(buf.len(), width as usize * height as usize);
3356 }
3357
3358 #[test]
3359 fn scissor_area_never_increases_random_rects(
3360 width in 20u16..60,
3361 height in 20u16..60,
3362 rects in proptest::collection::vec(
3363 (0u16..20, 0u16..20, 1u16..15, 1u16..15),
3364 1..8
3365 ),
3366 ) {
3367 let mut buf = Buffer::new(width, height);
3368 let mut prev_area = (width as u32) * (height as u32);
3369
3370 for (x, y, w, h) in rects {
3371 buf.push_scissor(Rect::new(x, y, w, h));
3372 let s = buf.current_scissor();
3373 let area = (s.width as u32) * (s.height as u32);
3374 prop_assert!(area <= prev_area,
3375 "scissor area increased: {} -> {} after push({},{},{},{})",
3376 prev_area, area, x, y, w, h);
3377 prev_area = area;
3378 }
3379 }
3380
3381 #[test]
3382 fn opacity_range_invariant_random_sequence(
3383 opacities in proptest::collection::vec(0.0f32..=1.0, 1..15),
3384 ) {
3385 let mut buf = Buffer::new(5, 5);
3386
3387 for &op in &opacities {
3388 buf.push_opacity(op);
3389 let current = buf.current_opacity();
3390 prop_assert!(current >= 0.0, "opacity below 0: {}", current);
3391 prop_assert!(current <= 1.0 + f32::EPSILON,
3392 "opacity above 1: {}", current);
3393 }
3394
3395 for _ in &opacities {
3397 buf.pop_opacity();
3398 }
3399 prop_assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
3401 }
3402
3403 #[test]
3404 fn opacity_clamp_out_of_range(
3405 neg in -100.0f32..0.0,
3406 over in 1.01f32..100.0,
3407 ) {
3408 let mut buf = Buffer::new(5, 5);
3409
3410 buf.push_opacity(neg);
3411 prop_assert!(buf.current_opacity() >= 0.0,
3412 "negative opacity not clamped: {}", buf.current_opacity());
3413 buf.pop_opacity();
3414
3415 buf.push_opacity(over);
3416 prop_assert!(buf.current_opacity() <= 1.0 + f32::EPSILON,
3417 "over-1 opacity not clamped: {}", buf.current_opacity());
3418 }
3419
3420 #[test]
3421 fn scissor_stack_always_has_base(
3422 pushes in 0usize..10,
3423 pops in 0usize..15,
3424 ) {
3425 let mut buf = Buffer::new(10, 10);
3426
3427 for _ in 0..pushes {
3428 buf.push_scissor(Rect::new(0, 0, 5, 5));
3429 }
3430 for _ in 0..pops {
3431 buf.pop_scissor();
3432 }
3433
3434 prop_assert!(buf.scissor_depth() >= 1,
3436 "scissor depth dropped below 1 after {} pushes, {} pops",
3437 pushes, pops);
3438 }
3439
3440 #[test]
3441 fn opacity_stack_always_has_base(
3442 pushes in 0usize..10,
3443 pops in 0usize..15,
3444 ) {
3445 let mut buf = Buffer::new(10, 10);
3446
3447 for _ in 0..pushes {
3448 buf.push_opacity(0.5);
3449 }
3450 for _ in 0..pops {
3451 buf.pop_opacity();
3452 }
3453
3454 prop_assert!(buf.opacity_depth() >= 1,
3456 "opacity depth dropped below 1 after {} pushes, {} pops",
3457 pushes, pops);
3458 }
3459
3460 #[test]
3461 fn cells_len_invariant_always_holds(
3462 width in 1u16..50,
3463 height in 1u16..50,
3464 ) {
3465 let mut buf = Buffer::new(width, height);
3466 let expected = width as usize * height as usize;
3467
3468 prop_assert_eq!(buf.cells().len(), expected);
3469
3470 buf.set(0, 0, Cell::from_char('X'));
3472 prop_assert_eq!(buf.cells().len(), expected);
3473
3474 buf.clear();
3475 prop_assert_eq!(buf.cells().len(), expected);
3476 }
3477
3478 #[test]
3479 fn set_outside_scissor_is_noop(
3480 width in 10u16..30,
3481 height in 10u16..30,
3482 ) {
3483 let mut buf = Buffer::new(width, height);
3484 buf.push_scissor(Rect::new(2, 2, 3, 3));
3485
3486 buf.set(0, 0, Cell::from_char('X'));
3488 let cell = buf.get(0, 0).unwrap();
3490 prop_assert!(cell.is_empty(),
3491 "cell (0,0) modified outside scissor region");
3492
3493 buf.set(3, 3, Cell::from_char('Y'));
3495 let cell = buf.get(3, 3).unwrap();
3496 prop_assert_eq!(cell.content.as_char(), Some('Y'));
3497 }
3498
3499 #[test]
3502 fn wide_char_overwrites_cleanup_tails(
3503 width in 10u16..30,
3504 x in 0u16..8,
3505 ) {
3506 let x = x % (width.saturating_sub(2).max(1));
3507 let mut buf = Buffer::new(width, 1);
3508
3509 buf.set(x, 0, Cell::from_char('中'));
3511
3512 if x + 1 < width {
3514 let head = buf.get(x, 0).unwrap();
3515 let tail = buf.get(x + 1, 0).unwrap();
3516
3517 if head.content.as_char() == Some('中') {
3518 prop_assert!(tail.is_continuation(),
3519 "tail at x+1={} should be continuation", x + 1);
3520
3521 buf.set(x, 0, Cell::from_char('A'));
3523 let new_head = buf.get(x, 0).unwrap();
3524 let cleared_tail = buf.get(x + 1, 0).unwrap();
3525
3526 prop_assert_eq!(new_head.content.as_char(), Some('A'));
3527 prop_assert!(cleared_tail.is_empty(),
3528 "tail should be cleared after head overwrite");
3529 }
3530 }
3531 }
3532
3533 #[test]
3534 fn wide_char_atomic_rejection_at_boundary(
3535 width in 3u16..20,
3536 ) {
3537 let mut buf = Buffer::new(width, 1);
3538
3539 let last_pos = width - 1;
3541 buf.set(last_pos, 0, Cell::from_char('中'));
3542
3543 let cell = buf.get(last_pos, 0).unwrap();
3545 prop_assert!(cell.is_empty(),
3546 "wide char at boundary position {} (width {}) should be rejected",
3547 last_pos, width);
3548 }
3549
3550 #[test]
3555 fn double_buffer_swap_is_involution(ops in proptest::collection::vec(proptest::bool::ANY, 0..100)) {
3556 let mut db = DoubleBuffer::new(10, 10);
3557 let initial_idx = db.current_idx;
3558
3559 for do_swap in &ops {
3560 if *do_swap {
3561 db.swap();
3562 }
3563 }
3564
3565 let swap_count = ops.iter().filter(|&&x| x).count();
3566 let expected_idx = if swap_count % 2 == 0 { initial_idx } else { 1 - initial_idx };
3567
3568 prop_assert_eq!(db.current_idx, expected_idx,
3569 "After {} swaps, index should be {} but was {}",
3570 swap_count, expected_idx, db.current_idx);
3571 }
3572
3573 #[test]
3574 fn double_buffer_resize_preserves_invariant(
3575 init_w in 1u16..200,
3576 init_h in 1u16..100,
3577 new_w in 1u16..200,
3578 new_h in 1u16..100,
3579 ) {
3580 let mut db = DoubleBuffer::new(init_w, init_h);
3581 db.resize(new_w, new_h);
3582
3583 prop_assert_eq!(db.width(), new_w);
3584 prop_assert_eq!(db.height(), new_h);
3585 prop_assert!(db.dimensions_match(new_w, new_h));
3586 }
3587
3588 #[test]
3589 fn double_buffer_current_previous_disjoint(
3590 width in 1u16..50,
3591 height in 1u16..50,
3592 ) {
3593 let mut db = DoubleBuffer::new(width, height);
3594
3595 db.current_mut().set(0, 0, Cell::from_char('C'));
3597
3598 prop_assert!(db.previous().get(0, 0).unwrap().is_empty(),
3600 "Previous buffer should not reflect changes to current");
3601
3602 db.swap();
3604 prop_assert_eq!(db.previous().get(0, 0).unwrap().content.as_char(), Some('C'),
3605 "After swap, previous should have the 'C' we wrote");
3606 }
3607
3608 #[test]
3609 fn double_buffer_swap_content_semantics(
3610 width in 5u16..30,
3611 height in 5u16..30,
3612 ) {
3613 let mut db = DoubleBuffer::new(width, height);
3614
3615 db.current_mut().set(0, 0, Cell::from_char('X'));
3617 db.swap();
3618
3619 db.current_mut().set(0, 0, Cell::from_char('Y'));
3621 db.swap();
3622
3623 prop_assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('X'));
3625 prop_assert_eq!(db.previous().get(0, 0).unwrap().content.as_char(), Some('Y'));
3626 }
3627
3628 #[test]
3629 fn double_buffer_resize_clears_both(
3630 w1 in 5u16..30,
3631 h1 in 5u16..30,
3632 w2 in 5u16..30,
3633 h2 in 5u16..30,
3634 ) {
3635 prop_assume!(w1 != w2 || h1 != h2);
3637
3638 let mut db = DoubleBuffer::new(w1, h1);
3639
3640 db.current_mut().set(0, 0, Cell::from_char('A'));
3642 db.swap();
3643 db.current_mut().set(0, 0, Cell::from_char('B'));
3644
3645 db.resize(w2, h2);
3647
3648 prop_assert!(db.current().get(0, 0).unwrap().is_empty(),
3650 "Current buffer should be empty after resize");
3651 prop_assert!(db.previous().get(0, 0).unwrap().is_empty(),
3652 "Previous buffer should be empty after resize");
3653 }
3654 }
3655 }
3656
3657 #[test]
3660 fn dirty_rows_start_dirty() {
3661 let buf = Buffer::new(10, 5);
3663 assert_eq!(buf.dirty_row_count(), 5);
3664 for y in 0..5 {
3665 assert!(buf.is_row_dirty(y));
3666 }
3667 }
3668
3669 #[test]
3670 fn dirty_bitmap_starts_full() {
3671 let buf = Buffer::new(4, 3);
3672 assert!(buf.dirty_all());
3673 assert_eq!(buf.dirty_cell_count(), 12);
3674 }
3675
3676 #[test]
3677 fn dirty_bitmap_tracks_single_cell() {
3678 let mut buf = Buffer::new(4, 3);
3679 buf.clear_dirty();
3680 assert!(!buf.dirty_all());
3681 buf.set_raw(1, 1, Cell::from_char('X'));
3682 let idx = 1 + 4;
3683 assert_eq!(buf.dirty_cell_count(), 1);
3684 assert_eq!(buf.dirty_bits()[idx], 1);
3685 }
3686
3687 #[test]
3688 fn dirty_bitmap_dedupes_cells() {
3689 let mut buf = Buffer::new(4, 3);
3690 buf.clear_dirty();
3691 buf.set_raw(2, 2, Cell::from_char('A'));
3692 buf.set_raw(2, 2, Cell::from_char('B'));
3693 assert_eq!(buf.dirty_cell_count(), 1);
3694 }
3695
3696 #[test]
3697 fn set_marks_row_dirty() {
3698 let mut buf = Buffer::new(10, 5);
3699 buf.clear_dirty(); buf.set(3, 2, Cell::from_char('X'));
3701 assert!(buf.is_row_dirty(2));
3702 assert!(!buf.is_row_dirty(0));
3703 assert!(!buf.is_row_dirty(1));
3704 assert!(!buf.is_row_dirty(3));
3705 assert!(!buf.is_row_dirty(4));
3706 }
3707
3708 #[test]
3709 fn set_raw_marks_row_dirty() {
3710 let mut buf = Buffer::new(10, 5);
3711 buf.clear_dirty(); buf.set_raw(0, 4, Cell::from_char('Z'));
3713 assert!(buf.is_row_dirty(4));
3714 assert_eq!(buf.dirty_row_count(), 1);
3715 }
3716
3717 #[test]
3718 fn clear_marks_all_dirty() {
3719 let mut buf = Buffer::new(10, 5);
3720 buf.clear();
3721 assert_eq!(buf.dirty_row_count(), 5);
3722 }
3723
3724 #[test]
3725 fn clear_dirty_resets_flags() {
3726 let mut buf = Buffer::new(10, 5);
3727 assert_eq!(buf.dirty_row_count(), 5);
3729 buf.clear_dirty();
3730 assert_eq!(buf.dirty_row_count(), 0);
3731
3732 buf.set(0, 0, Cell::from_char('A'));
3734 buf.set(0, 3, Cell::from_char('B'));
3735 assert_eq!(buf.dirty_row_count(), 2);
3736
3737 buf.clear_dirty();
3738 assert_eq!(buf.dirty_row_count(), 0);
3739 }
3740
3741 #[test]
3742 fn clear_dirty_resets_bitmap() {
3743 let mut buf = Buffer::new(4, 3);
3744 buf.clear();
3745 assert!(buf.dirty_all());
3746 buf.clear_dirty();
3747 assert!(!buf.dirty_all());
3748 assert_eq!(buf.dirty_cell_count(), 0);
3749 assert!(buf.dirty_bits().iter().all(|&b| b == 0));
3750 }
3751
3752 #[test]
3753 fn fill_with_wide_cells_leaves_no_stale_content() {
3754 let mut buf = Buffer::new(5, 1);
3755 for x in 0..5 {
3756 buf.set(x, 0, Cell::from_char('X'));
3757 }
3758 let wide = Cell::from_char('世');
3762 assert_eq!(wide.content.width(), 2);
3763 buf.fill(Rect::new(0, 0, 5, 1), wide);
3764 let trailing = *buf.get(4, 0).expect("in bounds");
3765 assert_ne!(
3766 trailing,
3767 Cell::from_char('X'),
3768 "stale content survived fill"
3769 );
3770 assert_eq!(trailing, Cell::default());
3771 assert_eq!(*buf.get(0, 0).unwrap(), wide);
3773 assert_eq!(*buf.get(2, 0).unwrap(), wide);
3774 }
3775
3776 #[test]
3777 fn fill_marks_affected_rows_dirty() {
3778 let mut buf = Buffer::new(10, 10);
3779 buf.clear_dirty(); buf.fill(Rect::new(0, 2, 5, 3), Cell::from_char('.'));
3781 assert!(!buf.is_row_dirty(0));
3783 assert!(!buf.is_row_dirty(1));
3784 assert!(buf.is_row_dirty(2));
3785 assert!(buf.is_row_dirty(3));
3786 assert!(buf.is_row_dirty(4));
3787 assert!(!buf.is_row_dirty(5));
3788 }
3789
3790 #[test]
3791 fn get_mut_marks_row_dirty() {
3792 let mut buf = Buffer::new(10, 5);
3793 buf.clear_dirty(); if let Some(cell) = buf.get_mut(5, 3) {
3795 cell.fg = PackedRgba::rgb(255, 0, 0);
3796 }
3797 assert!(buf.is_row_dirty(3));
3798 assert_eq!(buf.dirty_row_count(), 1);
3799 }
3800
3801 #[test]
3802 fn cells_mut_marks_all_dirty() {
3803 let mut buf = Buffer::new(10, 5);
3804 let _ = buf.cells_mut();
3805 assert_eq!(buf.dirty_row_count(), 5);
3806 }
3807
3808 #[test]
3809 fn dirty_rows_slice_length_matches_height() {
3810 let buf = Buffer::new(10, 7);
3811 assert_eq!(buf.dirty_rows().len(), 7);
3812 }
3813
3814 #[test]
3815 fn out_of_bounds_set_does_not_dirty() {
3816 let mut buf = Buffer::new(10, 5);
3817 buf.clear_dirty(); buf.set(100, 100, Cell::from_char('X'));
3819 assert_eq!(buf.dirty_row_count(), 0);
3820 }
3821
3822 #[test]
3823 fn property_dirty_soundness() {
3824 let mut buf = Buffer::new(20, 10);
3826 let positions = [(3, 0), (5, 2), (0, 9), (19, 5), (10, 7)];
3827 for &(x, y) in &positions {
3828 buf.set(x, y, Cell::from_char('*'));
3829 }
3830 for &(_, y) in &positions {
3831 assert!(
3832 buf.is_row_dirty(y),
3833 "Row {} should be dirty after set({}, {})",
3834 y,
3835 positions.iter().find(|(_, ry)| *ry == y).unwrap().0,
3836 y
3837 );
3838 }
3839 }
3840
3841 #[test]
3842 fn dirty_clear_between_frames() {
3843 let mut buf = Buffer::new(10, 5);
3845
3846 assert_eq!(buf.dirty_row_count(), 5);
3848
3849 buf.clear_dirty();
3851 assert_eq!(buf.dirty_row_count(), 0);
3852
3853 buf.set(0, 0, Cell::from_char('A'));
3855 buf.set(0, 2, Cell::from_char('B'));
3856 assert_eq!(buf.dirty_row_count(), 2);
3857
3858 buf.clear_dirty();
3860 assert_eq!(buf.dirty_row_count(), 0);
3861
3862 buf.set(0, 4, Cell::from_char('C'));
3864 assert_eq!(buf.dirty_row_count(), 1);
3865 assert!(buf.is_row_dirty(4));
3866 assert!(!buf.is_row_dirty(0));
3867 }
3868
3869 #[test]
3872 fn dirty_spans_start_full_dirty() {
3873 let buf = Buffer::new(10, 5);
3874 for y in 0..5 {
3875 let row = buf.dirty_span_row(y).unwrap();
3876 assert!(row.is_full(), "row {y} should start full-dirty");
3877 assert!(row.spans().is_empty(), "row {y} spans should start empty");
3878 }
3879 }
3880
3881 #[test]
3882 fn clear_dirty_resets_spans() {
3883 let mut buf = Buffer::new(10, 5);
3884 buf.clear_dirty();
3885 for y in 0..5 {
3886 let row = buf.dirty_span_row(y).unwrap();
3887 assert!(!row.is_full(), "row {y} should clear full-dirty");
3888 assert!(row.spans().is_empty(), "row {y} spans should be cleared");
3889 }
3890 assert_eq!(buf.dirty_span_overflows, 0);
3891 }
3892
3893 #[test]
3894 fn set_records_dirty_span() {
3895 let mut buf = Buffer::new(20, 2);
3896 buf.clear_dirty();
3897 buf.set(2, 0, Cell::from_char('A'));
3898 let row = buf.dirty_span_row(0).unwrap();
3899 assert_eq!(row.spans(), &[DirtySpan::new(2, 3)]);
3900 assert!(!row.is_full());
3901 }
3902
3903 #[test]
3904 fn set_merges_adjacent_spans() {
3905 let mut buf = Buffer::new(20, 2);
3906 buf.clear_dirty();
3907 buf.set(2, 0, Cell::from_char('A'));
3908 buf.set(3, 0, Cell::from_char('B')); let row = buf.dirty_span_row(0).unwrap();
3910 assert_eq!(row.spans(), &[DirtySpan::new(2, 4)]);
3911 }
3912
3913 #[test]
3914 fn set_merges_close_spans() {
3915 let mut buf = Buffer::new(20, 2);
3916 buf.clear_dirty();
3917 buf.set(2, 0, Cell::from_char('A'));
3918 buf.set(4, 0, Cell::from_char('B')); let row = buf.dirty_span_row(0).unwrap();
3920 assert_eq!(row.spans(), &[DirtySpan::new(2, 5)]);
3921 }
3922
3923 #[test]
3924 fn span_overflow_sets_full_row() {
3925 let width = (DIRTY_SPAN_MAX_SPANS_PER_ROW as u16 + 2) * 3;
3926 let mut buf = Buffer::new(width, 1);
3927 buf.clear_dirty();
3928 for i in 0..(DIRTY_SPAN_MAX_SPANS_PER_ROW + 1) {
3929 let x = (i as u16) * 3;
3930 buf.set(x, 0, Cell::from_char('x'));
3931 }
3932 let row = buf.dirty_span_row(0).unwrap();
3933 assert!(row.is_full());
3934 assert!(row.spans().is_empty());
3935 assert_eq!(buf.dirty_span_overflows, 1);
3936 }
3937
3938 #[test]
3939 fn fill_full_row_marks_full_span() {
3940 let mut buf = Buffer::new(10, 3);
3941 buf.clear_dirty();
3942 let cell = Cell::from_char('x').with_bg(PackedRgba::rgb(0, 0, 0));
3943 buf.fill(Rect::new(0, 1, 10, 1), cell);
3944 let row = buf.dirty_span_row(1).unwrap();
3945 assert!(row.is_full());
3946 assert!(row.spans().is_empty());
3947 }
3948
3949 #[test]
3950 fn get_mut_records_dirty_span() {
3951 let mut buf = Buffer::new(10, 5);
3952 buf.clear_dirty();
3953 let _ = buf.get_mut(5, 3);
3954 let row = buf.dirty_span_row(3).unwrap();
3955 assert_eq!(row.spans(), &[DirtySpan::new(5, 6)]);
3956 }
3957
3958 #[test]
3959 fn cells_mut_marks_all_full_spans() {
3960 let mut buf = Buffer::new(10, 5);
3961 buf.clear_dirty();
3962 let _ = buf.cells_mut();
3963 for y in 0..5 {
3964 let row = buf.dirty_span_row(y).unwrap();
3965 assert!(row.is_full(), "row {y} should be full after cells_mut");
3966 }
3967 }
3968
3969 #[test]
3970 fn dirty_span_config_disabled_skips_rows() {
3971 let mut buf = Buffer::new(10, 1);
3972 buf.clear_dirty();
3973 buf.set_dirty_span_config(DirtySpanConfig::default().with_enabled(false));
3974 buf.set(5, 0, Cell::from_char('x'));
3975 assert!(buf.dirty_span_row(0).is_none());
3976 let stats = buf.dirty_span_stats();
3977 assert_eq!(stats.total_spans, 0);
3978 assert_eq!(stats.span_coverage_cells, 0);
3979 }
3980
3981 #[test]
3982 fn set_dirty_span_config_keeps_dirty_rows_full() {
3983 let mut buf = Buffer::new(10, 2);
3990 buf.clear_dirty();
3991 buf.set(7, 0, Cell::from_char('B')); buf.set_dirty_span_config(DirtySpanConfig::default().with_merge_gap(3));
3994
3995 let row = buf.dirty_span_row(0).expect("row 0 must have span state");
3997 assert!(
3998 row.is_full(),
3999 "dirty row must go full-row on config change, got spans {:?}",
4000 row.spans()
4001 );
4002 assert!(!buf.is_row_dirty(1));
4004
4005 buf.set(2, 0, Cell::from_char('A'));
4008 let row = buf.dirty_span_row(0).unwrap();
4009 assert!(row.is_full(), "full-row flag must survive later marks");
4010 }
4011
4012 #[test]
4013 fn set_raw_rewriting_tail_preserves_other_tails_of_wide_glyph() {
4014 let mut buf = Buffer::new(10, 1);
4019 let head = Cell::new(CellContent::from_grapheme(GraphemeId::new(0, 0, 3)));
4022 buf.set_raw(2, 0, head);
4023 buf.set_raw(3, 0, Cell::CONTINUATION);
4024 buf.set_raw(4, 0, Cell::CONTINUATION);
4025 assert!(buf.get(4, 0).unwrap().is_continuation());
4026
4027 buf.set_raw(3, 0, Cell::CONTINUATION);
4029 assert!(
4030 buf.get(4, 0).unwrap().is_continuation(),
4031 "second tail of the width-3 glyph must survive a tail rewrite"
4032 );
4033
4034 let head2 = Cell::new(CellContent::from_grapheme(GraphemeId::new(1, 0, 2)));
4037 buf.set_raw(2, 0, head2);
4038 buf.set_raw(3, 0, Cell::CONTINUATION);
4039 assert!(
4040 !buf.get(4, 0).unwrap().is_continuation(),
4041 "stale tail beyond a narrower rebuilt glyph must be swept"
4042 );
4043 }
4044
4045 #[test]
4046 fn dirty_span_guard_band_expands_span_bounds() {
4047 let mut buf = Buffer::new(10, 1);
4048 buf.clear_dirty();
4049 buf.set_dirty_span_config(DirtySpanConfig::default().with_guard_band(2));
4050 buf.set(5, 0, Cell::from_char('x'));
4051 let row = buf.dirty_span_row(0).unwrap();
4052 assert_eq!(row.spans(), &[DirtySpan::new(3, 8)]);
4053 }
4054
4055 #[test]
4056 fn dirty_span_max_spans_overflow_triggers_full_row() {
4057 let mut buf = Buffer::new(10, 1);
4058 buf.clear_dirty();
4059 buf.set_dirty_span_config(
4060 DirtySpanConfig::default()
4061 .with_max_spans_per_row(1)
4062 .with_merge_gap(0),
4063 );
4064 buf.set(0, 0, Cell::from_char('a'));
4065 buf.set(4, 0, Cell::from_char('b'));
4066 let row = buf.dirty_span_row(0).unwrap();
4067 assert!(row.is_full());
4068 assert!(row.spans().is_empty());
4069 assert_eq!(buf.dirty_span_overflows, 1);
4070 }
4071
4072 #[test]
4073 fn dirty_span_stats_counts_full_rows_and_spans() {
4074 let mut buf = Buffer::new(6, 2);
4075 buf.clear_dirty();
4076 buf.set_dirty_span_config(DirtySpanConfig::default().with_merge_gap(0));
4077 buf.set(1, 0, Cell::from_char('a'));
4078 buf.set(4, 0, Cell::from_char('b'));
4079 buf.mark_dirty_row_full(1);
4080
4081 let stats = buf.dirty_span_stats();
4082 assert_eq!(stats.rows_full_dirty, 1);
4083 assert_eq!(stats.rows_with_spans, 1);
4084 assert_eq!(stats.total_spans, 2);
4085 assert_eq!(stats.max_span_len, 6);
4086 assert_eq!(stats.span_coverage_cells, 8);
4087 }
4088
4089 #[test]
4090 fn dirty_span_stats_reports_overflow_and_full_row() {
4091 let mut buf = Buffer::new(8, 1);
4092 buf.clear_dirty();
4093 buf.set_dirty_span_config(
4094 DirtySpanConfig::default()
4095 .with_max_spans_per_row(1)
4096 .with_merge_gap(0),
4097 );
4098 buf.set(0, 0, Cell::from_char('x'));
4099 buf.set(3, 0, Cell::from_char('y'));
4100
4101 let stats = buf.dirty_span_stats();
4102 assert_eq!(stats.overflows, 1);
4103 assert_eq!(stats.rows_full_dirty, 1);
4104 assert_eq!(stats.total_spans, 0);
4105 assert_eq!(stats.span_coverage_cells, 8);
4106 }
4107
4108 #[test]
4113 fn double_buffer_new_has_matching_dimensions() {
4114 let db = DoubleBuffer::new(80, 24);
4115 assert_eq!(db.width(), 80);
4116 assert_eq!(db.height(), 24);
4117 assert!(db.dimensions_match(80, 24));
4118 assert!(!db.dimensions_match(120, 40));
4119 }
4120
4121 #[test]
4122 fn double_buffer_swap_is_o1() {
4123 let mut db = DoubleBuffer::new(80, 24);
4124
4125 db.current_mut().set(0, 0, Cell::from_char('A'));
4127 assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('A'));
4128
4129 db.swap();
4131 assert_eq!(
4132 db.previous().get(0, 0).unwrap().content.as_char(),
4133 Some('A')
4134 );
4135 assert!(db.current().get(0, 0).unwrap().is_empty());
4137 }
4138
4139 #[test]
4140 fn double_buffer_swap_round_trip() {
4141 let mut db = DoubleBuffer::new(10, 5);
4142
4143 db.current_mut().set(0, 0, Cell::from_char('X'));
4144 db.swap();
4145 db.current_mut().set(0, 0, Cell::from_char('Y'));
4146 db.swap();
4147
4148 assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('X'));
4150 assert_eq!(
4151 db.previous().get(0, 0).unwrap().content.as_char(),
4152 Some('Y')
4153 );
4154 }
4155
4156 #[test]
4157 fn double_buffer_resize_changes_dimensions() {
4158 let mut db = DoubleBuffer::new(80, 24);
4159 assert!(!db.resize(80, 24)); assert!(db.resize(120, 40)); assert_eq!(db.width(), 120);
4162 assert_eq!(db.height(), 40);
4163 assert!(db.dimensions_match(120, 40));
4164 }
4165
4166 #[test]
4167 fn double_buffer_resize_clears_content() {
4168 let mut db = DoubleBuffer::new(10, 5);
4169 db.current_mut().set(0, 0, Cell::from_char('Z'));
4170 db.swap();
4171 db.current_mut().set(0, 0, Cell::from_char('W'));
4172
4173 db.resize(20, 10);
4174
4175 assert!(db.current().get(0, 0).unwrap().is_empty());
4177 assert!(db.previous().get(0, 0).unwrap().is_empty());
4178 }
4179
4180 #[test]
4181 fn double_buffer_current_and_previous_are_distinct() {
4182 let mut db = DoubleBuffer::new(10, 5);
4183 db.current_mut().set(0, 0, Cell::from_char('C'));
4184
4185 assert!(db.previous().get(0, 0).unwrap().is_empty());
4187 assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('C'));
4188 }
4189
4190 #[test]
4195 fn adaptive_buffer_new_has_over_allocation() {
4196 let adb = AdaptiveDoubleBuffer::new(80, 24);
4197
4198 assert_eq!(adb.width(), 80);
4200 assert_eq!(adb.height(), 24);
4201 assert!(adb.dimensions_match(80, 24));
4202
4203 assert!(adb.capacity_width() > 80);
4207 assert!(adb.capacity_height() > 24);
4208 assert_eq!(adb.capacity_width(), 100); assert_eq!(adb.capacity_height(), 30); }
4211
4212 #[test]
4213 fn adaptive_buffer_resize_avoids_reallocation_when_within_capacity() {
4214 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4215
4216 assert!(adb.resize(90, 28)); assert_eq!(adb.width(), 90);
4219 assert_eq!(adb.height(), 28);
4220 assert_eq!(adb.stats().resize_avoided, 1);
4221 assert_eq!(adb.stats().resize_reallocated, 0);
4222 assert_eq!(adb.stats().resize_growth, 1);
4223 }
4224
4225 #[test]
4226 fn adaptive_buffer_resize_reallocates_on_growth_beyond_capacity() {
4227 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4228
4229 assert!(adb.resize(120, 40)); assert_eq!(adb.width(), 120);
4232 assert_eq!(adb.height(), 40);
4233 assert_eq!(adb.stats().resize_reallocated, 1);
4234 assert_eq!(adb.stats().resize_avoided, 0);
4235
4236 assert!(adb.capacity_width() > 120);
4238 assert!(adb.capacity_height() > 40);
4239 }
4240
4241 #[test]
4242 fn adaptive_buffer_resize_reallocates_on_significant_shrink() {
4243 let mut adb = AdaptiveDoubleBuffer::new(100, 50);
4244
4245 assert!(adb.resize(40, 20)); assert_eq!(adb.width(), 40);
4249 assert_eq!(adb.height(), 20);
4250 assert_eq!(adb.stats().resize_reallocated, 1);
4251 assert_eq!(adb.stats().resize_shrink, 1);
4252 }
4253
4254 #[test]
4255 fn adaptive_buffer_resize_avoids_reallocation_on_minor_shrink() {
4256 let mut adb = AdaptiveDoubleBuffer::new(100, 50);
4257
4258 assert!(adb.resize(80, 40));
4262 assert_eq!(adb.width(), 80);
4263 assert_eq!(adb.height(), 40);
4264 assert_eq!(adb.stats().resize_avoided, 1);
4265 assert_eq!(adb.stats().resize_reallocated, 0);
4266 assert_eq!(adb.stats().resize_shrink, 1);
4267 }
4268
4269 #[test]
4270 fn adaptive_buffer_no_change_returns_false() {
4271 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4272
4273 assert!(!adb.resize(80, 24)); assert_eq!(adb.stats().resize_avoided, 0);
4275 assert_eq!(adb.stats().resize_reallocated, 0);
4276 assert_eq!(adb.stats().resize_growth, 0);
4277 assert_eq!(adb.stats().resize_shrink, 0);
4278 }
4279
4280 #[test]
4281 fn adaptive_buffer_swap_works() {
4282 let mut adb = AdaptiveDoubleBuffer::new(10, 5);
4283
4284 adb.current_mut().set(0, 0, Cell::from_char('A'));
4285 assert_eq!(
4286 adb.current().get(0, 0).unwrap().content.as_char(),
4287 Some('A')
4288 );
4289
4290 adb.swap();
4291 assert_eq!(
4292 adb.previous().get(0, 0).unwrap().content.as_char(),
4293 Some('A')
4294 );
4295 assert!(adb.current().get(0, 0).unwrap().is_empty());
4296 }
4297
4298 #[test]
4299 fn adaptive_buffer_stats_reset() {
4300 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4301
4302 adb.resize(90, 28);
4303 adb.resize(120, 40);
4304 assert!(adb.stats().resize_avoided > 0 || adb.stats().resize_reallocated > 0);
4305
4306 adb.reset_stats();
4307 assert_eq!(adb.stats().resize_avoided, 0);
4308 assert_eq!(adb.stats().resize_reallocated, 0);
4309 assert_eq!(adb.stats().resize_growth, 0);
4310 assert_eq!(adb.stats().resize_shrink, 0);
4311 }
4312
4313 #[test]
4314 fn adaptive_buffer_memory_efficiency() {
4315 let adb = AdaptiveDoubleBuffer::new(80, 24);
4316
4317 let efficiency = adb.memory_efficiency();
4318 assert!(efficiency > 0.5);
4322 assert!(efficiency < 1.0);
4323 }
4324
4325 #[test]
4326 fn adaptive_buffer_logical_bounds() {
4327 let adb = AdaptiveDoubleBuffer::new(80, 24);
4328
4329 let bounds = adb.logical_bounds();
4330 assert_eq!(bounds.x, 0);
4331 assert_eq!(bounds.y, 0);
4332 assert_eq!(bounds.width, 80);
4333 assert_eq!(bounds.height, 24);
4334 }
4335
4336 #[test]
4337 fn adaptive_buffer_capacity_clamped_for_large_sizes() {
4338 let adb = AdaptiveDoubleBuffer::new(1000, 500);
4340
4341 assert_eq!(adb.capacity_width(), 1000 + 200); assert_eq!(adb.capacity_height(), 500 + 125); }
4346
4347 #[test]
4348 fn adaptive_capacity_saturates_at_u16_max() {
4349 assert_eq!(
4352 AdaptiveDoubleBuffer::compute_capacity(u16::MAX, u16::MAX),
4353 (u16::MAX, u16::MAX)
4354 );
4355 let half = u16::MAX / 2;
4356 assert_eq!(
4357 AdaptiveDoubleBuffer::compute_capacity(half, half),
4358 (half + ADAPTIVE_MAX_OVERAGE, half + ADAPTIVE_MAX_OVERAGE)
4359 );
4360 assert_eq!(
4361 AdaptiveDoubleBuffer::compute_capacity(u16::MAX - 10, 1),
4362 (u16::MAX, 1)
4363 );
4364 }
4365
4366 #[test]
4367 fn adaptive_stats_avoidance_ratio() {
4368 let mut stats = AdaptiveStats::default();
4369
4370 assert!((stats.avoidance_ratio() - 1.0).abs() < f64::EPSILON);
4372
4373 stats.resize_avoided = 3;
4375 stats.resize_reallocated = 1;
4376 assert!((stats.avoidance_ratio() - 0.75).abs() < f64::EPSILON);
4377
4378 stats.resize_avoided = 0;
4380 stats.resize_reallocated = 5;
4381 assert!((stats.avoidance_ratio() - 0.0).abs() < f64::EPSILON);
4382 }
4383
4384 #[test]
4385 fn adaptive_buffer_resize_storm_simulation() {
4386 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4388
4389 for i in 1..=10 {
4391 adb.resize(80 + i, 24 + (i / 2));
4392 }
4393
4394 let ratio = adb.stats().avoidance_ratio();
4396 assert!(
4397 ratio > 0.5,
4398 "Expected >50% avoidance ratio, got {:.2}",
4399 ratio
4400 );
4401 }
4402
4403 #[test]
4404 fn adaptive_buffer_width_only_growth() {
4405 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4406
4407 assert!(adb.resize(95, 24)); assert_eq!(adb.stats().resize_avoided, 1);
4410 assert_eq!(adb.stats().resize_growth, 1);
4411 }
4412
4413 #[test]
4414 fn adaptive_buffer_height_only_growth() {
4415 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4416
4417 assert!(adb.resize(80, 28)); assert_eq!(adb.stats().resize_avoided, 1);
4420 assert_eq!(adb.stats().resize_growth, 1);
4421 }
4422
4423 #[test]
4424 fn adaptive_buffer_one_dimension_exceeds_capacity() {
4425 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4426
4427 assert!(adb.resize(105, 24)); assert_eq!(adb.stats().resize_reallocated, 1);
4430 }
4431
4432 #[test]
4433 fn adaptive_buffer_current_and_previous_distinct() {
4434 let mut adb = AdaptiveDoubleBuffer::new(10, 5);
4435 adb.current_mut().set(0, 0, Cell::from_char('X'));
4436
4437 assert!(adb.previous().get(0, 0).unwrap().is_empty());
4439 assert_eq!(
4440 adb.current().get(0, 0).unwrap().content.as_char(),
4441 Some('X')
4442 );
4443 }
4444
4445 #[test]
4446 fn adaptive_buffer_resize_within_capacity_clears_previous() {
4447 let mut adb = AdaptiveDoubleBuffer::new(10, 5);
4448 adb.current_mut().set(9, 4, Cell::from_char('X'));
4449 adb.swap();
4450
4451 assert!(adb.resize(8, 4));
4453
4454 assert!(adb.previous().get(9, 4).unwrap().is_empty());
4456 }
4457
4458 #[test]
4460 fn adaptive_buffer_invariant_capacity_geq_logical() {
4461 for width in [1u16, 10, 80, 200, 1000, 5000] {
4463 for height in [1u16, 10, 24, 100, 500, 2000] {
4464 let adb = AdaptiveDoubleBuffer::new(width, height);
4465 assert!(
4466 adb.capacity_width() >= adb.width(),
4467 "capacity_width {} < logical_width {} for ({}, {})",
4468 adb.capacity_width(),
4469 adb.width(),
4470 width,
4471 height
4472 );
4473 assert!(
4474 adb.capacity_height() >= adb.height(),
4475 "capacity_height {} < logical_height {} for ({}, {})",
4476 adb.capacity_height(),
4477 adb.height(),
4478 width,
4479 height
4480 );
4481 }
4482 }
4483 }
4484
4485 #[test]
4486 fn adaptive_buffer_invariant_resize_dimensions_correct() {
4487 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4488
4489 let test_sizes = [
4491 (100, 50),
4492 (40, 20),
4493 (80, 24),
4494 (200, 100),
4495 (10, 5),
4496 (1000, 500),
4497 ];
4498 for (w, h) in test_sizes {
4499 adb.resize(w, h);
4500 assert_eq!(adb.width(), w, "width mismatch for ({}, {})", w, h);
4501 assert_eq!(adb.height(), h, "height mismatch for ({}, {})", w, h);
4502 assert!(
4503 adb.capacity_width() >= w,
4504 "capacity_width < width for ({}, {})",
4505 w,
4506 h
4507 );
4508 assert!(
4509 adb.capacity_height() >= h,
4510 "capacity_height < height for ({}, {})",
4511 w,
4512 h
4513 );
4514 }
4515 }
4516
4517 #[test]
4521 fn adaptive_buffer_no_ghosting_on_shrink() {
4522 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4523
4524 for y in 0..adb.height() {
4526 for x in 0..adb.width() {
4527 adb.current_mut().set(x, y, Cell::from_char('X'));
4528 }
4529 }
4530
4531 adb.resize(60, 20);
4534
4535 for y in 0..adb.height() {
4538 for x in 0..adb.width() {
4539 let cell = adb.current().get(x, y).unwrap();
4540 assert!(
4541 cell.is_empty(),
4542 "Ghost content at ({}, {}): expected empty, got {:?}",
4543 x,
4544 y,
4545 cell.content
4546 );
4547 }
4548 }
4549 }
4550
4551 #[test]
4555 fn adaptive_buffer_no_ghosting_on_reallocation_shrink() {
4556 let mut adb = AdaptiveDoubleBuffer::new(100, 50);
4557
4558 for y in 0..adb.height() {
4560 for x in 0..adb.width() {
4561 adb.current_mut().set(x, y, Cell::from_char('A'));
4562 }
4563 }
4564 adb.swap();
4565 for y in 0..adb.height() {
4566 for x in 0..adb.width() {
4567 adb.current_mut().set(x, y, Cell::from_char('B'));
4568 }
4569 }
4570
4571 adb.resize(30, 15);
4573 assert_eq!(adb.stats().resize_reallocated, 1);
4574
4575 for y in 0..adb.height() {
4577 for x in 0..adb.width() {
4578 assert!(
4579 adb.current().get(x, y).unwrap().is_empty(),
4580 "Ghost in current at ({}, {})",
4581 x,
4582 y
4583 );
4584 assert!(
4585 adb.previous().get(x, y).unwrap().is_empty(),
4586 "Ghost in previous at ({}, {})",
4587 x,
4588 y
4589 );
4590 }
4591 }
4592 }
4593
4594 #[test]
4598 fn adaptive_buffer_no_ghosting_on_growth_reallocation() {
4599 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4600
4601 for y in 0..adb.height() {
4603 for x in 0..adb.width() {
4604 adb.current_mut().set(x, y, Cell::from_char('Z'));
4605 }
4606 }
4607
4608 adb.resize(150, 60);
4610 assert_eq!(adb.stats().resize_reallocated, 1);
4611
4612 for y in 0..adb.height() {
4614 for x in 0..adb.width() {
4615 assert!(
4616 adb.current().get(x, y).unwrap().is_empty(),
4617 "Ghost at ({}, {}) after growth reallocation",
4618 x,
4619 y
4620 );
4621 }
4622 }
4623 }
4624
4625 #[test]
4627 fn adaptive_buffer_resize_idempotent() {
4628 let mut adb = AdaptiveDoubleBuffer::new(80, 24);
4629 adb.current_mut().set(5, 5, Cell::from_char('K'));
4630
4631 let changed = adb.resize(80, 24);
4633 assert!(!changed);
4634
4635 assert_eq!(
4637 adb.current().get(5, 5).unwrap().content.as_char(),
4638 Some('K')
4639 );
4640 }
4641
4642 #[test]
4647 fn dirty_span_merge_adjacent() {
4648 let mut buf = Buffer::new(100, 1);
4649 buf.clear_dirty(); buf.mark_dirty_span(0, 10, 20);
4653 let spans = buf.dirty_span_row(0).unwrap().spans();
4654 assert_eq!(spans.len(), 1);
4655 assert_eq!(spans[0], DirtySpan::new(10, 20));
4656
4657 buf.mark_dirty_span(0, 20, 30);
4659 let spans = buf.dirty_span_row(0).unwrap().spans();
4660 assert_eq!(spans.len(), 1);
4661 assert_eq!(spans[0], DirtySpan::new(10, 30));
4662 }
4663
4664 #[test]
4665 fn dirty_span_merge_overlapping() {
4666 let mut buf = Buffer::new(100, 1);
4667 buf.clear_dirty();
4668
4669 buf.mark_dirty_span(0, 10, 20);
4671 buf.mark_dirty_span(0, 15, 25);
4673
4674 let spans = buf.dirty_span_row(0).unwrap().spans();
4675 assert_eq!(spans.len(), 1);
4676 assert_eq!(spans[0], DirtySpan::new(10, 25));
4677 }
4678
4679 #[test]
4680 fn dirty_span_merge_with_gap() {
4681 let mut buf = Buffer::new(100, 1);
4682 buf.clear_dirty();
4683
4684 buf.mark_dirty_span(0, 10, 20);
4687 buf.mark_dirty_span(0, 21, 30);
4689
4690 let spans = buf.dirty_span_row(0).unwrap().spans();
4691 assert_eq!(spans.len(), 1);
4692 assert_eq!(spans[0], DirtySpan::new(10, 30));
4693 }
4694
4695 #[test]
4696 fn dirty_span_no_merge_large_gap() {
4697 let mut buf = Buffer::new(100, 1);
4698 buf.clear_dirty();
4699
4700 buf.mark_dirty_span(0, 10, 20);
4702 buf.mark_dirty_span(0, 22, 30);
4704
4705 let spans = buf.dirty_span_row(0).unwrap().spans();
4706 assert_eq!(spans.len(), 2);
4707 assert_eq!(spans[0], DirtySpan::new(10, 20));
4708 assert_eq!(spans[1], DirtySpan::new(22, 30));
4709 }
4710
4711 #[test]
4712 fn dirty_span_overflow_to_full() {
4713 let mut buf = Buffer::new(1000, 1);
4714 buf.clear_dirty();
4715
4716 for i in 0..DIRTY_SPAN_MAX_SPANS_PER_ROW + 10 {
4718 let start = (i * 4) as u16;
4719 buf.mark_dirty_span(0, start, start + 1);
4720 }
4721
4722 let row = buf.dirty_span_row(0).unwrap();
4723 assert!(row.is_full(), "Row should overflow to full scan");
4724 assert!(
4725 row.spans().is_empty(),
4726 "Spans should be cleared on overflow"
4727 );
4728 }
4729
4730 #[test]
4731 fn dirty_span_bounds_clamping() {
4732 let mut buf = Buffer::new(10, 1);
4733 buf.clear_dirty();
4734
4735 buf.mark_dirty_span(0, 15, 20);
4737 let spans = buf.dirty_span_row(0).unwrap().spans();
4738 assert!(spans.is_empty());
4739
4740 buf.mark_dirty_span(0, 8, 15);
4742 let spans = buf.dirty_span_row(0).unwrap().spans();
4743 assert_eq!(spans.len(), 1);
4744 assert_eq!(spans[0], DirtySpan::new(8, 10)); }
4746
4747 #[test]
4748 fn dirty_span_guard_band_clamps_bounds() {
4749 let mut buf = Buffer::new(10, 1);
4750 buf.clear_dirty();
4751 buf.set_dirty_span_config(DirtySpanConfig::default().with_guard_band(5));
4752
4753 buf.mark_dirty_span(0, 2, 3);
4754 let spans = buf.dirty_span_row(0).unwrap().spans();
4755 assert_eq!(spans.len(), 1);
4756 assert_eq!(spans[0], DirtySpan::new(0, 8));
4757
4758 buf.clear_dirty();
4759 buf.mark_dirty_span(0, 8, 10);
4760 let spans = buf.dirty_span_row(0).unwrap().spans();
4761 assert_eq!(spans.len(), 1);
4762 assert_eq!(spans[0], DirtySpan::new(3, 10));
4763 }
4764
4765 #[test]
4766 fn dirty_span_empty_span_is_ignored() {
4767 let mut buf = Buffer::new(10, 1);
4768 buf.clear_dirty();
4769 buf.mark_dirty_span(0, 5, 5);
4770 let spans = buf.dirty_span_row(0).unwrap().spans();
4771 assert!(spans.is_empty());
4772 }
4773
4774 #[test]
4775 fn dirty_all_skips_redundant_bookkeeping_while_preserving_exact_state() {
4776 let mut buf = Buffer::new(16, 4);
4777 assert!(buf.dirty_all());
4778 assert!(buf.is_dirty_witness_consistent());
4779 let gen0 = buf.mutation_gen();
4780
4781 buf.mark_dirty_span(4, 0, 2);
4783 buf.mark_dirty_span(0, 16, 18);
4784 buf.mark_dirty_span(0, 5, 5);
4785 assert_eq!(buf.mutation_gen(), gen0);
4786
4787 buf.set(3, 1, Cell::from_char('A'));
4789 buf.fill(Rect::new(0, 2, 8, 1), Cell::from_char('B'));
4790 let gen1 = buf.mutation_gen();
4791 assert_ne!(gen1, gen0);
4792 assert!(buf.dirty_all());
4793 assert_eq!(buf.dirty_row_count(), 4);
4794 assert_eq!(buf.dirty_cell_count(), 64);
4795 assert_eq!(buf.dirty_span_stats().rows_full_dirty, 4);
4796 assert_eq!(buf.dirty_span_stats().overflows, 0);
4797 assert!(buf.is_dirty_witness_consistent());
4798
4799 buf.clear_dirty();
4801 assert!(!buf.dirty_all());
4802 assert_eq!(buf.dirty_baseline_gen(), Some(gen1));
4803 assert_eq!(buf.dirty_row_count(), 0);
4804 assert_eq!(buf.dirty_cell_count(), 0);
4805
4806 buf.set(5, 2, Cell::from_char('C'));
4807 assert!(!buf.dirty_all());
4808 assert_eq!(buf.dirty_row_count(), 1);
4809 assert_eq!(buf.dirty_cell_count(), 1);
4810 assert_eq!(
4811 buf.dirty_span_row(2).unwrap().spans(),
4812 &[DirtySpan::new(5, 6)]
4813 );
4814 assert!(buf.is_dirty_witness_consistent());
4815
4816 buf.clear();
4818 assert!(buf.dirty_all());
4819 assert!(buf.is_dirty_witness_consistent());
4820 buf.set_dirty_span_config(DirtySpanConfig::default().with_enabled(false));
4821 buf.set(1, 0, Cell::from_char('D'));
4822 assert!(buf.dirty_all());
4823 assert!(buf.is_dirty_witness_consistent());
4824 buf.set_dirty_span_config(DirtySpanConfig::default().with_enabled(true));
4825 assert_eq!(buf.dirty_span_stats().rows_full_dirty, 4);
4826 assert!(buf.is_dirty_witness_consistent());
4827 }
4828
4829 #[test]
4830 fn buffer_fill_wide_char_clipping() {
4831 let mut buf = Buffer::new(10, 5);
4835 let wide_cell = Cell::from_char('🦀'); buf.fill(Rect::new(0, 0, 10, 5), wide_cell);
4839
4840 let head = buf.get(0, 0).unwrap();
4842 assert_eq!(head.content.as_char(), Some('🦀'));
4843 assert_eq!(head.content.width(), 2);
4844
4845 let tail = buf.get(1, 0).unwrap();
4846 assert!(tail.is_continuation());
4847
4848 buf.push_scissor(Rect::new(0, 0, 1, 5));
4851 let x_cell = Cell::from_char('X');
4853 buf.fill(Rect::new(0, 0, 10, 5), x_cell);
4854
4855 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('X'));
4857 assert!(buf.get(1, 0).unwrap().is_empty()); buf.pop_scissor();
4860 }
4861
4862 #[test]
4863 fn buffer_checksum_known_vector() {
4864 let mut empty = Buffer::new(1, 1);
4865 empty.cells.clear();
4866 assert_eq!(buffer_checksum(&empty), BUFFER_CHECKSUM_FNV_OFFSET_BASIS);
4867 assert_eq!(buffer_cells_checksum(&[]), BUFFER_CHECKSUM_FNV_OFFSET_BASIS);
4868
4869 let mut buf = Buffer::new(2, 1);
4870 buf.set_raw(0, 0, Cell::from_char('a'));
4871 buf.set_raw(1, 0, Cell::from_char('b'));
4872 let expected: u64 = 0x5cda_4da4_1d73_449e;
4873 assert_eq!(buffer_checksum(&buf), expected);
4874 assert_eq!(buf.checksum(), expected);
4875
4876 let mut changed = buf.clone();
4877 changed.set_raw(1, 0, Cell::from_char('c'));
4878 assert_ne!(buffer_checksum(&changed), expected);
4879 }
4880
4881 proptest::proptest! {
4882 #[test]
4883 fn buffer_checksum_row_major_order_sensitive(
4884 c1 in proptest::prelude::any::<char>(),
4885 c2 in proptest::prelude::any::<char>(),
4886 fg1 in proptest::prelude::any::<u32>(),
4887 fg2 in proptest::prelude::any::<u32>(),
4888 ) {
4889 let cell1 = Cell::from_char(c1).with_fg(PackedRgba(fg1));
4890 let cell2 = Cell::from_char(c2).with_fg(PackedRgba(fg2));
4891 proptest::prop_assume!(cell1 != cell2);
4892
4893 let mut buf_ab = Buffer::new(2, 2);
4894 buf_ab.set_raw(1, 0, cell1);
4895 buf_ab.set_raw(0, 1, cell2);
4896
4897 let mut buf_ba = Buffer::new(2, 2);
4898 buf_ba.set_raw(1, 0, cell2);
4899 buf_ba.set_raw(0, 1, cell1);
4900
4901 proptest::prop_assert_ne!(buffer_checksum(&buf_ab), buffer_checksum(&buf_ba));
4902 }
4903 }
4904}