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,
};
const AREA: Rect = Rect::new(0, 0, 120, 40);
const NARROW_AREA: Rect = Rect::new(0, 0, 80, 24);
const WIDE_AREA: Rect = Rect::new(0, 0, 180, 50);
const TINY_AREA: Rect = Rect::new(0, 0, 44, 12);
const DEFAULT_FRAMES: usize = 80;
const DEFAULT_HIGHLIGHT_FRAMES: usize = 3;
const DEFAULT_SUITE_FRAMES: usize = DEFAULT_FRAMES;
const DEFAULT_RUNS: usize = 3;
const DEFAULT_FILES: usize = 32;
const DEFAULT_LINES: usize = 128;
const SAMPLE_ROWS: usize = 5;
const SAMPLE_COLS: usize = 7;
const REPORT_DIM: Color = Color::Fixed(244);
const THEME_NAME: &str = "rustik-catppuccin-mocha";
const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json");
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);
}
#[derive(Clone, Copy, Debug)]
struct Args {
workload: Workload,
frames: FrameCount,
runs: usize,
files: usize,
lines: usize,
}
impl Args {
fn parse() -> Self {
Self::parse_from(std::env::args().skip(1))
}
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
}
}
#[derive(Clone, Copy, Debug)]
enum FrameCount {
Default,
Explicit(usize),
}
impl FrameCount {
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,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Workload {
WarmScroll,
Session,
Resize,
Sticky,
Highlight,
HighlightRequests,
WordDiff,
ManyFiles,
HugeFile,
LongLines,
All,
}
impl Workload {
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],
}
}
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",
}
}
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",
}
}
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(),
}
}
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(()),
}
}
}
#[derive(Clone, Copy, Debug)]
struct DiffShape {
files: usize,
lines: usize,
hunk_lines: usize,
profile: LineProfile,
}
#[derive(Clone, Copy, Debug)]
enum LineProfile {
Normal,
Tiny,
LongUnicode,
}
#[derive(Clone, Copy, Debug)]
struct BenchReport {
workload: Workload,
metric: RepeatStats,
checksum: usize,
}
#[derive(Clone, Copy, Debug)]
struct RepeatStats {
avg: f64,
stddev: f64,
}
#[derive(Clone, Copy, Debug)]
struct ReportWidths {
workload: usize,
metric: usize,
}
const METRIC_FORMAT: &str = "000000.0";
fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize {
args.next()
.and_then(|value| value.parse().ok())
.unwrap_or(fallback)
}
fn next_workload(args: &mut impl Iterator<Item = String>, fallback: Workload) -> Workload {
args.next()
.and_then(|value| value.parse().ok())
.unwrap_or(fallback)
}
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,
}
}
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"),
}
}
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)
}
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
})
}
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
})
}
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
})
}
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)
}
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;
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)
}
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)
}
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)
}
fn apply_resize(viewer: &mut DiffViewer, area: Rect) {
viewer.apply(DiffAction::Resize, area);
}
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)
}
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
}
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');
}
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)
),
}
}
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
}
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())
})
}
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)
}
}
}
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 {
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()),
}
}
}
fn flush_stdout() {
let _ = io::stdout().flush();
}
impl RepeatStats {
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(),
}
}
}
fn format_metric(value: f64, unit: &str) -> String {
format!("{value:.1} {unit}")
}