rustik-diff 0.3.0

Pure diff viewer and Git diff pager for Rustik.
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! Render benchmarks for `rustik-diff`.
//!
//! The benchmark decodes deterministic unified diffs once, then exercises
//! render, scroll, resize, focus, highlight-request, and highlight-refresh paths.

use std::hint::black_box;
use std::io::{self, Write as _};
use std::str::FromStr;
use std::time::{Duration, Instant};

use rustik_diff::{
    BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer,
    HighlightRequest, HighlightResult,
};
use rustik_highlight as syntax;
use rustik_tui::{
    Buffer, Color, Constraint, Label, Line, Rect, Scroll, Style, Table, TableOptions,
};

/// Fixed terminal-sized render area.
const AREA: Rect = Rect::new(0, 0, 120, 40);
/// Narrow terminal area used by resize-heavy scenarios.
const NARROW_AREA: Rect = Rect::new(0, 0, 80, 24);
/// Wide terminal area used by resize-heavy scenarios.
const WIDE_AREA: Rect = Rect::new(0, 0, 180, 50);
/// Tiny terminal area used to stress minimum-width rendering.
const TINY_AREA: Rect = Rect::new(0, 0, 44, 12);
/// Default frame count.
const DEFAULT_FRAMES: usize = 80;
/// Default frame count for expensive real syntax-highlight landing runs.
const DEFAULT_HIGHLIGHT_FRAMES: usize = 3;
/// Default frame count for each workload in the full suite.
const DEFAULT_SUITE_FRAMES: usize = DEFAULT_FRAMES;
/// Default number of independent timed runs per workload.
const DEFAULT_RUNS: usize = 3;
/// Default number of file sections in the generated diff.
const DEFAULT_FILES: usize = 32;
/// Default number of hunk lines per generated file.
const DEFAULT_LINES: usize = 128;
/// One row sample stride for the checksum.
const SAMPLE_ROWS: usize = 5;
/// One column sample stride for the checksum.
const SAMPLE_COLS: usize = 7;
/// Low-emphasis report text color.
const REPORT_DIM: Color = Color::Fixed(244);
/// Theme name used by the interactive pager.
const THEME_NAME: &str = "rustik-catppuccin-mocha";
/// Built-in syntax theme JSON used by the interactive pager.
const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json");

/// Runs the benchmark.
fn main() {
    let args = Args::parse();
    let workloads = args.workload.expanded();
    let report_widths = ReportWidths::new(&workloads);
    let mut checksum = 0usize;

    for workload in workloads {
        let report = run_workload(workload, args);
        checksum ^= report.checksum.rotate_left(report.workload as u32);
        report_workload(&report, report_widths);
        black_box(report);
    }
    black_box(checksum);
}

/// Benchmark command-line arguments.
#[derive(Clone, Copy, Debug)]
struct Args {
    /// Workload to run.
    workload: Workload,
    /// Number of frames to render.
    frames: FrameCount,
    /// Number of independent timed runs per workload.
    runs: usize,
    /// Number of synthetic file sections.
    files: usize,
    /// Number of synthetic hunk lines per file.
    lines: usize,
}

impl Args {
    /// Parses benchmark arguments from the process environment.
    fn parse() -> Self {
        Self::parse_from(std::env::args().skip(1))
    }

    /// Parses benchmark arguments from an iterator.
    fn parse_from(args: impl IntoIterator<Item = String>) -> Self {
        let mut parsed = Self {
            workload: Workload::All,
            frames: FrameCount::Default,
            runs: DEFAULT_RUNS,
            files: DEFAULT_FILES,
            lines: DEFAULT_LINES,
        };
        let mut args = args.into_iter();

        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--workload" | "-w" => parsed.workload = next_workload(&mut args, parsed.workload),
                "--frames" => {
                    parsed.frames = FrameCount::Explicit(next_usize(&mut args, DEFAULT_FRAMES));
                }
                "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1),
                "--files" => parsed.files = next_usize(&mut args, parsed.files),
                "--lines" => parsed.lines = next_usize(&mut args, parsed.lines),
                "--help" | "-h" => {
                    println!(
                        "usage: cargo bench -p rustik-diff --bench render -- [--workload NAME] [--runs N] [--frames N] [--files N] [--lines N]"
                    );
                    std::process::exit(0);
                }
                value => {
                    if let Ok(value) = value.parse() {
                        parsed.frames = FrameCount::Explicit(value);
                    }
                }
            }
        }

        parsed
    }
}

/// Frame-count selection mode.
#[derive(Clone, Copy, Debug)]
enum FrameCount {
    /// Use workload-sensitive defaults.
    Default,
    /// Use the same explicit frame count for every selected workload.
    Explicit(usize),
}

impl FrameCount {
    /// Returns the concrete frame count for one workload.
    const fn for_workload(self, requested: Workload) -> usize {
        match (self, requested) {
            (Self::Default, Workload::Highlight) => DEFAULT_HIGHLIGHT_FRAMES,
            (Self::Default, Workload::All) => DEFAULT_SUITE_FRAMES,
            (Self::Default, _) => DEFAULT_FRAMES,
            (Self::Explicit(frames), _) => frames,
        }
    }
}

/// Named benchmark workload.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Workload {
    /// Original fixed-area, warm-cache, one-line scroll workload.
    WarmScroll,
    /// Mixed pager session with scrolling, navigation, and resize.
    Session,
    /// Width-changing render workload.
    Resize,
    /// Scrolling offsets concentrated around file boundaries.
    Sticky,
    /// Visible syntax-highlight landing workload.
    Highlight,
    /// Visible highlight request scheduling without drawing rows.
    HighlightRequests,
    /// Steady-state render of word-diff overlays on a warm highlight cache.
    WordDiff,
    /// Large file-count workload with short hunks.
    ManyFiles,
    /// Single huge file workload.
    HugeFile,
    /// Long and Unicode-heavy source line workload.
    LongLines,
    /// Runs every named workload.
    All,
}

impl Workload {
    /// Returns concrete workloads represented by this value.
    fn expanded(self) -> Vec<Self> {
        match self {
            Self::All => vec![
                Self::WarmScroll,
                Self::Session,
                Self::Resize,
                Self::Sticky,
                Self::Highlight,
                Self::HighlightRequests,
                Self::WordDiff,
                Self::ManyFiles,
                Self::HugeFile,
                Self::LongLines,
            ],
            workload => vec![workload],
        }
    }

    /// Returns the workload display name.
    const fn name(self) -> &'static str {
        match self {
            Self::WarmScroll => "warm-scroll",
            Self::Session => "session",
            Self::Resize => "resize",
            Self::Sticky => "sticky",
            Self::Highlight => "highlight",
            Self::HighlightRequests => "highlight-requests",
            Self::WordDiff => "word-diff",
            Self::ManyFiles => "many-files",
            Self::HugeFile => "huge-file",
            Self::LongLines => "long-lines",
            Self::All => "all",
        }
    }

    /// Returns the report unit measured by the workload.
    const fn metric_unit(self) -> &'static str {
        match self {
            Self::HighlightRequests => "tps",
            Self::Highlight => "ms/land",
            Self::WarmScroll
            | Self::Session
            | Self::Resize
            | Self::Sticky
            | Self::WordDiff
            | Self::ManyFiles
            | Self::HugeFile
            | Self::LongLines
            | Self::All => "fps",
        }
    }

    /// Converts an elapsed workload run into the reported metric.
    fn metric_value(self, elapsed: Duration, frames: usize) -> f64 {
        let frames = frames.max(1);
        match self {
            Self::Highlight => elapsed.as_secs_f64() * 1_000.0 / frames as f64,
            _ => frames as f64 / elapsed.as_secs_f64(),
        }
    }

    /// Returns the synthetic document shape for the workload.
    fn document_shape(self, args: Args) -> DiffShape {
        match self {
            Self::ManyFiles => DiffShape {
                files: args.files.max(1_024),
                lines: 12,
                hunk_lines: 6,
                profile: LineProfile::Tiny,
            },
            Self::HugeFile => DiffShape {
                files: 1,
                lines: args.lines.max(16_384),
                hunk_lines: 256,
                profile: LineProfile::Normal,
            },
            Self::LongLines => DiffShape {
                files: args.files,
                lines: args.lines,
                hunk_lines: 64,
                profile: LineProfile::LongUnicode,
            },
            Self::Highlight => {
                let lines = args.lines.max(16_384);
                DiffShape {
                    files: 1,
                    lines,
                    hunk_lines: lines,
                    profile: LineProfile::Normal,
                }
            }
            Self::Sticky => DiffShape {
                files: args.files.max(256),
                lines: 32,
                hunk_lines: 16,
                profile: LineProfile::Normal,
            },
            Self::Session
            | Self::Resize
            | Self::HighlightRequests
            | Self::WordDiff
            | Self::WarmScroll
            | Self::All => DiffShape {
                files: args.files,
                lines: args.lines,
                hunk_lines: 64,
                profile: LineProfile::Normal,
            },
        }
    }
}

impl FromStr for Workload {
    type Err = ();

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "warm-scroll" | "plain" | "scroll" => Ok(Self::WarmScroll),
            "session" => Ok(Self::Session),
            "resize" => Ok(Self::Resize),
            "sticky" | "sticky-boundaries" => Ok(Self::Sticky),
            "highlight" | "highlights" => Ok(Self::Highlight),
            "highlight-requests" | "requests" => Ok(Self::HighlightRequests),
            "word-diff" | "worddiff" => Ok(Self::WordDiff),
            "many-files" => Ok(Self::ManyFiles),
            "huge-file" => Ok(Self::HugeFile),
            "long-lines" => Ok(Self::LongLines),
            "all" => Ok(Self::All),
            _ => Err(()),
        }
    }
}

/// Shape of a generated diff document.
#[derive(Clone, Copy, Debug)]
struct DiffShape {
    /// Number of files to generate.
    files: usize,
    /// Number of source rows to generate per file.
    lines: usize,
    /// Maximum number of rows per hunk.
    hunk_lines: usize,
    /// Source-line content profile.
    profile: LineProfile,
}

/// Source-line text profile.
#[derive(Clone, Copy, Debug)]
enum LineProfile {
    /// Short Rust-like lines.
    Normal,
    /// Very small hunks for many-file workloads.
    Tiny,
    /// Wide rows with Unicode graphemes.
    LongUnicode,
}

/// Result from one workload run.
#[derive(Clone, Copy, Debug)]
struct BenchReport {
    /// Workload that produced the report.
    workload: Workload,
    /// Workload metric statistics across independent runs.
    metric: RepeatStats,
    /// Combined deterministic render checksum across independent runs.
    checksum: usize,
}

/// Summary statistics for repeated benchmark runs.
#[derive(Clone, Copy, Debug)]
struct RepeatStats {
    /// Average reported workload value.
    avg: f64,
    /// Reported workload value standard deviation.
    stddev: f64,
}

/// Report column widths derived before workloads run.
#[derive(Clone, Copy, Debug)]
struct ReportWidths {
    /// Widest selected workload name.
    workload: usize,
    /// Width reserved for formatted workload metrics.
    metric: usize,
}

/// Widest expected workload-metric value used to keep streaming rows aligned.
const METRIC_FORMAT: &str = "000000.0";

/// Parses the next argument as a `usize`.
fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize {
    args.next()
        .and_then(|value| value.parse().ok())
        .unwrap_or(fallback)
}

/// Parses the next argument as a workload.
fn next_workload(args: &mut impl Iterator<Item = String>, fallback: Workload) -> Workload {
    args.next()
        .and_then(|value| value.parse().ok())
        .unwrap_or(fallback)
}

/// Runs one named benchmark workload.
fn run_workload(workload: Workload, args: Args) -> BenchReport {
    let frames = args.frames.for_workload(workload);
    let shape = workload.document_shape(args);
    let input = synthetic_diff(shape);
    let document = match DiffDocument::decode_str(&input) {
        Ok(document) => document,
        Err(error) => {
            eprintln!("failed to decode generated benchmark diff: {error}");
            std::process::exit(1);
        }
    };
    let rows = rustik_tui::Widget::size(
        &DiffViewer::new(document.clone(), DiffOptions::default()),
        Constraint::UNBOUNDED,
    )
    .rows;
    let mut metrics = Vec::with_capacity(args.runs);
    let mut checksum = rows;

    for run in 0..args.runs {
        let (run_elapsed, run_checksum) = run_once(workload, document.clone(), frames);
        metrics.push(workload.metric_value(run_elapsed, frames));
        checksum ^= run_checksum.rotate_left((run % usize::BITS as usize) as u32);
    }

    BenchReport {
        workload,
        metric: RepeatStats::from_values(&metrics),
        checksum,
    }
}

/// Runs one independent timed pass for a workload.
fn run_once(workload: Workload, document: DiffDocument, frames: usize) -> (Duration, usize) {
    match workload {
        Workload::WarmScroll => run_warm_scroll(document, frames),
        Workload::Session => run_session(document, frames),
        Workload::Resize => run_resize(document, frames),
        Workload::Sticky => run_sticky(document, frames),
        Workload::Highlight => run_highlight(document, frames),
        Workload::HighlightRequests => run_highlight_requests(document, frames),
        Workload::WordDiff => run_word_diff(document, frames),
        Workload::ManyFiles => run_session(document, frames),
        Workload::HugeFile => run_sticky(document, frames),
        Workload::LongLines => run_resize(document, frames),
        Workload::All => unreachable!("run_once: all is expanded before dispatch"),
    }
}

/// Renders a fixed-area warm-cache scrolling workload.
fn run_warm_scroll(document: DiffDocument, frames: usize) -> (Duration, usize) {
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
    let mut buffer = Buffer::empty(AREA);
    let start = Instant::now();
    let mut checksum = 0usize;

    for frame in 0..frames {
        buffer.clear();
        viewer.render(AREA, &mut buffer);
        checksum ^= sample_buffer(&buffer, frame);
        viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA);
        buffer.reset_dirty();
    }

    (start.elapsed(), checksum)
}

/// Renders a mixed pager session.
fn run_session(document: DiffDocument, frames: usize) -> (Duration, usize) {
    let areas = [AREA, AREA, WIDE_AREA, AREA, NARROW_AREA, AREA];
    run_scripted(document, frames, |viewer, frame| {
        let area = areas[frame % areas.len()];
        match frame % 24 {
            0 => apply_resize(viewer, area),
            1..=6 => {
                viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), area);
            }
            7 => {
                viewer.apply(
                    DiffAction::Scroll(Scroll::Lines((area.rows / 2) as isize)),
                    area,
                );
            }
            8 => {
                viewer.apply(DiffAction::NextHunk, area);
            }
            9 => {
                viewer.apply(DiffAction::FocusNext, area);
            }
            10 => {
                viewer.apply(DiffAction::FocusPrevious, area);
            }
            11 => {
                viewer.apply(DiffAction::NextHunk, area);
            }
            12 => {
                viewer.apply(DiffAction::PreviousHunk, area);
            }
            _ => {
                viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), area);
            }
        }
        area
    })
}

/// Renders while invalidating width-dependent caches with resize events.
fn run_resize(document: DiffDocument, frames: usize) -> (Duration, usize) {
    let areas = [AREA, WIDE_AREA, NARROW_AREA, TINY_AREA, AREA];
    run_scripted(document, frames, |viewer, frame| {
        let area = areas[frame % areas.len()];
        apply_resize(viewer, area);
        viewer.apply(
            DiffAction::Scroll(Scroll::Lines((frame % 7) as isize - 3)),
            area,
        );
        area
    })
}

/// Renders offsets concentrated around sticky file-header transitions.
fn run_sticky(document: DiffDocument, frames: usize) -> (Duration, usize) {
    run_scripted(document, frames, |viewer, frame| {
        if frame % 16 == 0 {
            viewer.apply(DiffAction::FocusNext, AREA);
        } else if frame % 16 < 8 {
            viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA);
        } else {
            viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), AREA);
        }
        AREA
    })
}

/// Renders until visible rows have real syntax highlights applied.
fn run_highlight(document: DiffDocument, frames: usize) -> (Duration, usize) {
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
    let mut buffer = Buffer::empty(AREA);
    let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows;
    viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA);
    let start = Instant::now();
    let raw_theme = match THEME.parse::<syntax::RawTheme>() {
        Ok(theme) => theme,
        Err(error) => {
            eprintln!("failed to parse benchmark theme: {error:?}");
            std::process::exit(1);
        }
    };
    let mut raw = match syntax::syntaxes::RUST.parse::<syntax::RawGrammar>() {
        Ok(raw) => raw,
        Err(error) => {
            eprintln!("failed to parse benchmark grammar: {error:?}");
            std::process::exit(1);
        }
    };
    if !raw
        .file_types
        .iter()
        .any(|existing| existing.eq_ignore_ascii_case("rs"))
    {
        raw.file_types.push("rs".to_owned());
    }
    let rust_grammar = match syntax::Grammar::compile_with(&raw, &[]) {
        Ok(grammar) => grammar,
        Err(error) => {
            eprintln!("failed to compile benchmark grammar: {error:?}");
            std::process::exit(1);
        }
    };
    let mut registry = syntax::Registry::default();
    registry.add_theme(syntax::Theme::compile(&raw_theme));
    registry.add_grammar(rust_grammar);
    let mut highlighter = BuiltinHighlighter::new(registry, THEME_NAME);
    let mut checksum = 0usize;

    for frame in 0..frames {
        buffer.clear();
        viewer.render(AREA, &mut buffer);
        checksum ^= sample_buffer(&buffer, frame);
        let requests = viewer.visible_highlight_requests(AREA);
        let results = highlighter.highlight_requests(requests);
        viewer.apply_highlights(results);
        buffer.clear();
        viewer.render(AREA, &mut buffer);
        checksum ^= sample_buffer(&buffer, frame.wrapping_add(frames));
        viewer.apply(
            DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)),
            AREA,
        );
        buffer.reset_dirty();
    }

    (start.elapsed(), checksum)
}

/// Renders cached word-diff overlays with a warm highlight cache.
///
/// Pre-applies synthetic highlight results for the rows the workload will
/// scroll across, then measures render+scroll cost on already-overlaid lines.
/// Because every `-/+` pair in `synthetic_diff` passes the word-diff similarity
/// gate, this isolates the cached-render fast path that
/// [`DiffViewer::apply_highlights`] now bakes the overlay into.
fn run_word_diff(document: DiffDocument, frames: usize) -> (Duration, usize) {
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
    let mut buffer = Buffer::empty(AREA);
    let span = AREA.rows.saturating_mul(2) as isize;

    // Walk forward across the scroll span so every row we'll visit gets a
    // highlight result. Then walk back to the start before timing begins.
    for _ in 0..span {
        let requests = viewer.highlight_requests(AREA);
        viewer.apply_highlights(requests.into_iter().map(highlight_result));
        viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA);
    }
    viewer.apply(DiffAction::Scroll(Scroll::Lines(-span)), AREA);

    let start = Instant::now();
    let mut checksum = 0usize;

    for frame in 0..frames {
        buffer.clear();
        viewer.render(AREA, &mut buffer);
        checksum ^= sample_buffer(&buffer, frame);
        let step = if (frame as isize / span) % 2 == 0 {
            1
        } else {
            -1
        };
        viewer.apply(DiffAction::Scroll(Scroll::Lines(step)), AREA);
        buffer.reset_dirty();
    }
    (start.elapsed(), checksum)
}

/// Schedules visible highlight requests without drawing rendered rows.
fn run_highlight_requests(document: DiffDocument, frames: usize) -> (Duration, usize) {
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
    let start = Instant::now();
    let mut checksum = 0usize;

    for frame in 0..frames {
        let requests = viewer.highlight_requests(AREA);
        checksum ^= sample_requests(&requests, frame);
        viewer.apply(
            DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)),
            AREA,
        );
    }

    (start.elapsed(), checksum)
}

/// Renders frames using a caller-provided action script.
fn run_scripted(
    document: DiffDocument,
    frames: usize,
    mut script: impl FnMut(&mut DiffViewer, usize) -> Rect,
) -> (Duration, usize) {
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
    let mut buffer = Buffer::empty(AREA);
    let start = Instant::now();
    let mut checksum = 0usize;

    for frame in 0..frames {
        let area = script(&mut viewer, frame);
        buffer.resize(area);
        buffer.clear();
        viewer.render(area, &mut buffer);
        checksum ^= sample_buffer(&buffer, frame);
        buffer.reset_dirty();
    }

    (start.elapsed(), checksum)
}

/// Applies resize handling for an area.
fn apply_resize(viewer: &mut DiffViewer, area: Rect) {
    viewer.apply(DiffAction::Resize, area);
}

/// Converts a highlight request into a deterministic synthetic result.
fn highlight_result(request: HighlightRequest) -> HighlightResult {
    let line = Line::new(
        Label::from(
            request
                .source
                .line(request.key.source_line)
                .unwrap_or_default(),
        )
        .fg(Color::Yellow),
    );
    HighlightResult::new(request, line)
}

/// Creates a deterministic Git-style unified diff.
fn synthetic_diff(shape: DiffShape) -> String {
    let mut diff = String::new();

    for file in 0..shape.files {
        diff.push_str(&format!(
            "diff --git a/src/file_{file:04}.rs b/src/file_{file:04}.rs\n"
        ));
        diff.push_str(&format!("index {file:040x}..{:040x} 100644\n", file + 1));
        diff.push_str(&format!("--- a/src/file_{file:04}.rs\n"));
        diff.push_str(&format!("+++ b/src/file_{file:04}.rs\n"));

        let mut old_start = 1usize;
        let mut new_start = 1usize;
        for hunk_start in (0..shape.lines).step_by(shape.hunk_lines.max(1)) {
            let hunk_lines = shape.hunk_lines.min(shape.lines - hunk_start);
            let hunk_range = hunk_start..hunk_start + hunk_lines;
            let additions = hunk_range.clone().filter(|line| line % 5 == 1).count();
            let deletions = hunk_range.filter(|line| line % 5 == 0).count();
            let context = hunk_lines.saturating_sub(additions + deletions);
            let old_lines = deletions + context;
            let new_lines = additions + context;

            diff.push_str(&format!(
                "@@ -{old_start},{old_lines} +{new_start},{new_lines} @@ fn file_{file:04}_hunk_{hunk_start:04}()\n"
            ));

            for line in hunk_start..hunk_start + hunk_lines {
                push_diff_line(&mut diff, shape.profile, file, line);
            }

            old_start += old_lines + 8;
            new_start += new_lines + 8;
        }
    }

    diff
}

/// Adds one generated diff line.
fn push_diff_line(diff: &mut String, profile: LineProfile, file: usize, line: usize) {
    let prefix = match line % 5 {
        0 => '-',
        1 => '+',
        _ => ' ',
    };
    diff.push(prefix);
    diff.push_str(&line_text(profile, file, line));
    diff.push('\n');
}

/// Returns one generated source line.
fn line_text(profile: LineProfile, file: usize, line: usize) -> String {
    match profile {
        LineProfile::Normal => match line % 5 {
            0 => format!("let old_value_{line:04} = compute({file}, {line});"),
            1 => format!("let new_value_{line:04} = compute_fast({file}, {line});"),
            _ => format!("let stable_value_{line:04} = keep({file}, {line});"),
        },
        LineProfile::Tiny => format!("v{file}_{line}();"),
        LineProfile::LongUnicode => format!(
            "let sample_{line:04} = \"file={file} row={line} λ ❤️ {}\";",
            "payload_segment::".repeat(line % 19 + 12)
        ),
    }
}

/// Samples a buffer for a deterministic checksum.
fn sample_buffer(buffer: &Buffer, frame: usize) -> usize {
    let area = buffer.area();
    let mut checksum = frame;

    for row in (0..area.rows).step_by(SAMPLE_ROWS) {
        for col in (0..area.cols).step_by(SAMPLE_COLS) {
            if let Some(cell) = buffer.get(area.x + col, area.y + row) {
                checksum = checksum.wrapping_mul(16_777_619) ^ cell.glyph().len();
                checksum ^= color_id(cell.style().fg_color());
                checksum ^= color_id(cell.style().bg_color()).rotate_left(7);
            }
        }
    }

    checksum
}

/// Samples highlight requests for a deterministic checksum.
fn sample_requests(requests: &[HighlightRequest], frame: usize) -> usize {
    requests
        .iter()
        .fold(frame ^ requests.len(), |checksum, request| {
            checksum
                ^ request.key.text_hash as usize
                ^ request.source.text.len()
                ^ request
                    .path
                    .as_ref()
                    .map_or(0, |path| path.as_os_str().len())
        })
}

/// Returns a stable numeric id for a color.
fn color_id(color: Color) -> usize {
    match color {
        Color::Unset => 0,
        Color::Black => 1,
        Color::Red => 2,
        Color::Green => 3,
        Color::Yellow => 4,
        Color::Blue => 5,
        Color::Magenta => 6,
        Color::Cyan => 7,
        Color::White => 8,
        Color::Fixed(value) => 0x100 + usize::from(value),
        Color::RGB(r, g, b) => {
            0x1_0000 + (usize::from(r) << 16) + (usize::from(g) << 8) + usize::from(b)
        }
    }
}

/// Prints one styled workload report line.
fn report_workload(report: &BenchReport, widths: ReportWidths) {
    let table = Table::new(TableOptions {
        spacing: 3,
        ..TableOptions::default()
    })
    .row([
        Label::from("x".repeat(widths.workload)),
        Label::from("0".repeat(widths.metric)),
        Label::from(format!("±{}", "0".repeat(widths.metric))),
    ])
    .row([
        Label::new(report.workload.name()).style(Style::default().bold()),
        Label::from(format_metric(
            report.metric.avg,
            report.workload.metric_unit(),
        ))
        .fg(Color::White),
        Label::from(format!("±{:.1}", report.metric.stddev)).fg(REPORT_DIM),
    ]);

    if let Some(line) = table.lines(Constraint::UNBOUNDED).get(1) {
        println!("{}", line.styled());
    }
    flush_stdout();
}

impl ReportWidths {
    /// Computes report column widths for a selected workload set.
    fn new(workloads: &[Workload]) -> Self {
        Self {
            workload: workloads
                .iter()
                .map(|workload| workload.name().len())
                .max()
                .unwrap_or_default(),
            metric: workloads
                .iter()
                .map(|workload| METRIC_FORMAT.len() + 1 + workload.metric_unit().len())
                .max()
                .unwrap_or(METRIC_FORMAT.len() + 1 + "fps".len()),
        }
    }
}

/// Flushes benchmark output after an incremental report.
fn flush_stdout() {
    let _ = io::stdout().flush();
}

impl RepeatStats {
    /// Computes statistics from repeated numeric values.
    fn from_values(values: &[f64]) -> Self {
        let count = values.len() as f64;
        let avg = values.iter().sum::<f64>() / count;
        let variance = values
            .iter()
            .map(|value| {
                let delta = value - avg;
                delta * delta
            })
            .sum::<f64>()
            / count;

        Self {
            avg,
            stddev: variance.sqrt(),
        }
    }
}

/// Formats a workload report metric.
fn format_metric(value: f64, unit: &str) -> String {
    format!("{value:.1} {unit}")
}