Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(project): encode keyboard events without a temporary payload

vedanthcdefb491c48b
diff --git a/crates/project/examples/keyboard-encoding-benchmark.rs b/crates/project/examples/keyboard-encoding-benchmark.rs
new file mode 100644
index 000000000..3a67d900e
--- /dev/null
+++ b/crates/project/examples/keyboard-encoding-benchmark.rs
@@ -0,0 +1,71 @@
+use cap_project::{KeyPressEvent, KeyboardEvents};
+use std::{
+ collections::hash_map::DefaultHasher,
+ error::Error,
+ hash::{Hash, Hasher},
+ hint::black_box,
+ time::Instant,
+};
+
+fn fixture(count: usize, unicode: bool) -> KeyboardEvents {
+ KeyboardEvents {
+ presses: (0..count)
+ .map(|index| KeyPressEvent {
+ key: if unicode {
+ ["a", "文字🖱", "Space", "LControl"][index % 4]
+ } else {
+ "a"
+ }
+ .into(),
+ key_code: "KeyA".into(),
+ time_ms: index as f64 * 50.25,
+ down: index % 2 == 0,
+ })
+ .collect(),
+ }
+}
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let mut arguments = std::env::args().skip(1);
+ let iterations: usize = arguments.next().unwrap_or_else(|| "10".into()).parse()?;
+ if iterations == 0 || arguments.next().is_some() {
+ return Err("expected one positive iteration count".into());
+ }
+ println!("case,events,unicode,sample,elapsed_ms,bytes,capacity,fingerprint");
+ for (case, (count, unicode)) in [
+ (0, false),
+ (1_000, false),
+ (1_000, true),
+ (72_000, false),
+ (72_000, true),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let events = fixture(count, unicode);
+ let expected = events.to_bytes()?;
+ let decoded = KeyboardEvents::from_bytes(&expected, std::path::Path::new("keyboard.bin"))?;
+ assert_eq!(decoded.presses, events.presses);
+ let mut hasher = DefaultHasher::new();
+ expected.hash(&mut hasher);
+ let fingerprint = hasher.finish();
+ for _ in 0..3 {
+ black_box(events.to_bytes()?);
+ }
+ for sample in 0..25 {
+ let started = Instant::now();
+ for _ in 0..iterations {
+ black_box(black_box(&events).to_bytes()?);
+ }
+ let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0 / iterations as f64;
+ let output = events.to_bytes()?;
+ assert_eq!(output, expected);
+ println!(
+ "{case},{count},{unicode},{sample},{elapsed_ms:.6},{},{},{fingerprint}",
+ output.len(),
+ output.capacity()
+ );
+ }
+ }
+ Ok(())
+}
diff --git a/crates/project/src/keyboard.rs b/crates/project/src/keyboard.rs
index 003a6d613..77baf8f31 100644
--- a/crates/project/src/keyboard.rs
+++ b/crates/project/src/keyboard.rs
@@ -61,9 +61,8 @@ impl KeyboardEvents {
pub fn to_bytes(&self) -> Result<Vec<u8>, String> {
let mut bytes = KEYBOARD_EVENTS_MAGIC.to_vec();
- let payload = bincode::serde::encode_to_vec(self, bincode::config::standard())
+ bincode::serde::encode_into_std_write(self, &mut bytes, bincode::config::standard())
.map_err(|e| format!("Failed to serialize keyboard events: {e}"))?;
- bytes.extend(payload);
Ok(bytes)
}
@@ -1166,6 +1165,52 @@ mod tests {
assert_eq!(segments[0].display_text, "⏎");
}
+ #[test]
+ fn keyboard_encoding_matches_the_original_payload_copy() {
+ for count in [0, 1, 250, 251, 65_535, 65_536] {
+ let events = KeyboardEvents {
+ presses: (0..count)
+ .map(|index| KeyPressEvent {
+ key: ["", "a", "文字🖱", "LControl"][index % 4].into(),
+ key_code: "KeyA".into(),
+ time_ms: [
+ f64::NEG_INFINITY,
+ -0.0,
+ f64::from_bits(0x7ff8_0000_0000_1234),
+ 1.25,
+ f64::INFINITY,
+ ][index % 5],
+ down: index % 2 == 0,
+ })
+ .collect(),
+ };
+ let mut expected = KEYBOARD_EVENTS_MAGIC.to_vec();
+ expected.extend(
+ bincode::serde::encode_to_vec(&events, bincode::config::standard()).unwrap(),
+ );
+ let actual = events.to_bytes().unwrap();
+ assert_eq!(actual, expected, "{count} events");
+ let decoded = KeyboardEvents::from_bytes(&actual, Path::new("keyboard.bin")).unwrap();
+ assert_eq!(decoded.presses.len(), events.presses.len());
+ for (decoded, source) in decoded.presses.iter().zip(&events.presses) {
+ assert_eq!(decoded.key, source.key);
+ assert_eq!(decoded.key_code, source.key_code);
+ assert_eq!(decoded.time_ms.to_bits(), source.time_ms.to_bits());
+ assert_eq!(decoded.down, source.down);
+ }
+ }
+ for length in [0, 1, 250, 251, 65_535, 65_536] {
+ let events = KeyboardEvents {
+ presses: vec![key_down(&"x".repeat(length), 1.25)],
+ };
+ let mut expected = KEYBOARD_EVENTS_MAGIC.to_vec();
+ expected.extend(
+ bincode::serde::encode_to_vec(&events, bincode::config::standard()).unwrap(),
+ );
+ assert_eq!(events.to_bytes().unwrap(), expected, "key length {length}");
+ }
+ }
+
#[test]
fn roundtrips_binary_keyboard_events() {
let events = KeyboardEvents {