.cargo/
crates/
brain/
diff/
benches/
highlight.rs
11.3 KiB
render.rs
28.7 KiB
src/
tests/
Cargo.toml
867 B
README.md
696 B
files/
highlight/
repo/
signals/
tui/
tui-core/
tui-termion/
tui-widgets/
scripts/
src/
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
crates/diff/benches/highlight.rs
raw
| 1 | //! Highlight pipeline benchmarks for `rustik-diff`. |
| 2 | //! |
| 3 | //! The benchmark mirrors the interactive pager's slow path more closely than |
| 4 | //! the render benchmark. It times built-in grammar and theme setup, whole-file |
| 5 | //! source indexing, request collection, and the final highlight, apply, and |
| 6 | //! render pass. |
| 7 | //! |
| 8 | //! Run with `cargo bench -p rustik-diff --bench highlight`. |
| 9 | |
| 10 | use std::convert::Infallible; |
| 11 | use std::hint::black_box; |
| 12 | use std::io::{self, Write as _}; |
| 13 | use std::time::{Duration, Instant}; |
| 14 | |
| 15 | use rustik_diff::{BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer}; |
| 16 | use rustik_highlight as syntax; |
| 17 | use rustik_tui::{Buffer, Color, Constraint, Label, Rect, Scroll, Style, Table, TableOptions}; |
| 18 | |
| 19 | /// Fixed terminal-sized render area. |
| 20 | const AREA: Rect = Rect::new(0, 0, 120, 40); |
| 21 | /// Default source line number targeted by the generated patch. |
| 22 | const DEFAULT_LINES: usize = 100_000; |
| 23 | /// Default number of independent timed runs. |
| 24 | const DEFAULT_RUNS: usize = 3; |
| 25 | /// Context rows in the sparse viewport document. |
| 26 | const SPARSE_CONTEXT_LINES: usize = 32; |
| 27 | /// Theme name used by the interactive pager. |
| 28 | const THEME_NAME: &str = "rustik-catppuccin-mocha"; |
| 29 | /// Built-in syntax theme JSON used by the interactive pager. |
| 30 | const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json"); |
| 31 | /// Low-emphasis report text color. |
| 32 | const REPORT_DIM: Color = Color::Fixed(244); |
| 33 | /// Widest expected duration value used to keep report rows aligned. |
| 34 | const DURATION_FORMAT: &str = "000000.0 ms"; |
| 35 | |
| 36 | /// Runs the benchmark. |
| 37 | fn main() { |
| 38 | let args = Args::parse(); |
| 39 | let sparse_patch = synthetic_context_diff("src/slow.rs", args.lines, SPARSE_CONTEXT_LINES); |
| 40 | let sparse_document = decode_patch(&sparse_patch); |
| 41 | let old_source = synthetic_source(args.lines, SPARSE_CONTEXT_LINES, "old"); |
| 42 | let new_source = synthetic_source(args.lines, SPARSE_CONTEXT_LINES, "new"); |
| 43 | let widths = ReportWidths::new(); |
| 44 | let mut totals = StageDurations::default(); |
| 45 | let mut checksum = 0usize; |
| 46 | |
| 47 | for _ in 0..args.runs { |
| 48 | let report = run_once(&sparse_document, &old_source, &new_source); |
| 49 | totals += report.stages; |
| 50 | checksum ^= report.checksum; |
| 51 | } |
| 52 | let stats = totals.div(args.runs); |
| 53 | |
| 54 | report_stage("assets", stats.assets, widths); |
| 55 | report_stage("whole-source", stats.whole_source, widths); |
| 56 | report_stage("requests", stats.requests, widths); |
| 57 | report_stage("land", stats.land, widths); |
| 58 | io::stdout().flush().ok(); |
| 59 | |
| 60 | black_box(checksum); |
| 61 | } |
| 62 | |
| 63 | /// Benchmark command-line arguments. |
| 64 | #[derive(Clone, Copy, Debug)] |
| 65 | struct Args { |
| 66 | /// Source line number targeted by the generated patch. |
| 67 | lines: usize, |
| 68 | /// Number of independent timed runs. |
| 69 | runs: usize, |
| 70 | } |
| 71 | |
| 72 | impl Args { |
| 73 | /// Parses benchmark arguments from the process environment. |
| 74 | fn parse() -> Self { |
| 75 | let mut parsed = Self { |
| 76 | lines: DEFAULT_LINES, |
| 77 | runs: DEFAULT_RUNS, |
| 78 | }; |
| 79 | let mut args = std::env::args().skip(1); |
| 80 | |
| 81 | while let Some(arg) = args.next() { |
| 82 | match arg.as_str() { |
| 83 | "--lines" => parsed.lines = next_usize(&mut args, parsed.lines), |
| 84 | "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1), |
| 85 | "--help" | "-h" => { |
| 86 | println!( |
| 87 | "usage: cargo bench -p rustik-diff --bench highlight -- [--lines N] [--runs N]" |
| 88 | ); |
| 89 | std::process::exit(0); |
| 90 | } |
| 91 | _ => {} |
| 92 | } |
| 93 | } |
| 94 | parsed |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// Stage timings from one benchmark run. |
| 99 | #[derive(Clone, Copy, Debug, Default)] |
| 100 | struct StageDurations { |
| 101 | /// Built-in theme and grammar setup. |
| 102 | assets: Duration, |
| 103 | /// Whole-file source indexing and loading. |
| 104 | whole_source: Duration, |
| 105 | /// Visible highlight request collection. |
| 106 | requests: Duration, |
| 107 | /// Syntax highlight, cache apply, and highlighted render. |
| 108 | land: Duration, |
| 109 | } |
| 110 | |
| 111 | impl StageDurations { |
| 112 | /// Returns average stage timings over `count` runs. |
| 113 | fn div(self, count: usize) -> Self { |
| 114 | let count = count.max(1) as u32; |
| 115 | |
| 116 | Self { |
| 117 | assets: self.assets / count, |
| 118 | whole_source: self.whole_source / count, |
| 119 | requests: self.requests / count, |
| 120 | land: self.land / count, |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | impl std::ops::AddAssign for StageDurations { |
| 126 | fn add_assign(&mut self, rhs: Self) { |
| 127 | self.assets += rhs.assets; |
| 128 | self.whole_source += rhs.whole_source; |
| 129 | self.requests += rhs.requests; |
| 130 | self.land += rhs.land; |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /// Result from one benchmark run. |
| 135 | #[derive(Clone, Copy, Debug)] |
| 136 | struct BenchReport { |
| 137 | /// Timed stage durations. |
| 138 | stages: StageDurations, |
| 139 | /// Deterministic checksum of the produced work. |
| 140 | checksum: usize, |
| 141 | } |
| 142 | |
| 143 | /// Report column widths. |
| 144 | #[derive(Clone, Copy, Debug)] |
| 145 | struct ReportWidths { |
| 146 | /// Width reserved for stage names. |
| 147 | stage: usize, |
| 148 | /// Width reserved for formatted durations. |
| 149 | duration: usize, |
| 150 | } |
| 151 | |
| 152 | impl ReportWidths { |
| 153 | /// Computes report column widths. |
| 154 | fn new() -> Self { |
| 155 | Self { |
| 156 | stage: "whole-source".len(), |
| 157 | duration: DURATION_FORMAT.len(), |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// Parses the next argument as a `usize`. |
| 163 | fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize { |
| 164 | args.next() |
| 165 | .and_then(|value| value.parse().ok()) |
| 166 | .unwrap_or(fallback) |
| 167 | } |
| 168 | |
| 169 | /// Runs one timed highlight pipeline pass. |
| 170 | fn run_once(sparse_document: &DiffDocument, old_source: &str, new_source: &str) -> BenchReport { |
| 171 | let mut stages = StageDurations::default(); |
| 172 | let mut checksum = 0usize; |
| 173 | |
| 174 | let start = Instant::now(); |
| 175 | let mut highlighter = build_highlighter(); |
| 176 | stages.assets = start.elapsed(); |
| 177 | |
| 178 | let old_oid = sparse_document.files[0].header.old_oid.unwrap(); |
| 179 | let mut viewer = DiffViewer::new(sparse_document.clone(), DiffOptions::default()); |
| 180 | let start = Instant::now(); |
| 181 | viewer |
| 182 | .load_file_sources(|oid| { |
| 183 | let source = if oid == old_oid { |
| 184 | old_source |
| 185 | } else { |
| 186 | new_source |
| 187 | }; |
| 188 | Ok::<_, Infallible>(source.as_bytes().to_vec()) |
| 189 | }) |
| 190 | .unwrap(); |
| 191 | stages.whole_source = start.elapsed(); |
| 192 | |
| 193 | let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows; |
| 194 | viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA); |
| 195 | |
| 196 | let start = Instant::now(); |
| 197 | let requests = viewer.highlight_requests(AREA); |
| 198 | stages.requests = start.elapsed(); |
| 199 | |
| 200 | let start = Instant::now(); |
| 201 | let results = highlighter.highlight_requests(requests); |
| 202 | |
| 203 | checksum ^= results.len(); |
| 204 | viewer.apply_highlights(results); |
| 205 | |
| 206 | let mut buffer = Buffer::empty(AREA); |
| 207 | viewer.render(AREA, &mut buffer); |
| 208 | checksum ^= buffer.area().rows ^ buffer.area().cols; |
| 209 | stages.land = start.elapsed(); |
| 210 | |
| 211 | BenchReport { stages, checksum } |
| 212 | } |
| 213 | |
| 214 | /// Creates a full source whose visible hunk matches the generated sparse diff. |
| 215 | fn synthetic_source(lines: usize, context_lines: usize, changed_value: &str) -> String { |
| 216 | let changed = lines.max(1).div_ceil(2); |
| 217 | let before = context_lines.min(changed.saturating_sub(1)); |
| 218 | let after = context_lines.min(lines.saturating_sub(changed)); |
| 219 | let start = changed - before; |
| 220 | let end = changed + after; |
| 221 | let mut source = String::new(); |
| 222 | |
| 223 | for line in 1..=lines { |
| 224 | if (start..=end).contains(&line) { |
| 225 | let value = if line == changed { |
| 226 | changed_value |
| 227 | } else { |
| 228 | "same" |
| 229 | }; |
| 230 | push_source_line(&mut source, line, value); |
| 231 | } else { |
| 232 | source.push_str("x\n"); |
| 233 | } |
| 234 | } |
| 235 | source |
| 236 | } |
| 237 | |
| 238 | /// Builds a highlighter for the generated Rust source file. |
| 239 | fn build_highlighter() -> BuiltinHighlighter { |
| 240 | let raw_theme = match THEME.parse::<syntax::RawTheme>() { |
| 241 | Ok(theme) => theme, |
| 242 | Err(error) => { |
| 243 | eprintln!("failed to parse benchmark theme: {error:?}"); |
| 244 | std::process::exit(1); |
| 245 | } |
| 246 | }; |
| 247 | let mut registry = syntax::Registry::default(); |
| 248 | |
| 249 | registry.add_theme(syntax::Theme::compile(&raw_theme)); |
| 250 | let mut raw = match syntax::syntaxes::RUST.parse::<syntax::RawGrammar>() { |
| 251 | Ok(raw) => raw, |
| 252 | Err(error) => { |
| 253 | eprintln!("failed to parse benchmark grammar: {error:?}"); |
| 254 | std::process::exit(1); |
| 255 | } |
| 256 | }; |
| 257 | if !raw |
| 258 | .file_types |
| 259 | .iter() |
| 260 | .any(|existing| existing.eq_ignore_ascii_case("rs")) |
| 261 | { |
| 262 | raw.file_types.push("rs".to_owned()); |
| 263 | } |
| 264 | let grammar = match syntax::Grammar::compile_with(&raw, &[]) { |
| 265 | Ok(grammar) => grammar, |
| 266 | Err(error) => { |
| 267 | eprintln!("failed to compile benchmark grammar: {error:?}"); |
| 268 | std::process::exit(1); |
| 269 | } |
| 270 | }; |
| 271 | registry.add_grammar(grammar); |
| 272 | BuiltinHighlighter::new(registry, THEME_NAME) |
| 273 | } |
| 274 | |
| 275 | /// Decodes a synthetic patch or exits with a benchmark setup error. |
| 276 | fn decode_patch(patch: &str) -> DiffDocument { |
| 277 | match DiffDocument::decode_str(patch) { |
| 278 | Ok(document) => document, |
| 279 | Err(error) => { |
| 280 | eprintln!("failed to decode generated benchmark diff: {error}"); |
| 281 | std::process::exit(1); |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /// Creates a deterministic Git-style unified diff for one centered file hunk. |
| 287 | fn synthetic_context_diff(path: &str, lines: usize, context_lines: usize) -> String { |
| 288 | let mut diff = String::new(); |
| 289 | |
| 290 | diff.push_str(&format!("diff --git a/{path} b/{path}\n")); |
| 291 | diff.push_str("index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n"); |
| 292 | diff.push_str(&format!("--- a/{path}\n")); |
| 293 | diff.push_str(&format!("+++ b/{path}\n")); |
| 294 | |
| 295 | let changed = lines.max(1).div_ceil(2); |
| 296 | let before = context_lines.min(changed.saturating_sub(1)); |
| 297 | let after = context_lines.min(lines.saturating_sub(changed)); |
| 298 | let start = changed - before; |
| 299 | let old_lines = before + 1 + after; |
| 300 | let new_lines = old_lines; |
| 301 | |
| 302 | diff.push_str(&format!( |
| 303 | "@@ -{start},{old_lines} +{start},{new_lines} @@ fn hunk_{changed:06}()\n" |
| 304 | )); |
| 305 | |
| 306 | for line in start..changed { |
| 307 | push_context_line(&mut diff, line); |
| 308 | } |
| 309 | diff.push('-'); |
| 310 | push_source_line(&mut diff, changed, "old"); |
| 311 | diff.push('+'); |
| 312 | push_source_line(&mut diff, changed, "new"); |
| 313 | for line in changed + 1..=changed + after { |
| 314 | push_context_line(&mut diff, line); |
| 315 | } |
| 316 | |
| 317 | diff |
| 318 | } |
| 319 | |
| 320 | /// Adds one generated context line. |
| 321 | fn push_context_line(diff: &mut String, line: usize) { |
| 322 | diff.push(' '); |
| 323 | push_source_line(diff, line, "same"); |
| 324 | } |
| 325 | |
| 326 | /// Adds one generated source line after the diff prefix. |
| 327 | fn push_source_line(diff: &mut String, line: usize, value: &str) { |
| 328 | diff.push_str(&format!("let value_{line:06} = compute_{value}({line});")); |
| 329 | diff.push('\n'); |
| 330 | } |
| 331 | |
| 332 | /// Prints one styled stage report line. |
| 333 | fn report_stage(stage: &str, duration: Duration, widths: ReportWidths) { |
| 334 | let table = Table::new(TableOptions { |
| 335 | spacing: 3, |
| 336 | ..TableOptions::default() |
| 337 | }) |
| 338 | .row([ |
| 339 | Label::from("x".repeat(widths.stage)), |
| 340 | Label::from("0".repeat(widths.duration)), |
| 341 | ]) |
| 342 | .row([ |
| 343 | Label::new(stage).style(Style::default().bold()), |
| 344 | Label::from(format_duration(duration)).fg(REPORT_DIM), |
| 345 | ]); |
| 346 | |
| 347 | if let Some(line) = table.lines(Constraint::UNBOUNDED).get(1) { |
| 348 | println!("{}", line.styled()); |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | /// Formats a duration in milliseconds. |
| 353 | fn format_duration(duration: Duration) -> String { |
| 354 | format!("{:.1} ms", duration.as_secs_f64() * 1_000.0) |
| 355 | } |