Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/helm-bench/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,7 @@ harness = false
[[bench]]
name = "vim_objects"
harness = false

[[bench]]
name = "typing"
harness = false
210 changes: 210 additions & 0 deletions crates/helm-bench/benches/typing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
//! Typing group benchmarks for `helm-editor` (T-112), gated by the `bench`
//! CI job against `budgets.toml`. NF-1 gives a keypress 5 ms from input to
//! pixel, and deciding whether an edit joins the open undo step is on that
//! path. A decision that copied or read the text would show up here.

use std::hint::black_box;
use std::time::Duration;

use criterion::{Criterion, criterion_group, criterion_main};
use helm_editor::{
CommandRegistry, Dispatcher, Editor, Key, KeyEvent, KeySequence, Keystroke, Modifiers,
Selection, Selections, UndoGrouping, vscode,
};
use helm_text::{Buffer, BufferId, BufferSet, FileFormat, LineEndings, TextBuffer};

/// Number of cursors in the many-cursor benchmark.
const CURSORS: usize = 1000;

/// Size of the benchmark text: 10 MiB, cut down to a char boundary.
const TEXT_LEN: usize = 10 << 20;

/// The chars the typing benchmarks cycle through: ASCII, a space, and
/// chars of 4, 3 and 2 bytes.
const TYPED: &str = "helm 😀中é";

/// The time between two keys: well under `Editor::TYPING_PAUSE`, so no
/// pause ends a step.
const KEY_GAP: Duration = Duration::from_millis(10);

/// The same lines `benches/editor.rs` repeats: ASCII code mixed with é,
/// 中 and 😀, ending in both LF and CRLF.
const LINES: &str = concat!(
"fn main() {\n",
" let café = \"crème brûlée\";\r\n",
" // 中文注释: 编辑器\n",
" println!(\"{café} 😀 done\");\r\n",
" let emoji = ['😀', '中', 'é'];\n",
"}\r\n",
"\n",
);

/// The largest char boundary of `text` at or below `byte`.
fn floor_boundary(text: &str, mut byte: usize) -> usize {
while !text.is_char_boundary(byte) {
byte -= 1;
}
byte
}

/// 10 MiB of `LINES` repeated, cut at the last char boundary at or below
/// `TEXT_LEN`.
fn build_text() -> String {
let mut text = LINES.repeat(TEXT_LEN / LINES.len() + 1);
text.truncate(floor_boundary(&text, TEXT_LEN));
text
}

/// An editor on `id` with `selections`, under typing grouping.
fn typing_editor(id: BufferId, format: FileFormat, selections: &Selections) -> Editor {
let mut editor = Editor::new(id, format);
editor.set_selections(selections.clone());
editor.set_undo_grouping(UndoGrouping::Typing);
editor
}

/// One key event per key of `keys`, in `KeySequence` notation.
fn keys(keys: &str) -> Vec<KeyEvent> {
KeySequence::parse(keys)
.expect("valid keys")
.as_slice()
.iter()
.map(|&keystroke| KeyEvent::new(keystroke))
.collect()
}

/// One key event per char of `text`, each typing its char.
fn chars(text: &str) -> Vec<KeyEvent> {
text.chars()
.map(|c| KeyEvent::new(Keystroke::new(Key::Char(c), Modifiers::NONE)))
.collect()
}

fn typing(c: &mut Criterion) {
let text = build_text();
let mut set = BufferSet::new();
let id = set.add(Buffer::from(text.as_str()));
let format = FileFormat {
bom: false,
line_endings: LineEndings::count(&text),
};
let buffer = set.get(id).expect("just added");
// One cursor at the start of each of 1,000 `fn main() {` lines spread
// evenly across the text, as `benches/cursor.rs` places them.
let repeats = buffer.len_lines() / LINES.lines().count() - 1;
let starts: Vec<usize> = (0..CURSORS)
.map(|i| {
let line = i * repeats / CURSORS * LINES.lines().count();
let at = buffer.line_to_byte(line).expect("line in range");
assert_eq!(buffer.slice(at..at + 2).as_deref(), Ok("fn"));
at
})
.collect();
let selections = Selections::new(starts.iter().map(|&at| Selection::cursor(at)).collect(), 0)
.expect("non-empty, primary in range");
let middle = Selections::single(Selection::cursor(starts[CURSORS / 2]));
let typed: Vec<String> = TYPED.chars().map(String::from).collect();

let mut group = c.benchmark_group("typing");

// Each benchmark moves its own clock on by `KEY_GAP` per key, so every
// run of keys is one step, and the undo takes the whole run back. The
// next edit drops the redo entry, so every iteration starts from the
// same text and selections.
let mut now = Duration::ZERO;
let mut editor = typing_editor(id, format, &middle);
group.bench_function("type_100_chars_undo_10mb", |b| {
b.iter(|| {
for c in typed.iter().cycle().take(100) {
now += KEY_GAP;
editor.set_time(now);
black_box(
editor
.insert(&mut set, black_box(c))
.expect("buffer is in the set"),
);
}
black_box(editor.undo(&mut set).expect("nothing blocks the undo"));
})
});
assert_eq!(
editor.selections(),
&middle,
"type_100_chars_undo_10mb ends where it began"
);

let mut now = Duration::ZERO;
let mut editor = typing_editor(id, format, &selections);
group.bench_function("type_10_chars_undo_1000_cursors_10mb", |b| {
b.iter(|| {
for c in typed.iter().cycle().take(10) {
now += KEY_GAP;
editor.set_time(now);
black_box(
editor
.insert(&mut set, black_box(c))
.expect("buffer is in the set"),
);
}
black_box(editor.undo(&mut set).expect("nothing blocks the undo"));
})
});
assert_eq!(
editor.selections(),
&selections,
"type_10_chars_undo_1000_cursors_10mb ends where it began"
);

// `hello`, two Backspaces, `lo world`, Enter and `x`, Left, then `y`:
// five steps, which five `cmd-z`s take back.
let dispatcher = Dispatcher::new(CommandRegistry::with_all_commands(), vscode::keymap());
let mut state = dispatcher.key_state();
let mut events = chars("hello");
events.extend(keys("backspace backspace"));
events.extend(chars("lo world"));
events.extend(keys("enter"));
events.extend(chars("x"));
events.extend(keys("left"));
events.extend(chars("y"));
let undo = keys("cmd-z");
let mut now = Duration::ZERO;
let mut editor = Editor::new(id, format);
editor.set_selections(middle.clone());
group.bench_function("vscode_session_undo_10mb", |b| {
b.iter(|| {
for event in &events {
now += KEY_GAP;
editor.set_time(now);
black_box(
dispatcher
.dispatch(&mut state, black_box(event), &[], &mut editor, &mut set)
.expect("the command runs"),
);
}
for _ in 0..5 {
now += KEY_GAP;
editor.set_time(now);
black_box(
dispatcher
.dispatch(&mut state, black_box(&undo[0]), &[], &mut editor, &mut set)
.expect("the command runs"),
);
}
})
});
assert_eq!(
editor.selections(),
&middle,
"vscode_session_undo_10mb ends where it began"
);
assert_eq!(
set.get(id).expect("in the set").to_string(),
text,
"the typing benchmarks end with the text they started with"
);

group.finish();
}

criterion_group!(benches, typing);
criterion_main!(benches);
2 changes: 2 additions & 0 deletions crates/helm-editor/src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,7 @@ impl Dispatcher {
) -> Result<Resolution, CommandError> {
let resolution = self.resolve(state, event, contexts);
if let Resolution::Run(invocation) = &resolution {
editor.set_undo_grouping(self.keymap.undo_grouping());
self.registry.run(invocation, editor, set)?;
}
Ok(resolution)
Expand Down Expand Up @@ -524,6 +525,7 @@ impl Dispatcher {
let resolution = self.resolve(state, event, contexts);
let requests = match &resolution {
Resolution::Run(invocation) => {
editor.set_undo_grouping(self.keymap.undo_grouping());
self.registry.run_in(invocation, editor, set, session)?
}
_ => Vec::new(),
Expand Down
Loading
Loading