ftui-render 0.3.1

Render kernel: cells, buffers, diffs, and ANSI presentation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
#![forbid(unsafe_code)]

//! Counting writer for tracking bytes emitted.
//!
//! This module provides a wrapper around any `Write` implementation that
//! counts the number of bytes written. This is used to verify O(changes)
//! output size for diff-based rendering.
//!
//! # Usage
//!
//! ```
//! use ftui_render::counting_writer::CountingWriter;
//! use std::io::Write;
//!
//! let mut buffer = Vec::new();
//! let mut writer = CountingWriter::new(&mut buffer);
//!
//! writer.write_all(b"Hello, world!").unwrap();
//! assert_eq!(writer.bytes_written(), 13);
//!
//! writer.reset_counter();
//! writer.write_all(b"Hi").unwrap();
//! assert_eq!(writer.bytes_written(), 2);
//! ```

use std::io::{self, Write};
use web_time::{Duration, Instant};

/// A write wrapper that counts bytes written.
///
/// Wraps any `Write` implementation and tracks the total number of bytes
/// written through it. The counter can be reset between operations.
#[derive(Debug)]
pub struct CountingWriter<W> {
    /// The underlying writer.
    inner: W,
    /// Total bytes written since last reset.
    bytes_written: u64,
}

impl<W> CountingWriter<W> {
    /// Create a new counting writer wrapping the given writer.
    #[inline]
    pub fn new(inner: W) -> Self {
        Self {
            inner,
            bytes_written: 0,
        }
    }

    /// Get the number of bytes written since the last reset.
    #[inline]
    pub fn bytes_written(&self) -> u64 {
        self.bytes_written
    }

    /// Reset the byte counter to zero.
    #[inline]
    pub fn reset_counter(&mut self) {
        self.bytes_written = 0;
    }

    /// Get a reference to the underlying writer.
    #[inline]
    #[must_use]
    pub fn inner(&self) -> &W {
        &self.inner
    }

    /// Get a mutable reference to the underlying writer.
    #[inline]
    #[must_use]
    pub fn inner_mut(&mut self) -> &mut W {
        &mut self.inner
    }

    /// Consume the counting writer and return the inner writer.
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> W {
        self.inner
    }
}

impl<W: Write> Write for CountingWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let n = self.inner.write(buf)?;
        self.bytes_written += n as u64;
        Ok(n)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }

    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.inner.write_all(buf)?;
        self.bytes_written += buf.len() as u64;
        Ok(())
    }
}

/// Statistics from a present() operation.
///
/// Captures metrics for verifying O(changes) output size and detecting
/// performance regressions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PresentStats {
    /// Bytes emitted for this frame.
    pub bytes_emitted: u64,
    /// Number of cells changed.
    pub cells_changed: usize,
    /// Number of runs (groups of consecutive changes).
    pub run_count: usize,
    /// Time spent in present().
    pub duration: Duration,
}

impl PresentStats {
    /// Create new stats with the given values.
    #[inline]
    pub fn new(
        bytes_emitted: u64,
        cells_changed: usize,
        run_count: usize,
        duration: Duration,
    ) -> Self {
        Self {
            bytes_emitted,
            cells_changed,
            run_count,
            duration,
        }
    }

    /// Calculate bytes per cell changed.
    ///
    /// Returns 0.0 if no cells were changed.
    #[inline]
    pub fn bytes_per_cell(&self) -> f64 {
        if self.cells_changed == 0 {
            0.0
        } else {
            self.bytes_emitted as f64 / self.cells_changed as f64
        }
    }

    /// Calculate bytes per run.
    ///
    /// Returns 0.0 if no runs.
    #[inline]
    pub fn bytes_per_run(&self) -> f64 {
        if self.run_count == 0 {
            0.0
        } else {
            self.bytes_emitted as f64 / self.run_count as f64
        }
    }

    /// Check if output is within the expected budget.
    ///
    /// Uses conservative estimates for worst-case bytes per cell.
    #[inline]
    pub fn within_budget(&self) -> bool {
        let budget = expected_max_bytes(self.cells_changed, self.run_count);
        self.bytes_emitted <= budget
    }

    /// Log stats at debug level (requires tracing feature).
    #[cfg(feature = "tracing")]
    pub fn log(&self) {
        tracing::debug!(
            bytes = self.bytes_emitted,
            cells_changed = self.cells_changed,
            runs = self.run_count,
            duration_us = self.duration.as_micros() as u64,
            bytes_per_cell = format!("{:.1}", self.bytes_per_cell()),
            "Present stats"
        );
    }

    /// Log stats at debug level (no-op without tracing feature).
    #[cfg(not(feature = "tracing"))]
    pub fn log(&self) {
        // No-op without tracing
    }
}

impl Default for PresentStats {
    fn default() -> Self {
        Self {
            bytes_emitted: 0,
            cells_changed: 0,
            run_count: 0,
            duration: Duration::ZERO,
        }
    }
}

/// Expected bytes per cell change (approximate worst case).
///
/// Worst case: cursor move (10) + full SGR reset+apply (25) + 4-byte UTF-8 char
pub const BYTES_PER_CELL_MAX: u64 = 40;

/// Bytes for sync output wrapper.
pub const SYNC_OVERHEAD: u64 = 20;

/// Bytes for cursor move sequence (CUP).
pub const BYTES_PER_CURSOR_MOVE: u64 = 10;

/// Calculate expected maximum bytes for a frame with given changes.
///
/// This is a conservative budget for regression testing.
#[inline]
pub fn expected_max_bytes(cells_changed: usize, runs: usize) -> u64 {
    // cursor move per run + cells * max_per_cell + sync overhead
    (runs as u64 * BYTES_PER_CURSOR_MOVE)
        + (cells_changed as u64 * BYTES_PER_CELL_MAX)
        + SYNC_OVERHEAD
}

/// A stats collector for measuring present operations.
///
/// Use this to wrap present() calls and collect statistics.
#[derive(Debug)]
pub struct StatsCollector {
    start: Instant,
    cells_changed: usize,
    run_count: usize,
}

impl StatsCollector {
    /// Start collecting stats for a present operation.
    #[inline]
    pub fn start(cells_changed: usize, run_count: usize) -> Self {
        Self {
            start: Instant::now(),
            cells_changed,
            run_count,
        }
    }

    /// Finish collecting and return stats.
    #[inline]
    pub fn finish(self, bytes_emitted: u64) -> PresentStats {
        PresentStats {
            bytes_emitted,
            cells_changed: self.cells_changed,
            run_count: self.run_count,
            duration: self.start.elapsed(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ============== CountingWriter Tests ==============

    #[test]
    fn counting_writer_basic() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);

        writer.write_all(b"Hello").unwrap();
        assert_eq!(writer.bytes_written(), 5);

        writer.write_all(b", world!").unwrap();
        assert_eq!(writer.bytes_written(), 13);
    }

    #[test]
    fn counting_writer_reset() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);

        writer.write_all(b"Hello").unwrap();
        assert_eq!(writer.bytes_written(), 5);

        writer.reset_counter();
        assert_eq!(writer.bytes_written(), 0);

        writer.write_all(b"Hi").unwrap();
        assert_eq!(writer.bytes_written(), 2);
    }

    #[test]
    fn counting_writer_write() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);

        // write() may write partial buffer
        let n = writer.write(b"Hello").unwrap();
        assert_eq!(n, 5);
        assert_eq!(writer.bytes_written(), 5);
    }

    #[test]
    fn counting_writer_flush() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);

        writer.write_all(b"test").unwrap();
        writer.flush().unwrap();

        // flush doesn't change byte count
        assert_eq!(writer.bytes_written(), 4);
    }

    #[test]
    fn counting_writer_into_inner() {
        let buffer: Vec<u8> = Vec::new();
        let writer = CountingWriter::new(buffer);
        let inner = writer.into_inner();
        assert!(inner.is_empty());
    }

    #[test]
    fn counting_writer_inner_ref() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);
        writer.write_all(b"test").unwrap();

        assert_eq!(writer.inner().len(), 4);
    }

    // ============== PresentStats Tests ==============

    #[test]
    fn stats_bytes_per_cell() {
        let stats = PresentStats::new(100, 10, 2, Duration::from_micros(50));
        assert!((stats.bytes_per_cell() - 10.0).abs() < f64::EPSILON);
    }

    #[test]
    fn stats_bytes_per_cell_zero() {
        let stats = PresentStats::new(0, 0, 0, Duration::ZERO);
        assert!((stats.bytes_per_cell() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn stats_bytes_per_run() {
        let stats = PresentStats::new(100, 10, 5, Duration::from_micros(50));
        assert!((stats.bytes_per_run() - 20.0).abs() < f64::EPSILON);
    }

    #[test]
    fn stats_bytes_per_run_zero() {
        let stats = PresentStats::new(0, 0, 0, Duration::ZERO);
        assert!((stats.bytes_per_run() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn stats_within_budget_pass() {
        // 10 cells, 2 runs
        // Budget = 2*10 + 10*40 + 20 = 440
        let stats = PresentStats::new(200, 10, 2, Duration::from_micros(50));
        assert!(stats.within_budget());
    }

    #[test]
    fn stats_within_budget_fail() {
        // 10 cells, 2 runs
        // Budget = 2*10 + 10*40 + 20 = 440
        let stats = PresentStats::new(500, 10, 2, Duration::from_micros(50));
        assert!(!stats.within_budget());
    }

    #[test]
    fn stats_default() {
        let stats = PresentStats::default();
        assert_eq!(stats.bytes_emitted, 0);
        assert_eq!(stats.cells_changed, 0);
        assert_eq!(stats.run_count, 0);
        assert_eq!(stats.duration, Duration::ZERO);
    }

    // ============== Budget Calculation Tests ==============

    #[test]
    fn expected_max_bytes_calculation() {
        // 10 cells, 2 runs
        let budget = expected_max_bytes(10, 2);
        // 2*10 + 10*40 + 20 = 440
        assert_eq!(budget, 440);
    }

    #[test]
    fn expected_max_bytes_empty() {
        let budget = expected_max_bytes(0, 0);
        // Just sync overhead
        assert_eq!(budget, SYNC_OVERHEAD);
    }

    #[test]
    fn expected_max_bytes_single_cell() {
        let budget = expected_max_bytes(1, 1);
        // 1*10 + 1*40 + 20 = 70
        assert_eq!(budget, 70);
    }

    // ============== StatsCollector Tests ==============

    #[test]
    fn stats_collector_basic() {
        let collector = StatsCollector::start(10, 2);
        std::thread::sleep(Duration::from_micros(100));
        let stats = collector.finish(150);

        assert_eq!(stats.cells_changed, 10);
        assert_eq!(stats.run_count, 2);
        assert_eq!(stats.bytes_emitted, 150);
        assert!(stats.duration >= Duration::from_micros(100));
    }

    // ============== Integration Tests ==============

    #[test]
    fn full_stats_workflow() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);

        // Simulate present operation
        let collector = StatsCollector::start(5, 1);

        writer.write_all(b"\x1b[1;1H").unwrap(); // CUP
        writer.write_all(b"\x1b[0m").unwrap(); // SGR reset
        writer.write_all(b"Hello").unwrap(); // Content
        writer.flush().unwrap();

        let stats = collector.finish(writer.bytes_written());

        assert_eq!(stats.cells_changed, 5);
        assert_eq!(stats.run_count, 1);
        assert_eq!(stats.bytes_emitted, 6 + 4 + 5); // 15 bytes
        assert!(stats.within_budget());
    }

    #[test]
    fn spinner_update_budget() {
        // Single cell update should be well under budget
        let stats = PresentStats::new(35, 1, 1, Duration::from_micros(10));
        assert!(
            stats.within_budget(),
            "Single cell update should be within budget"
        );
        assert!(
            stats.bytes_emitted < 50,
            "Spinner tick should be < 50 bytes"
        );
    }

    #[test]
    fn status_bar_budget() {
        // 80-column status bar
        let stats = PresentStats::new(2500, 80, 1, Duration::from_micros(100));
        assert!(
            stats.within_budget(),
            "Status bar update should be within budget"
        );
        assert!(
            stats.bytes_emitted < 3500,
            "Status bar should be < 3500 bytes"
        );
    }

    #[test]
    fn full_redraw_budget() {
        // Full 80x24 screen
        let stats = PresentStats::new(50000, 1920, 24, Duration::from_micros(1000));
        assert!(stats.within_budget(), "Full redraw should be within budget");
        assert!(stats.bytes_emitted < 80000, "Full redraw should be < 80KB");
    }

    // --- CountingWriter edge cases ---

    #[test]
    fn counting_writer_debug() {
        let buffer: Vec<u8> = Vec::new();
        let writer = CountingWriter::new(buffer);
        let dbg = format!("{:?}", writer);
        assert!(dbg.contains("CountingWriter"), "Debug: {dbg}");
    }

    #[test]
    fn counting_writer_inner_mut() {
        let mut writer = CountingWriter::new(Vec::<u8>::new());
        writer.write_all(b"hello").unwrap();
        // Modify inner via inner_mut
        writer.inner_mut().push(b'!');
        assert_eq!(writer.inner(), &b"hello!"[..]);
        // Byte counter unchanged by direct inner manipulation
        assert_eq!(writer.bytes_written(), 5);
    }

    #[test]
    fn counting_writer_empty_write() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);
        writer.write_all(b"").unwrap();
        assert_eq!(writer.bytes_written(), 0);
        let n = writer.write(b"").unwrap();
        assert_eq!(n, 0);
        assert_eq!(writer.bytes_written(), 0);
    }

    #[test]
    fn counting_writer_multiple_resets() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);
        writer.write_all(b"abc").unwrap();
        writer.reset_counter();
        writer.reset_counter();
        assert_eq!(writer.bytes_written(), 0);
        writer.write_all(b"de").unwrap();
        assert_eq!(writer.bytes_written(), 2);
    }

    #[test]
    fn counting_writer_accumulates_u64() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);
        // Write enough to test u64 accumulation (though not near overflow)
        for _ in 0..1000 {
            writer.write_all(b"x").unwrap();
        }
        assert_eq!(writer.bytes_written(), 1000);
    }

    #[test]
    fn counting_writer_multiple_flushes() {
        let mut buffer = Vec::new();
        let mut writer = CountingWriter::new(&mut buffer);
        writer.write_all(b"test").unwrap();
        writer.flush().unwrap();
        writer.flush().unwrap();
        writer.flush().unwrap();
        assert_eq!(writer.bytes_written(), 4);
    }

    #[test]
    fn counting_writer_into_inner_preserves_data() {
        let mut writer = CountingWriter::new(Vec::<u8>::new());
        writer.write_all(b"hello world").unwrap();
        let inner = writer.into_inner();
        assert_eq!(&inner, b"hello world");
    }

    #[test]
    fn counting_writer_initial_state() {
        let buffer: Vec<u8> = Vec::new();
        let writer = CountingWriter::new(buffer);
        assert_eq!(writer.bytes_written(), 0);
        assert!(writer.inner().is_empty());
    }

    // --- PresentStats edge cases ---

    #[test]
    fn present_stats_debug_clone_eq() {
        let a = PresentStats::new(100, 10, 2, Duration::from_micros(50));
        let dbg = format!("{:?}", a);
        assert!(dbg.contains("PresentStats"), "Debug: {dbg}");
        let cloned = a.clone();
        assert_eq!(a, cloned);
        let b = PresentStats::new(200, 10, 2, Duration::from_micros(50));
        assert_ne!(a, b);
    }

    #[test]
    fn present_stats_log_noop() {
        let stats = PresentStats::default();
        stats.log(); // Should not panic (noop without tracing)
    }

    #[test]
    fn present_stats_large_values() {
        let stats = PresentStats::new(u64::MAX, usize::MAX, usize::MAX, Duration::MAX);
        assert_eq!(stats.bytes_emitted, u64::MAX);
        assert_eq!(stats.cells_changed, usize::MAX);
    }

    #[test]
    fn present_stats_bytes_per_cell_fractional() {
        let stats = PresentStats::new(10, 3, 1, Duration::ZERO);
        let bpc = stats.bytes_per_cell();
        assert!((bpc - 3.333333333).abs() < 0.001);
    }

    #[test]
    fn present_stats_bytes_per_run_fractional() {
        let stats = PresentStats::new(10, 5, 3, Duration::ZERO);
        let bpr = stats.bytes_per_run();
        assert!((bpr - 3.333333333).abs() < 0.001);
    }

    #[test]
    fn present_stats_within_budget_at_exact_boundary() {
        // Budget for 10 cells, 2 runs: 2*10 + 10*40 + 20 = 440
        let budget = expected_max_bytes(10, 2);
        assert_eq!(budget, 440);

        let at_boundary = PresentStats::new(440, 10, 2, Duration::ZERO);
        assert!(at_boundary.within_budget());

        let over_boundary = PresentStats::new(441, 10, 2, Duration::ZERO);
        assert!(!over_boundary.within_budget());
    }

    // --- Constants ---

    #[test]
    fn constants_values() {
        assert_eq!(BYTES_PER_CELL_MAX, 40);
        assert_eq!(SYNC_OVERHEAD, 20);
        assert_eq!(BYTES_PER_CURSOR_MOVE, 10);
    }

    // --- expected_max_bytes edge cases ---

    #[test]
    fn expected_max_bytes_many_runs_few_cells() {
        // 1 cell, 100 runs (pathological case)
        let budget = expected_max_bytes(1, 100);
        // 100*10 + 1*40 + 20 = 1060
        assert_eq!(budget, 1060);
    }

    #[test]
    fn expected_max_bytes_many_cells_one_run() {
        let budget = expected_max_bytes(1000, 1);
        // 1*10 + 1000*40 + 20 = 40030
        assert_eq!(budget, 40030);
    }

    // --- StatsCollector edge cases ---

    #[test]
    fn stats_collector_debug() {
        let collector = StatsCollector::start(5, 2);
        let dbg = format!("{:?}", collector);
        assert!(dbg.contains("StatsCollector"), "Debug: {dbg}");
    }

    #[test]
    fn stats_collector_zero_cells_runs() {
        let collector = StatsCollector::start(0, 0);
        let stats = collector.finish(0);
        assert_eq!(stats.cells_changed, 0);
        assert_eq!(stats.run_count, 0);
        assert_eq!(stats.bytes_emitted, 0);
        assert!(stats.within_budget()); // 0 <= SYNC_OVERHEAD
    }

    #[test]
    fn stats_collector_immediate_finish() {
        let collector = StatsCollector::start(1, 1);
        let stats = collector.finish(50);
        assert_eq!(stats.bytes_emitted, 50);
        // Duration should be very small (near zero)
        assert!(stats.duration < Duration::from_millis(100));
    }
}