Skip to main content

ftui_render/
counting_writer.rs

1#![forbid(unsafe_code)]
2
3//! Counting writer for tracking bytes emitted.
4//!
5//! This module provides a wrapper around any `Write` implementation that
6//! counts the number of bytes written. This is used to verify O(changes)
7//! output size for diff-based rendering.
8//!
9//! # Usage
10//!
11//! ```
12//! use ftui_render::counting_writer::CountingWriter;
13//! use std::io::Write;
14//!
15//! let mut buffer = Vec::new();
16//! let mut writer = CountingWriter::new(&mut buffer);
17//!
18//! writer.write_all(b"Hello, world!").unwrap();
19//! assert_eq!(writer.bytes_written(), 13);
20//!
21//! writer.reset_counter();
22//! writer.write_all(b"Hi").unwrap();
23//! assert_eq!(writer.bytes_written(), 2);
24//! ```
25
26use std::io::{self, Write};
27use web_time::{Duration, Instant};
28
29/// A write wrapper that counts bytes written.
30///
31/// Wraps any `Write` implementation and tracks the total number of bytes
32/// written through it. The counter can be reset between operations.
33#[derive(Debug)]
34pub struct CountingWriter<W> {
35    /// The underlying writer.
36    inner: W,
37    /// Total bytes written since last reset.
38    bytes_written: u64,
39}
40
41impl<W> CountingWriter<W> {
42    /// Create a new counting writer wrapping the given writer.
43    #[inline]
44    pub fn new(inner: W) -> Self {
45        Self {
46            inner,
47            bytes_written: 0,
48        }
49    }
50
51    /// Get the number of bytes written since the last reset.
52    #[inline]
53    pub fn bytes_written(&self) -> u64 {
54        self.bytes_written
55    }
56
57    /// Reset the byte counter to zero.
58    #[inline]
59    pub fn reset_counter(&mut self) {
60        self.bytes_written = 0;
61    }
62
63    /// Get a reference to the underlying writer.
64    #[inline]
65    #[must_use]
66    pub fn inner(&self) -> &W {
67        &self.inner
68    }
69
70    /// Get a mutable reference to the underlying writer.
71    #[inline]
72    #[must_use]
73    pub fn inner_mut(&mut self) -> &mut W {
74        &mut self.inner
75    }
76
77    /// Consume the counting writer and return the inner writer.
78    #[inline]
79    #[must_use]
80    pub fn into_inner(self) -> W {
81        self.inner
82    }
83}
84
85impl<W: Write> Write for CountingWriter<W> {
86    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
87        let n = self.inner.write(buf)?;
88        self.bytes_written += n as u64;
89        Ok(n)
90    }
91
92    fn flush(&mut self) -> io::Result<()> {
93        self.inner.flush()
94    }
95
96    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
97        self.inner.write_all(buf)?;
98        self.bytes_written += buf.len() as u64;
99        Ok(())
100    }
101}
102
103/// Statistics from a present() operation.
104///
105/// Captures metrics for verifying O(changes) output size and detecting
106/// performance regressions.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct PresentStats {
109    /// Bytes emitted for this frame.
110    pub bytes_emitted: u64,
111    /// Number of cells changed.
112    pub cells_changed: usize,
113    /// Number of runs (groups of consecutive changes).
114    pub run_count: usize,
115    /// Time spent in present().
116    pub duration: Duration,
117}
118
119impl PresentStats {
120    /// Create new stats with the given values.
121    #[inline]
122    pub fn new(
123        bytes_emitted: u64,
124        cells_changed: usize,
125        run_count: usize,
126        duration: Duration,
127    ) -> Self {
128        Self {
129            bytes_emitted,
130            cells_changed,
131            run_count,
132            duration,
133        }
134    }
135
136    /// Calculate bytes per cell changed.
137    ///
138    /// Returns 0.0 if no cells were changed.
139    #[inline]
140    pub fn bytes_per_cell(&self) -> f64 {
141        if self.cells_changed == 0 {
142            0.0
143        } else {
144            self.bytes_emitted as f64 / self.cells_changed as f64
145        }
146    }
147
148    /// Calculate bytes per run.
149    ///
150    /// Returns 0.0 if no runs.
151    #[inline]
152    pub fn bytes_per_run(&self) -> f64 {
153        if self.run_count == 0 {
154            0.0
155        } else {
156            self.bytes_emitted as f64 / self.run_count as f64
157        }
158    }
159
160    /// Check if output is within the expected budget.
161    ///
162    /// Uses conservative estimates for worst-case bytes per cell.
163    #[inline]
164    pub fn within_budget(&self) -> bool {
165        let budget = expected_max_bytes(self.cells_changed, self.run_count);
166        self.bytes_emitted <= budget
167    }
168
169    /// Log stats at debug level (requires tracing feature).
170    #[cfg(feature = "tracing")]
171    pub fn log(&self) {
172        tracing::debug!(
173            bytes = self.bytes_emitted,
174            cells_changed = self.cells_changed,
175            runs = self.run_count,
176            duration_us = self.duration.as_micros() as u64,
177            bytes_per_cell = format!("{:.1}", self.bytes_per_cell()),
178            "Present stats"
179        );
180    }
181
182    /// Log stats at debug level (no-op without tracing feature).
183    #[cfg(not(feature = "tracing"))]
184    pub fn log(&self) {
185        // No-op without tracing
186    }
187}
188
189impl Default for PresentStats {
190    fn default() -> Self {
191        Self {
192            bytes_emitted: 0,
193            cells_changed: 0,
194            run_count: 0,
195            duration: Duration::ZERO,
196        }
197    }
198}
199
200/// Expected bytes per cell change (approximate worst case).
201///
202/// Worst case: cursor move (10) + full SGR reset+apply (25) + 4-byte UTF-8 char
203pub const BYTES_PER_CELL_MAX: u64 = 40;
204
205/// Bytes for sync output wrapper.
206pub const SYNC_OVERHEAD: u64 = 20;
207
208/// Bytes for cursor move sequence (CUP).
209pub const BYTES_PER_CURSOR_MOVE: u64 = 10;
210
211/// Calculate expected maximum bytes for a frame with given changes.
212///
213/// This is a conservative budget for regression testing.
214#[inline]
215pub fn expected_max_bytes(cells_changed: usize, runs: usize) -> u64 {
216    // cursor move per run + cells * max_per_cell + sync overhead
217    (runs as u64 * BYTES_PER_CURSOR_MOVE)
218        + (cells_changed as u64 * BYTES_PER_CELL_MAX)
219        + SYNC_OVERHEAD
220}
221
222/// Calculate the strict O(changes) byte budget (`8 * cells_changed + 64`)
223/// enforced by the performance regression gate for sparse frames.
224#[inline]
225#[must_use]
226pub const fn plan_bytes_budget(cells_changed: usize) -> u64 {
227    (cells_changed as u64).saturating_mul(8).saturating_add(64)
228}
229
230/// A stats collector for measuring present operations.
231///
232/// Use this to wrap present() calls and collect statistics.
233#[derive(Debug)]
234pub struct StatsCollector {
235    start: Instant,
236    cells_changed: usize,
237    run_count: usize,
238}
239
240impl StatsCollector {
241    /// Start collecting stats for a present operation.
242    #[inline]
243    pub fn start(cells_changed: usize, run_count: usize) -> Self {
244        Self {
245            start: Instant::now(),
246            cells_changed,
247            run_count,
248        }
249    }
250
251    /// Finish collecting and return stats.
252    #[inline]
253    pub fn finish(self, bytes_emitted: u64) -> PresentStats {
254        PresentStats {
255            bytes_emitted,
256            cells_changed: self.cells_changed,
257            run_count: self.run_count,
258            duration: self.start.elapsed(),
259        }
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    // ============== CountingWriter Tests ==============
268
269    #[test]
270    fn counting_writer_basic() {
271        let mut buffer = Vec::new();
272        let mut writer = CountingWriter::new(&mut buffer);
273
274        writer.write_all(b"Hello").unwrap();
275        assert_eq!(writer.bytes_written(), 5);
276
277        writer.write_all(b", world!").unwrap();
278        assert_eq!(writer.bytes_written(), 13);
279    }
280
281    #[test]
282    fn counting_writer_reset() {
283        let mut buffer = Vec::new();
284        let mut writer = CountingWriter::new(&mut buffer);
285
286        writer.write_all(b"Hello").unwrap();
287        assert_eq!(writer.bytes_written(), 5);
288
289        writer.reset_counter();
290        assert_eq!(writer.bytes_written(), 0);
291
292        writer.write_all(b"Hi").unwrap();
293        assert_eq!(writer.bytes_written(), 2);
294    }
295
296    #[test]
297    fn counting_writer_write() {
298        let mut buffer = Vec::new();
299        let mut writer = CountingWriter::new(&mut buffer);
300
301        // write() may write partial buffer
302        let n = writer.write(b"Hello").unwrap();
303        assert_eq!(n, 5);
304        assert_eq!(writer.bytes_written(), 5);
305    }
306
307    #[test]
308    fn counting_writer_flush() {
309        let mut buffer = Vec::new();
310        let mut writer = CountingWriter::new(&mut buffer);
311
312        writer.write_all(b"test").unwrap();
313        writer.flush().unwrap();
314
315        // flush doesn't change byte count
316        assert_eq!(writer.bytes_written(), 4);
317    }
318
319    #[test]
320    fn counting_writer_into_inner() {
321        let buffer: Vec<u8> = Vec::new();
322        let writer = CountingWriter::new(buffer);
323        let inner = writer.into_inner();
324        assert!(inner.is_empty());
325    }
326
327    #[test]
328    fn counting_writer_inner_ref() {
329        let mut buffer = Vec::new();
330        let mut writer = CountingWriter::new(&mut buffer);
331        writer.write_all(b"test").unwrap();
332
333        assert_eq!(writer.inner().len(), 4);
334    }
335
336    // ============== PresentStats Tests ==============
337
338    #[test]
339    fn stats_bytes_per_cell() {
340        let stats = PresentStats::new(100, 10, 2, Duration::from_micros(50));
341        assert!((stats.bytes_per_cell() - 10.0).abs() < f64::EPSILON);
342    }
343
344    #[test]
345    fn stats_bytes_per_cell_zero() {
346        let stats = PresentStats::new(0, 0, 0, Duration::ZERO);
347        assert!((stats.bytes_per_cell() - 0.0).abs() < f64::EPSILON);
348    }
349
350    #[test]
351    fn stats_bytes_per_run() {
352        let stats = PresentStats::new(100, 10, 5, Duration::from_micros(50));
353        assert!((stats.bytes_per_run() - 20.0).abs() < f64::EPSILON);
354    }
355
356    #[test]
357    fn stats_bytes_per_run_zero() {
358        let stats = PresentStats::new(0, 0, 0, Duration::ZERO);
359        assert!((stats.bytes_per_run() - 0.0).abs() < f64::EPSILON);
360    }
361
362    #[test]
363    fn stats_within_budget_pass() {
364        // 10 cells, 2 runs
365        // Budget = 2*10 + 10*40 + 20 = 440
366        let stats = PresentStats::new(200, 10, 2, Duration::from_micros(50));
367        assert!(stats.within_budget());
368    }
369
370    #[test]
371    fn stats_within_budget_fail() {
372        // 10 cells, 2 runs
373        // Budget = 2*10 + 10*40 + 20 = 440
374        let stats = PresentStats::new(500, 10, 2, Duration::from_micros(50));
375        assert!(!stats.within_budget());
376    }
377
378    #[test]
379    fn stats_default() {
380        let stats = PresentStats::default();
381        assert_eq!(stats.bytes_emitted, 0);
382        assert_eq!(stats.cells_changed, 0);
383        assert_eq!(stats.run_count, 0);
384        assert_eq!(stats.duration, Duration::ZERO);
385    }
386
387    // ============== Budget Calculation Tests ==============
388
389    #[test]
390    fn expected_max_bytes_calculation() {
391        // 10 cells, 2 runs
392        let budget = expected_max_bytes(10, 2);
393        // 2*10 + 10*40 + 20 = 440
394        assert_eq!(budget, 440);
395    }
396
397    #[test]
398    fn expected_max_bytes_empty() {
399        let budget = expected_max_bytes(0, 0);
400        // Just sync overhead
401        assert_eq!(budget, SYNC_OVERHEAD);
402    }
403
404    #[test]
405    fn expected_max_bytes_single_cell() {
406        let budget = expected_max_bytes(1, 1);
407        // 1*10 + 1*40 + 20 = 70
408        assert_eq!(budget, 70);
409    }
410
411    // ============== StatsCollector Tests ==============
412
413    #[test]
414    fn stats_collector_basic() {
415        let collector = StatsCollector::start(10, 2);
416        std::thread::sleep(Duration::from_micros(100));
417        let stats = collector.finish(150);
418
419        assert_eq!(stats.cells_changed, 10);
420        assert_eq!(stats.run_count, 2);
421        assert_eq!(stats.bytes_emitted, 150);
422        assert!(stats.duration >= Duration::from_micros(100));
423    }
424
425    // ============== Integration Tests ==============
426
427    #[test]
428    fn full_stats_workflow() {
429        let mut buffer = Vec::new();
430        let mut writer = CountingWriter::new(&mut buffer);
431
432        // Simulate present operation
433        let collector = StatsCollector::start(5, 1);
434
435        writer.write_all(b"\x1b[1;1H").unwrap(); // CUP
436        writer.write_all(b"\x1b[0m").unwrap(); // SGR reset
437        writer.write_all(b"Hello").unwrap(); // Content
438        writer.flush().unwrap();
439
440        let stats = collector.finish(writer.bytes_written());
441
442        assert_eq!(stats.cells_changed, 5);
443        assert_eq!(stats.run_count, 1);
444        assert_eq!(stats.bytes_emitted, 6 + 4 + 5); // 15 bytes
445        assert!(stats.within_budget());
446    }
447
448    #[test]
449    fn spinner_update_budget() {
450        // Single cell update should be well under budget
451        let stats = PresentStats::new(35, 1, 1, Duration::from_micros(10));
452        assert!(
453            stats.within_budget(),
454            "Single cell update should be within budget"
455        );
456        assert!(
457            stats.bytes_emitted < 50,
458            "Spinner tick should be < 50 bytes"
459        );
460    }
461
462    #[test]
463    fn status_bar_budget() {
464        // 80-column status bar
465        let stats = PresentStats::new(2500, 80, 1, Duration::from_micros(100));
466        assert!(
467            stats.within_budget(),
468            "Status bar update should be within budget"
469        );
470        assert!(
471            stats.bytes_emitted < 3500,
472            "Status bar should be < 3500 bytes"
473        );
474    }
475
476    #[test]
477    fn full_redraw_budget() {
478        // Full 80x24 screen
479        let stats = PresentStats::new(50000, 1920, 24, Duration::from_micros(1000));
480        assert!(stats.within_budget(), "Full redraw should be within budget");
481        assert!(stats.bytes_emitted < 80000, "Full redraw should be < 80KB");
482    }
483
484    // --- CountingWriter edge cases ---
485
486    #[test]
487    fn counting_writer_debug() {
488        let buffer: Vec<u8> = Vec::new();
489        let writer = CountingWriter::new(buffer);
490        let dbg = format!("{:?}", writer);
491        assert!(dbg.contains("CountingWriter"), "Debug: {dbg}");
492    }
493
494    #[test]
495    fn counting_writer_inner_mut() {
496        let mut writer = CountingWriter::new(Vec::<u8>::new());
497        writer.write_all(b"hello").unwrap();
498        // Modify inner via inner_mut
499        writer.inner_mut().push(b'!');
500        assert_eq!(writer.inner(), &b"hello!"[..]);
501        // Byte counter unchanged by direct inner manipulation
502        assert_eq!(writer.bytes_written(), 5);
503    }
504
505    #[test]
506    fn counting_writer_empty_write() {
507        let mut buffer = Vec::new();
508        let mut writer = CountingWriter::new(&mut buffer);
509        writer.write_all(b"").unwrap();
510        assert_eq!(writer.bytes_written(), 0);
511        let n = writer.write(b"").unwrap();
512        assert_eq!(n, 0);
513        assert_eq!(writer.bytes_written(), 0);
514    }
515
516    #[test]
517    fn counting_writer_multiple_resets() {
518        let mut buffer = Vec::new();
519        let mut writer = CountingWriter::new(&mut buffer);
520        writer.write_all(b"abc").unwrap();
521        writer.reset_counter();
522        writer.reset_counter();
523        assert_eq!(writer.bytes_written(), 0);
524        writer.write_all(b"de").unwrap();
525        assert_eq!(writer.bytes_written(), 2);
526    }
527
528    #[test]
529    fn counting_writer_accumulates_u64() {
530        let mut buffer = Vec::new();
531        let mut writer = CountingWriter::new(&mut buffer);
532        // Write enough to test u64 accumulation (though not near overflow)
533        for _ in 0..1000 {
534            writer.write_all(b"x").unwrap();
535        }
536        assert_eq!(writer.bytes_written(), 1000);
537    }
538
539    #[test]
540    fn counting_writer_multiple_flushes() {
541        let mut buffer = Vec::new();
542        let mut writer = CountingWriter::new(&mut buffer);
543        writer.write_all(b"test").unwrap();
544        writer.flush().unwrap();
545        writer.flush().unwrap();
546        writer.flush().unwrap();
547        assert_eq!(writer.bytes_written(), 4);
548    }
549
550    #[test]
551    fn counting_writer_into_inner_preserves_data() {
552        let mut writer = CountingWriter::new(Vec::<u8>::new());
553        writer.write_all(b"hello world").unwrap();
554        let inner = writer.into_inner();
555        assert_eq!(&inner, b"hello world");
556    }
557
558    #[test]
559    fn counting_writer_initial_state() {
560        let buffer: Vec<u8> = Vec::new();
561        let writer = CountingWriter::new(buffer);
562        assert_eq!(writer.bytes_written(), 0);
563        assert!(writer.inner().is_empty());
564    }
565
566    // --- PresentStats edge cases ---
567
568    #[test]
569    fn present_stats_debug_clone_eq() {
570        let a = PresentStats::new(100, 10, 2, Duration::from_micros(50));
571        let dbg = format!("{:?}", a);
572        assert!(dbg.contains("PresentStats"), "Debug: {dbg}");
573        let cloned = a.clone();
574        assert_eq!(a, cloned);
575        let b = PresentStats::new(200, 10, 2, Duration::from_micros(50));
576        assert_ne!(a, b);
577    }
578
579    #[test]
580    fn present_stats_log_noop() {
581        let stats = PresentStats::default();
582        stats.log(); // Should not panic (noop without tracing)
583    }
584
585    #[test]
586    fn present_stats_large_values() {
587        let stats = PresentStats::new(u64::MAX, usize::MAX, usize::MAX, Duration::MAX);
588        assert_eq!(stats.bytes_emitted, u64::MAX);
589        assert_eq!(stats.cells_changed, usize::MAX);
590    }
591
592    #[test]
593    fn present_stats_bytes_per_cell_fractional() {
594        let stats = PresentStats::new(10, 3, 1, Duration::ZERO);
595        let bpc = stats.bytes_per_cell();
596        assert!((bpc - 3.333333333).abs() < 0.001);
597    }
598
599    #[test]
600    fn present_stats_bytes_per_run_fractional() {
601        let stats = PresentStats::new(10, 5, 3, Duration::ZERO);
602        let bpr = stats.bytes_per_run();
603        assert!((bpr - 3.333333333).abs() < 0.001);
604    }
605
606    #[test]
607    fn present_stats_within_budget_at_exact_boundary() {
608        // Budget for 10 cells, 2 runs: 2*10 + 10*40 + 20 = 440
609        let budget = expected_max_bytes(10, 2);
610        assert_eq!(budget, 440);
611
612        let at_boundary = PresentStats::new(440, 10, 2, Duration::ZERO);
613        assert!(at_boundary.within_budget());
614
615        let over_boundary = PresentStats::new(441, 10, 2, Duration::ZERO);
616        assert!(!over_boundary.within_budget());
617    }
618
619    // --- Constants ---
620
621    #[test]
622    fn constants_values() {
623        assert_eq!(BYTES_PER_CELL_MAX, 40);
624        assert_eq!(SYNC_OVERHEAD, 20);
625        assert_eq!(BYTES_PER_CURSOR_MOVE, 10);
626    }
627
628    // --- expected_max_bytes edge cases ---
629
630    #[test]
631    fn expected_max_bytes_many_runs_few_cells() {
632        // 1 cell, 100 runs (pathological case)
633        let budget = expected_max_bytes(1, 100);
634        // 100*10 + 1*40 + 20 = 1060
635        assert_eq!(budget, 1060);
636    }
637
638    #[test]
639    fn expected_max_bytes_many_cells_one_run() {
640        let budget = expected_max_bytes(1000, 1);
641        // 1*10 + 1000*40 + 20 = 40030
642        assert_eq!(budget, 40030);
643    }
644
645    // --- StatsCollector edge cases ---
646
647    #[test]
648    fn stats_collector_debug() {
649        let collector = StatsCollector::start(5, 2);
650        let dbg = format!("{:?}", collector);
651        assert!(dbg.contains("StatsCollector"), "Debug: {dbg}");
652    }
653
654    #[test]
655    fn stats_collector_zero_cells_runs() {
656        let collector = StatsCollector::start(0, 0);
657        let stats = collector.finish(0);
658        assert_eq!(stats.cells_changed, 0);
659        assert_eq!(stats.run_count, 0);
660        assert_eq!(stats.bytes_emitted, 0);
661        assert!(stats.within_budget()); // 0 <= SYNC_OVERHEAD
662    }
663
664    #[test]
665    fn stats_collector_immediate_finish() {
666        let collector = StatsCollector::start(1, 1);
667        let stats = collector.finish(50);
668        assert_eq!(stats.bytes_emitted, 50);
669        // Duration should be very small (near zero)
670        assert!(stats.duration < Duration::from_millis(100));
671    }
672
673    #[test]
674    fn counting_writer_counts_and_resets() {
675        let mut sink = Vec::new();
676        let mut writer = CountingWriter::new(&mut sink);
677        writer.write_all(b"frame-1").unwrap();
678        assert_eq!(writer.bytes_written(), 7);
679        writer.reset_counter();
680        assert_eq!(writer.bytes_written(), 0);
681        writer.write_all(b"ok").unwrap();
682        assert_eq!(writer.bytes_written(), 2);
683    }
684
685    #[test]
686    fn within_budget_true_for_sparse_frame() {
687        // 80x24 @ 5% = 96 cells across 2 runs; ~150 bytes emitted.
688        let stats = PresentStats::new(150, 96, 2, Duration::from_micros(40));
689        assert!(stats.within_budget());
690        assert!(stats.bytes_emitted <= plan_bytes_budget(stats.cells_changed));
691    }
692
693    #[test]
694    fn bytes_budget_formula_8x_plus_64() {
695        assert_eq!(plan_bytes_budget(0), 64);
696        assert_eq!(plan_bytes_budget(96), 8 * 96 + 64);
697        assert_eq!(plan_bytes_budget(240), 8 * 240 + 64);
698        assert_eq!(plan_bytes_budget(600), 8 * 600 + 64);
699    }
700}