Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! `report`: a unit's result as Markdown and an SVG card, for a pull request or a README.
//!
//! Every number comes from a run made for the report: `diff` for the recorded cases that
//! match, `bench` for the speedup, and the cases of functions the Rust module does not provide
//! for the fallback rate. The machine and its core count go next to the timing.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::Serialize;
use crate::bridge::Manifest;
use crate::harness::{self, BenchRow};
use crate::walk::Canonical;
pub const SCHEMA: &str = "rust-anything/report@1";
#[derive(Debug, Serialize)]
pub struct Card {
pub schema: &'static str,
/// When the report ran, UTC.
pub at: String,
/// The port version it ran on ([`crate::state::port_version`]).
pub port: String,
pub crate_name: String,
pub unit: String,
/// The language's display name; `language_id` is the id `map` prints.
pub language: String,
pub language_id: String,
pub functions: Vec<String>,
pub cases: usize,
/// Cases that match the original, the ones `known-diffs.jsonl` accepts included.
pub matched: usize,
/// Of `matched`, the cases the port answers differently and a person accepted as intended.
pub accepted: usize,
/// What the cases were compared under: `comparison: exact`, or the float tolerance, key order
/// and known differences that loosened it.
pub comparison: String,
/// What the card leans on besides a clean diff: a recording that is not verified, cases
/// accepted as known differences.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
/// Geometric mean of `original_ns / rust_ns` over the timed functions, call included.
pub speedup: f64,
pub bench: Vec<BenchRow>,
/// Recorded cases whose function the Rust module does not provide, so the original answers.
pub fallback_cases: usize,
/// `Some(true)` while `enable` has switched the unit on; `None` where `enable` does not apply.
pub enabled: Option<bool>,
/// The distinct differences still left, most cases first (at most five).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub differences: Vec<crate::mismatch::Group>,
/// What the bindings are for once the port is done (`bridge --end-state`).
pub end_state: Option<crate::bridge::EndState>,
/// The entries of `known-diffs.jsonl`: inputs the port is meant to answer differently.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub intended: Vec<Intended>,
/// Exports kept in the original language, with the reason.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub kept: Vec<crate::bridge::JsOnly>,
pub machine: String,
pub markdown: PathBuf,
pub svg: PathBuf,
}
/// One `known-diffs.jsonl` entry, as reviewers read it.
#[derive(Debug, Serialize)]
pub struct Intended {
pub function: String,
/// The recorded arguments, as JSON, or the class of inputs an entry with `when` covers.
pub args: String,
pub reason: String,
}
impl Card {
/// Every benched function was left out of the timing because its cases do not match, so the
/// card has no speed to claim.
fn nothing_timed(&self) -> bool {
self.bench.iter().all(|b| b.failing)
}
/// Cases that match with no accepted difference among them.
fn exact(&self) -> usize {
self.matched - self.accepted.min(self.matched)
}
pub fn fallback_rate(&self) -> f64 {
if self.cases == 0 {
0.0
} else {
self.fallback_cases as f64 / self.cases as f64
}
}
}
pub struct Options<'a> {
pub crate_dir: &'a Path,
pub out: Option<&'a Path>,
pub min_ms: u64,
pub node_args: &'a [String],
/// Resolve npm packages the original imports from this folder's `node_modules`, as `bench` does.
pub resolve_from: Option<&'a Path>,
}
pub fn report(opts: &Options) -> Result<Card> {
anyhow::ensure!(opts.min_ms > 0, "`--min-ms` must be at least 1");
let manifest = Manifest::load(opts.crate_dir)?;
let crate_dir = opts
.crate_dir
.canonical()
.with_context(|| format!("resolving {}", opts.crate_dir.display()))?;
let port = crate::state::port_version(&crate_dir);
let _lock = crate::fuzz::RecordingLock::take_recovered(&crate_dir)?;
// A card says what the recorded cases showed, so the recording has to be the one `record`
// wrote from this original: a card for a stale or edited recording would be a green number
// for a port nobody checked against it.
let verified = crate::recording::verify(
&crate_dir,
&manifest,
crate::recording::VerifyOptions::default(),
);
anyhow::ensure!(
verified.ok(),
"no report for a recording that cannot be trusted:\n{}",
verified.refusal()
);
if let Some(dir) = opts.resolve_from {
dir.canonical()
.with_context(|| format!("resolving {}", dir.display()))?;
}
harness::build(&crate_dir)?;
let diff = harness::diff(&harness::DiffOptions {
crate_dir: &crate_dir,
module: None,
ignore_key_order: false,
node_args: opts.node_args,
float_tolerance: None,
})?;
let bench = harness::bench(&harness::BenchOptions {
crate_dir: &crate_dir,
min_ms: opts.min_ms,
resolve_from: opts.resolve_from,
node_args: opts.node_args,
})?;
let verdict = harness::verdict(&bench, manifest.language, &crate_dir);
let per_function = cases_per_function(&crate_dir);
let comparison = crate::recording::Loosening::read(&crate_dir);
let mut notes = verified.notes.clone();
if diff.accepted > 0 {
notes.push(format!(
"{} of {} cases are accepted as known differences ({}), not matches",
diff.accepted,
diff.total,
crate::recording::KNOWN_DIFFS
));
}
let fallback_cases = diff
.missing
.iter()
.map(|f| per_function.get(f).copied().unwrap_or(0))
.sum();
let out = opts
.out
.map_or_else(|| crate_dir.join("report"), Path::to_path_buf);
std::fs::create_dir_all(&out).with_context(|| format!("creating {}", out.display()))?;
let card = Card {
schema: SCHEMA,
at: crate::state::now(),
port,
crate_name: manifest.crate_name.clone(),
unit: manifest.unit.clone(),
language: manifest.language.name().to_string(),
language_id: format!("{:?}", manifest.language).to_lowercase(),
functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
cases: diff.total,
matched: diff.passed,
accepted: diff.accepted,
comparison: comparison.line(),
notes,
speedup: verdict.speedup,
bench,
fallback_cases,
enabled: switch_state(crate::enable::is_supported(&manifest), || {
crate::enable::is_enabled(&crate_dir)
})?,
differences: diff.groups.iter().take(5).cloned().collect(),
end_state: manifest.end_state,
intended: crate::recording::known_diffs(&crate_dir)?
.iter()
.map(|e| Intended {
function: e["fn"].as_str().unwrap_or_default().to_string(),
args: e["when"].as_str().map_or_else(
|| e["args"].to_string(),
|w| format!("every input, when {w}"),
),
reason: e["reason"].as_str().unwrap_or_default().to_string(),
})
.collect(),
kept: manifest.js_only.clone(),
machine: machine(),
markdown: out.join("REPORT.md"),
svg: out.join("card.svg"),
};
std::fs::write(&card.svg, svg(&card))?;
std::fs::write(&card.markdown, markdown(&card))?;
std::fs::write(
out.join("report.json"),
serde_json::to_string_pretty(&card)? + "\n",
)?;
Ok(card)
}
/// Whether `enable` has switched the unit on: `None` for a unit it cannot switch (the card says
/// so), its state otherwise. A failure to read the state is an error, not `None`: that would show
/// the "not switched by enable" label for a unit `enable` can switch.
fn switch_state(supported: bool, read: impl FnOnce() -> Result<bool>) -> Result<Option<bool>> {
if !supported {
return Ok(None);
}
read()
.map(Some)
.context("reading whether the unit is switched on")
}
fn cases_per_function(crate_dir: &Path) -> BTreeMap<String, usize> {
let mut out = BTreeMap::new();
let text = std::fs::read_to_string(crate_dir.join(harness::CASES)).unwrap_or_default();
for line in text.lines() {
if let Ok(case) = harness::parse_deep(line)
&& let Some(name) = case["fn"].as_str().or_else(|| case["class"].as_str())
{
*out.entry(name.to_string()).or_default() += 1;
}
}
out
}
/// The CPU's name and its core count, as `bench` numbers must be published with.
pub fn machine() -> String {
let cores = std::thread::available_parallelism().map_or(0, std::num::NonZero::get);
let mut cmd = std::process::Command::new("sysctl");
cmd.args(["-n", "machdep.cpu.brand_string"]);
let name = crate::process::output(&mut cmd, crate::process::QUICK)
.ok()
.filter(crate::process::Output::success)
.map(|o| o.stdout_text().trim().to_string())
.filter(|s| !s.is_empty())
.or_else(|| {
std::fs::read_to_string("/proc/cpuinfo").ok().and_then(|t| {
t.lines()
.find(|l| l.starts_with("model name"))
.and_then(|l| l.split_once(':'))
.map(|(_, v)| v.trim().to_string())
})
})
.unwrap_or_else(|| std::env::consts::ARCH.to_string());
let os = match std::env::consts::OS {
"macos" => "macOS",
"linux" => "Linux",
"windows" => "Windows",
other => other,
};
format!("{name}, {cores} cores, {os}")
}
fn times(x: f64) -> String {
// The boundary is where the one-decimal form would read `10.0x`: print the whole number it
// already shows instead of a decimal that adds nothing.
if x >= 9.95 {
format!("{x:.0}x")
} else {
format!("{x:.1}x")
}
}
/// What the card says instead of a speed when no function's cases all match.
const NOTHING_TO_COMPARE: &str = "nothing to compare";
/// "Nx faster" at or above parity, "Nx slower" below it, the way the card's headline reads.
fn speed_phrase(speedup: f64) -> String {
if speedup >= 1.0 {
format!("{} faster", times(speedup))
} else {
format!("{} slower", times(1.0 / speedup.max(1e-9)))
}
}
/// A table cell keeps the bare `Nx` for a faster port; below parity it names the slowdown so a
/// speedup like 0.04 can never print as `0.0x`.
fn table_speed(speedup: f64) -> String {
if speedup >= 1.0 {
times(speedup)
} else {
speed_phrase(speedup)
}
}
/// Each threshold is the value at which the unit below it would print as `1000` of that unit,
/// rounded: `999_999 ns` is `1000.0 µs`, so it belongs in `ms`.
fn ns(v: f64) -> String {
if v >= 999_950_000.0 {
format!("{:.2} s", v / 1e9)
} else if v >= 999_950.0 {
format!("{:.1} ms", v / 1e6)
} else if v >= 999.5 {
format!("{:.1} µs", v / 1e3)
} else {
format!("{v:.0} ns")
}
}
/// Only none or all of the cases print as `0.0%` or `100.0%`; a share that rounds to either
/// reads `<0.1%` or `>99.9%`.
fn fallback_percent(card: &Card) -> String {
let share = format!("{:.1}", 100.0 * card.fallback_rate());
if card.fallback_cases > 0 && share == "0.0" {
"<0.1%".into()
} else if card.fallback_cases < card.cases && share == "100.0" {
">99.9%".into()
} else {
format!("{share}%")
}
}
fn state(card: &Card) -> &'static str {
match card.enabled {
Some(true) => "on",
Some(false) => "off",
None => "not switched by `enable`",
}
}
pub fn markdown(card: &Card) -> String {
let mut out = format!(
"## `{}` in Rust\n\n\n\n\
| | |\n| --- | --- |\n\
| Unit | `{}` ({}) |\n\
| Comparison | {} |\n\
| Recorded cases matched | {} |\n\
| Speedup, call included | {} |\n\
| Fallback to the original | {} ({} of {}) |\n\
| Switched on | {} |\n\
| End state | {} |\n\n",
card.crate_name,
card.crate_name,
card.unit,
card.language,
card.comparison
.strip_prefix("comparison: ")
.or_else(|| card.comparison.strip_prefix("comparison "))
.unwrap_or(&card.comparison),
if card.accepted > 0 {
format!(
"{} / {} exactly, {} accepted as known differences",
card.exact(),
card.cases,
card.accepted
)
} else {
format!("{} / {}", card.matched, card.cases)
},
if card.nothing_timed() {
NOTHING_TO_COMPARE.to_string()
} else {
format!("{} (geometric mean)", table_speed(card.speedup))
},
fallback_percent(card),
card.fallback_cases,
crate::report::count(card.cases, "recorded case"),
state(card),
card.end_state.map_or_else(
|| "not chosen".to_string(),
|e| format!("{}: {}", e.name(), e.after_cut_over())
),
);
for note in &card.notes {
let _ = writeln!(out, "Note: {}\n", cell(note));
}
if !card.bench.is_empty() {
out.push_str(
"| Function | Cases | Original per call | Rust per call | Speedup |\n| --- | ---: | ---: | ---: | ---: |\n",
);
for r in &card.bench {
let speed = if r.failing {
"left out: cases do not match".to_string()
} else {
table_speed(r.speedup)
};
let _ = writeln!(
out,
"| `{}` | {} | {} | {} | {} |",
r.name,
r.cases,
ns(r.original_ns),
ns(r.rust_ns),
speed
);
}
out.push('\n');
}
if card.matched < card.cases && !card.differences.is_empty() {
out.push_str(
"### Remaining differences\n\n| Cases | Id | Difference |\n| ---: | --- | --- |\n",
);
for g in &card.differences {
let _ = writeln!(
out,
"| {} | `{}` | `{}` |",
g.cases,
g.id,
g.label().replace('`', "'").replace('|', "\\|")
);
}
out.push('\n');
}
if !card.intended.is_empty() {
let _ = writeln!(
out,
"### Intended differences\n\nFrom `{}`: the port is meant to differ on these \
inputs.\n\n| Function | Input | Reason |\n| --- | --- | --- |",
crate::recording::KNOWN_DIFFS
);
for i in &card.intended {
let _ = writeln!(
out,
"| `{}` | `{}` | {} |",
i.function,
cell(&i.args),
cell(&i.reason)
);
}
out.push('\n');
}
if !card.kept.is_empty() {
let _ = writeln!(
out,
"### Kept in {}\n\n| Export | Where | Reason |\n| --- | --- | --- |",
card.language
);
for k in &card.kept {
let _ = writeln!(
out,
"| `{}` | `{}:{}` | {} |",
k.name,
k.file,
k.line,
cell(&k.reason)
);
}
out.push('\n');
}
let _ = writeln!(
out,
"Measured with `rust-anything report` on {}: `diff` replays every recorded case, `bench` \
times them on both sides as callers call them. Reproduce: `rust-anything diff` and \
`rust-anything bench` in the crate folder.",
card.machine
);
out
}
/// Text safe inside a Markdown table cell, in or out of backticks.
fn cell(s: &str) -> String {
s.replace('`', "'").replace('|', "\\|")
}
fn esc(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
/// Light card in the v3 style: white, an outlined panel for the original, a tinted orange one
/// for Rust, the headline result below.
pub fn svg(card: &Card) -> String {
const W: u32 = 1200;
const H: u32 = 600;
let font = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif";
let mono = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
let timed: Vec<&BenchRow> = card.bench.iter().filter(|b| !b.failing).collect();
let (orig, rust) = timed
.iter()
.fold((0.0, 0.0), |(o, r), b| (o + b.original_ns, r + b.rust_ns));
let max = orig.max(rust).max(1.0);
let nothing_timed = card.nothing_timed();
let bar = |v: f64| {
if nothing_timed {
0.0
} else {
(5.0_f64).max(470.0 * v / max)
}
};
let timing = |v: f64| {
if nothing_timed {
"–".to_string()
} else {
ns(v)
}
};
let speed = if nothing_timed {
NOTHING_TO_COMPARE.to_string()
} else {
speed_phrase(card.speedup)
};
let all = card.matched == card.cases && card.cases > 0 && card.accepted == 0;
// A crate recorded from one input has one case, so every count here reads singular for one
// (issue #887).
let headline = if all {
format!(
"Same result as the original on all {}",
crate::report::count(card.cases, "recorded case")
)
} else if card.accepted > 0 {
format!(
"{} of {} match, {} accepted as known {}",
card.exact(),
crate::report::count(card.cases, "recorded case"),
card.accepted,
if card.accepted == 1 {
"difference"
} else {
"differences"
}
)
} else {
format!(
"{} of {} match the original",
card.matched,
crate::report::count(card.cases, "recorded case")
)
};
let per_call = if timed.len() == 1 {
"per call"
} else if timed.len() < card.bench.len() {
"per call, matching functions"
} else {
"per call, all functions"
};
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="{label}">
<rect width="{W}" height="{H}" fill="#ffffff"/>
<g font-family="{font}">
<svg x="64" y="52" width="60" height="60" viewBox="0 0 200 200">{crab}</svg>
<text x="140" y="94" font-size="34" font-weight="700" fill="#1a1a1a">rust-anything</text>
<text x="380" y="94" font-size="{title_size}" font-weight="700" fill="#1a1a1a">{name}, ported to <tspan fill="#e8561a">Rust</tspan></text>
<text x="64" y="140" font-size="18" fill="#666666">{unit} ({lang}) · {functions}</text>
<rect x="64" y="172" width="520" height="230" rx="20" fill="#ffffff" stroke="#e5e5e5" stroke-width="3"/>
<text x="96" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Original</text>
<text x="552" y="218" font-size="17" fill="#666666" text-anchor="end">{per_call}</text>
<text x="96" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#1a1a1a">{orig_t}</text>
<rect x="96" y="360" width="{orig_w:.0}" height="14" rx="7" fill="#9e9e9e"/>
<rect x="616" y="172" width="520" height="230" rx="20" fill="#fdf4ef" stroke="#f2b89a" stroke-width="3"/>
<text x="648" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Rust port</text>
<text x="1104" y="218" font-size="17" fill="#666666" text-anchor="end">{state}</text>
<text x="648" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#e8561a">{rust_t}</text>
<rect x="648" y="360" width="{rust_w:.0}" height="14" rx="7" fill="#e8561a"/>
<text x="600" y="460" font-size="28" fill="#1a1a1a" text-anchor="middle">{headline}: <tspan font-weight="700" fill="#e8561a">{speed}</tspan></text>
<text x="600" y="500" font-size="18" fill="#777777" text-anchor="middle">Fallback to the original: {fallback} of cases · call included · {machine}</text>
<text x="600" y="528" font-size="16" fill="#b45309" text-anchor="middle">{loosened}</text>
<text x="600" y="556" font-size="17" fill="#888888" text-anchor="middle">github.com/erkamyaman/rust-anything</text>
</g>
</svg>
"##,
label = esc(&format!(
"{}: {} of {} match{}, {}",
card.crate_name,
card.exact(),
crate::report::count(card.cases, "recorded case"),
if card.accepted > 0 {
format!(", {} accepted as known differences", card.accepted)
} else {
String::new()
},
speed
)),
loosened = esc(&if card.comparison == "comparison: exact" {
String::new()
} else {
card.comparison.clone()
}),
name = esc(&card.crate_name),
title_size = if card.crate_name.chars().count() > 22 {
24
} else {
34
},
unit = esc(&card.unit),
lang = esc(&card.language),
functions = esc(&card.functions.join(", ")),
orig_t = esc(&timing(orig)),
rust_t = esc(&timing(rust)),
orig_w = bar(orig),
rust_w = bar(rust),
// A unit `enable` cannot switch (Go, C, Ruby, ...) is not "switched off": that would say
// it could be turned on. REPORT.md says the same words.
state = match card.enabled {
Some(true) => "switched on",
Some(false) => "switched off",
None => "not switched by enable",
},
speed = esc(&speed),
crab = include_str!("card_crab.svg").trim(),
fallback = esc(&fallback_percent(card)),
machine = esc(&card.machine),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn table_speed_names_a_slowdown_below_parity() {
assert_eq!(table_speed(2.0), "2.0x");
assert_eq!(table_speed(0.5), "2.0x slower");
}
#[test]
fn esc_encodes_svg_special_characters_once() {
assert_eq!(esc("&<>\""), "&<>"");
assert_eq!(esc("<"), "&lt;");
}
#[test]
fn a_value_that_rounds_up_to_the_next_unit_prints_in_that_unit() {
assert_eq!(ns(999.6), "1.0 µs");
assert_eq!(ns(999_999.0), "1.0 ms");
assert_eq!(ns(999_999_999.0), "1.00 s");
assert_eq!(times(9.96), "10x");
// Just under each boundary stays where it is.
assert_eq!(ns(999.0), "999 ns");
assert_eq!(ns(999_000.0), "999.0 µs");
assert_eq!(ns(999_000_000.0), "999.0 ms");
assert_eq!(times(9.94), "9.9x");
// The ordinary cases are unchanged.
assert_eq!(ns(500.0), "500 ns");
assert_eq!(ns(1_500_000.0), "1.5 ms");
assert_eq!(times(31.4), "31x");
}
fn card() -> Card {
Card {
schema: SCHEMA,
at: "2026-11-28T10:00:00Z".into(),
port: "0123456789abcdef".into(),
crate_name: "fuzzy-rs".into(),
unit: "app.py".into(),
language: "Python".into(),
language_id: "python".into(),
functions: vec!["dedupe".into()],
cases: 412,
matched: 412,
accepted: 0,
comparison: "comparison: exact".into(),
notes: Vec::new(),
speedup: 31.4,
bench: vec![BenchRow {
name: "dedupe".into(),
cases: 412,
original_ns: 9_120_000.0,
rust_ns: 290_000.0,
speedup: 31.4,
failing: false,
}],
fallback_cases: 0,
enabled: Some(true),
differences: Vec::new(),
end_state: None,
intended: Vec::new(),
kept: Vec::new(),
machine: "Apple M4, 10 cores, macOS".into(),
markdown: "REPORT.md".into(),
svg: "card.svg".into(),
}
}
#[test]
fn fallback_percent_distinguishes_rounded_limits_from_exact_limits() {
let mut c = card();
c.cases = 10_000;
for (fallback_cases, expected) in [
(0, "0.0%"),
(10_000, "100.0%"),
(1, "<0.1%"),
(9_999, ">99.9%"),
] {
c.fallback_cases = fallback_cases;
assert_eq!(fallback_percent(&c), expected);
}
c.cases = 4;
c.fallback_cases = 1;
assert_eq!(fallback_percent(&c), "25.0%");
}
#[test]
fn an_unreadable_switch_state_is_an_error_not_the_unsupported_label() {
// A unit `enable` cannot switch: no state, and the state is not even read.
assert_eq!(
switch_state(false, || panic!("not read for an unsupported unit")).unwrap(),
None
);
// One it can: its state.
assert_eq!(switch_state(true, || Ok(true)).unwrap(), Some(true));
assert_eq!(switch_state(true, || Ok(false)).unwrap(), Some(false));
// A failed read must not become `None`, which the card words as "not switched by enable".
let err = switch_state(true, || anyhow::bail!("rust-anything.json changed")).unwrap_err();
assert!(
format!("{err:#}").contains("reading whether the unit is switched on"),
"{err:#}"
);
}
#[test]
fn the_card_says_not_switched_for_a_unit_enable_cannot_switch() {
let state_of = |enabled: Option<bool>| {
let mut c = card();
c.enabled = enabled;
svg(&c)
};
// Go, C, Ruby and the others `enable` does not support are not "switched off": that
// reads as if they could be turned on, and REPORT.md says "not switched by `enable`".
let none = state_of(None);
assert!(none.contains("not switched by enable"), "no such label");
assert!(
!none.contains("switched off") && !none.contains("switched on"),
"the card says the unit is switched on or off"
);
// The units it can switch still show their state.
assert!(state_of(Some(true)).contains(">switched on<"));
assert!(state_of(Some(false)).contains(">switched off<"));
}
#[test]
fn the_card_shows_what_was_measured() {
let svg = svg(&card());
assert!(svg.starts_with("<svg"), "{svg}");
for want in [
"fuzzy-rs",
"9.1 ms",
"290.0 µs",
"all 412 recorded cases",
"31x faster",
"switched on",
"0.0% of cases",
"Apple M4, 10 cores",
] {
assert!(svg.contains(want), "{want} missing:\n{svg}");
}
let md = markdown(&card());
assert!(
md.contains("| Recorded cases matched | 412 / 412 |"),
"{md}"
);
assert!(
md.contains("| `dedupe` | 412 | 9.1 ms | 290.0 µs | 31x |"),
"{md}"
);
}
#[test]
fn a_one_case_report_reads_singular_in_the_fallback_row() {
// The card's SVG said "1 recorded case" after #890, but the markdown table kept
// "(1 of 1 cases)".
let mut one = card();
one.cases = 1;
one.matched = 1;
one.fallback_cases = 1;
let md = markdown(&one);
assert!(
md.contains("| Fallback to the original | 100.0% (1 of 1 recorded case) |"),
"{md}"
);
assert!(!md.contains("1 recorded cases"), "{md}");
let many = markdown(&card());
assert!(
many.contains("(0 of 412 recorded cases)"),
"the plural row is unchanged: {many}"
);
}
#[test]
fn reviewers_see_the_end_state_intended_differences_and_kept_exports() {
let md = markdown(&card());
assert!(md.contains("| End state | not chosen |"), "{md}");
assert!(!md.contains("### Intended differences"), "{md}");
assert!(!md.contains("### Kept in Python"), "{md}");
let mut c = card();
c.end_state = Some(crate::bridge::EndState::Replace);
c.intended = vec![Intended {
function: "dedupe".into(),
args: "[\"a|b\"]".into(),
reason: "keeps the first spelling, as the docs say".into(),
}];
c.kept = vec![crate::bridge::JsOnly {
name: "load".into(),
file: "app.py".into(),
line: 12,
reason: "reads files".into(),
}];
let md = markdown(&c);
assert!(
md.contains("| End state | replace: delete the original once callers use the Rust |"),
"{md}"
);
assert!(
md.contains(
"### Intended differences\n\nFrom `known-diffs.jsonl`: the port is meant to \
differ on these inputs.\n\n| Function | Input | Reason |\n| --- | --- | --- \
|\n| `dedupe` | `[\"a\\|b\"]` | keeps the first spelling, as the docs say |\n"
),
"{md}"
);
assert!(
md.contains(
"### Kept in Python\n\n| Export | Where | Reason |\n| --- | --- | --- |\n\
| `load` | `app.py:12` | reads files |\n"
),
"{md}"
);
}
#[test]
fn a_fallback_rate_never_rounds_to_none_or_all() {
let mut c = card();
c.cases = 2001;
c.fallback_cases = 1;
assert!(svg(&c).contains("Fallback to the original: <0.1% of cases"));
assert!(
markdown(&c)
.contains("| Fallback to the original | <0.1% (1 of 2001 recorded cases) |")
);
c.cases = 2000;
c.fallback_cases = 1999;
assert!(svg(&c).contains("Fallback to the original: >99.9% of cases"));
assert!(
markdown(&c)
.contains("| Fallback to the original | >99.9% (1999 of 2000 recorded cases) |")
);
// None and all still print as they are, and so does a share that rounds to neither.
c.fallback_cases = 0;
assert!(svg(&c).contains("Fallback to the original: 0.0% of cases"));
c.fallback_cases = 2000;
assert!(svg(&c).contains("Fallback to the original: 100.0% of cases"));
c.fallback_cases = 1;
assert!(svg(&c).contains("Fallback to the original: 0.1% of cases"));
}
#[test]
fn a_card_whose_functions_all_fail_claims_no_speed() {
// #341 review: every row left out of the timing left verdict's 1.0 as a speed claim.
let mut c = card();
c.bench[0].failing = true;
c.speedup = 1.0;
let svg = svg(&c);
assert!(
svg.contains("<tspan font-weight=\"700\" fill=\"#e8561a\">nothing to compare</tspan>"),
"{svg}"
);
assert!(
svg.contains("recorded cases match, nothing to compare\""),
"{svg}"
);
assert!(!svg.contains("faster") && !svg.contains("slower"), "{svg}");
assert!(svg.contains("width=\"0\" height=\"14\""), "{svg}");
let md = markdown(&c);
assert!(
md.contains("| Speedup, call included | nothing to compare |"),
"{md}"
);
assert!(
md.contains("| `dedupe` | 412 | 9.1 ms | 290.0 µs | left out: cases do not match |"),
"{md}"
);
}
#[test]
fn a_slower_port_says_slower_in_the_label_and_tables_too() {
let mut c = card();
c.speedup = 0.04;
c.bench[0].original_ns = 290_000.0;
c.bench[0].rust_ns = 9_120_000.0;
c.bench[0].speedup = 0.04;
let svg = svg(&c);
for want in [
"aria-label=\"fuzzy-rs: 412 of 412 recorded cases match, 25x slower\"",
"<tspan font-weight=\"700\" fill=\"#e8561a\">25x slower</tspan>",
] {
assert!(svg.contains(want), "{want} missing:\n{svg}");
}
assert!(!svg.contains("0.0x"), "{svg}");
let md = markdown(&c);
assert!(
md.contains("| Speedup, call included | 25x slower (geometric mean) |"),
"{md}"
);
assert!(
md.contains("| `dedupe` | 412 | 290.0 µs | 9.1 ms | 25x slower |"),
"{md}"
);
}
#[test]
fn text_from_the_project_is_escaped() {
let mut c = card();
c.unit = "src/<a&b>.ts".into();
c.matched = 400;
let svg = svg(&c);
assert!(svg.contains("src/<a&b>.ts"));
assert!(svg.contains("400 of 412 recorded cases match"));
}
#[test]
fn remaining_differences_are_listed_while_cases_differ() {
let mut c = card();
assert!(!markdown(&c).contains("Remaining differences"));
c.matched = 400;
c.differences = vec![crate::mismatch::Group {
id: "a1b2c3d4".into(),
function: Some("dedupe".into()),
channel: "return".into(),
path: Some("$[]".into()),
kind: "value".into(),
cases: 12,
example: serde_json::Value::Null,
}];
let md = markdown(&c);
assert!(md.contains("### Remaining differences"), "{md}");
assert!(
md.contains("| 12 | `a1b2c3d4` | `dedupe: return $[] (value)` |"),
"{md}"
);
c.matched = c.cases;
assert!(!markdown(&c).contains("Remaining differences"));
}
#[test]
fn one_recorded_case_reads_singular_in_the_headline_and_the_label() {
// Issue #887: `record --count 0 --inputs one.jsonl` gives a crate one case, and the card said
// "all 1 recorded cases".
let mut one = card();
one.cases = 1;
one.matched = 1;
let out = svg(&one);
assert!(
out.contains("Same result as the original on all 1 recorded case:"),
"{out}"
);
assert!(!out.contains("1 recorded cases"), "{out}");
assert!(out.contains("1 of 1 recorded case match"), "{out}");
// The plural is unchanged.
let many = svg(&card());
assert!(many.contains("all 412 recorded cases"), "{many}");
}
#[test]
fn cases_accepted_as_known_differences_are_never_called_the_same_result() {
// A port that answers 12 of 412 cases differently, each accepted in known-diffs.jsonl,
// does not have "the same result on all 412 recorded cases".
let mut c = card();
c.accepted = 12;
c.comparison = "comparison loosened: 12 known differences in known-diffs.jsonl".into();
c.notes = vec!["12 of 412 cases are accepted as known differences".into()];
let out = svg(&c);
assert!(!out.contains("Same result"), "{out}");
assert!(
out.contains("400 of 412 recorded cases match, 12 accepted as known differences"),
"{out}"
);
assert!(
out.contains("comparison loosened: 12 known differences"),
"{out}"
);
let md = markdown(&c);
assert!(
md.contains(
"| Recorded cases matched | 400 / 412 exactly, 12 accepted as known differences |"
),
"{md}"
);
assert!(
md.contains("| Comparison | loosened: 12 known differences"),
"{md}"
);
assert!(md.contains("Note: 12 of 412 cases are accepted"), "{md}");
// One accepted case reads singular.
c.accepted = 1;
assert!(
svg(&c).contains("1 accepted as known difference:"),
"{}",
svg(&c)
);
}
#[test]
fn a_loosened_comparison_is_on_the_card_even_when_every_case_matches() {
let mut c = card();
c.comparison = "comparison loosened: float tolerance 0.5".into();
let md = markdown(&c);
assert!(
md.contains("| Comparison | loosened: float tolerance 0.5 |"),
"{md}"
);
assert!(svg(&c).contains("comparison loosened: float tolerance 0.5"));
// Exact reads exact.
assert!(markdown(&card()).contains("| Comparison | exact |"));
}
#[test]
fn a_card_with_nothing_timed_claims_no_speed() {
let mut c = card();
c.bench = Vec::new();
assert!(svg(&c).contains("nothing to compare"));
assert!(!markdown(&c).contains("geometric mean"));
}
}