Skip to main content

rust_anything/
card.rs

1//! `report`: a unit's result as Markdown and an SVG card, for a pull request or a README.
2//!
3//! Every number comes from a run made for the report: `diff` for the recorded cases that
4//! match, `bench` for the speedup, and the cases of functions the Rust module does not provide
5//! for the fallback rate. The machine and its core count go next to the timing.
6
7use std::collections::BTreeMap;
8use std::fmt::Write as _;
9use std::path::{Path, PathBuf};
10
11use anyhow::{Context, Result};
12use serde::Serialize;
13
14use crate::bridge::Manifest;
15use crate::harness::{self, BenchRow};
16use crate::walk::Canonical;
17
18pub const SCHEMA: &str = "rust-anything/report@1";
19
20#[derive(Debug, Serialize)]
21pub struct Card {
22    pub schema: &'static str,
23    pub crate_name: String,
24    pub unit: String,
25    pub language: String,
26    pub functions: Vec<String>,
27    pub cases: usize,
28    pub matched: usize,
29    /// Geometric mean of `original_ns / rust_ns` over the timed functions, call included.
30    pub speedup: f64,
31    pub bench: Vec<BenchRow>,
32    /// Recorded cases whose function the Rust module does not provide, so the original answers.
33    pub fallback_cases: usize,
34    /// `Some(true)` while `enable` has switched the unit on; `None` where `enable` does not apply.
35    pub enabled: Option<bool>,
36    /// The distinct differences still left, most cases first (at most five).
37    #[serde(skip_serializing_if = "Vec::is_empty")]
38    pub differences: Vec<crate::mismatch::Group>,
39    /// What the bindings are for once the port is done (`bridge --end-state`).
40    pub end_state: Option<crate::bridge::EndState>,
41    /// The entries of `known-diffs.jsonl`: inputs the port is meant to answer differently.
42    #[serde(skip_serializing_if = "Vec::is_empty")]
43    pub intended: Vec<Intended>,
44    /// Exports kept in the original language, with the reason.
45    #[serde(skip_serializing_if = "Vec::is_empty")]
46    pub kept: Vec<crate::bridge::JsOnly>,
47    pub machine: String,
48    pub markdown: PathBuf,
49    pub svg: PathBuf,
50}
51
52/// One `known-diffs.jsonl` entry, as reviewers read it.
53#[derive(Debug, Serialize)]
54pub struct Intended {
55    pub function: String,
56    /// The recorded arguments, as JSON.
57    pub args: String,
58    pub reason: String,
59}
60
61impl Card {
62    /// Every benched function was left out of the timing because its cases do not match, so the
63    /// card has no speed to claim.
64    fn nothing_timed(&self) -> bool {
65        !self.bench.is_empty() && self.bench.iter().all(|b| b.failing)
66    }
67
68    pub fn fallback_rate(&self) -> f64 {
69        if self.cases == 0 {
70            0.0
71        } else {
72            self.fallback_cases as f64 / self.cases as f64
73        }
74    }
75}
76
77pub struct Options<'a> {
78    pub crate_dir: &'a Path,
79    pub out: Option<&'a Path>,
80    pub min_ms: u64,
81    pub node_args: &'a [String],
82    /// Resolve npm packages the original imports from this folder's `node_modules`, as `bench` does.
83    pub resolve_from: Option<&'a Path>,
84}
85
86pub fn report(opts: &Options) -> Result<Card> {
87    anyhow::ensure!(opts.min_ms > 0, "`--min-ms` must be at least 1");
88    let crate_dir = opts.crate_dir.canonical().with_context(|| {
89        format!(
90            "resolving {} (run `rust-anything bridge` first)",
91            opts.crate_dir.display()
92        )
93    })?;
94    let manifest = Manifest::load(&crate_dir)?;
95    if let Some(dir) = opts.resolve_from {
96        dir.canonical()
97            .with_context(|| format!("resolving {}", dir.display()))?;
98    }
99    harness::build(&crate_dir)?;
100    let diff = harness::diff(&harness::DiffOptions {
101        crate_dir: &crate_dir,
102        module: None,
103        ignore_key_order: false,
104        node_args: opts.node_args,
105        float_tolerance: None,
106    })?;
107    let bench = harness::bench(&harness::BenchOptions {
108        crate_dir: &crate_dir,
109        min_ms: opts.min_ms,
110        resolve_from: opts.resolve_from,
111        node_args: opts.node_args,
112    })?;
113    let verdict = harness::verdict(&bench, manifest.language);
114    let per_function = cases_per_function(&crate_dir);
115    let fallback_cases = diff
116        .missing
117        .iter()
118        .map(|f| per_function.get(f).copied().unwrap_or(0))
119        .sum();
120    let out = opts
121        .out
122        .map_or_else(|| crate_dir.join("report"), Path::to_path_buf);
123    std::fs::create_dir_all(&out).with_context(|| format!("creating {}", out.display()))?;
124    let mut card = Card {
125        schema: SCHEMA,
126        crate_name: manifest.crate_name.clone(),
127        unit: manifest.unit.clone(),
128        language: manifest.language.name().to_string(),
129        functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
130        cases: diff.total,
131        matched: diff.passed,
132        speedup: verdict.speedup,
133        bench,
134        fallback_cases,
135        enabled: crate::enable::is_enabled(&crate_dir).ok(),
136        differences: diff.groups.iter().take(5).cloned().collect(),
137        end_state: manifest.end_state,
138        intended: crate::recording::known_diffs(&crate_dir)?
139            .iter()
140            .map(|e| Intended {
141                function: e["fn"].as_str().unwrap_or_default().to_string(),
142                args: e["args"].to_string(),
143                reason: e["reason"].as_str().unwrap_or_default().to_string(),
144            })
145            .collect(),
146        kept: manifest.js_only.clone(),
147        machine: machine(),
148        markdown: out.join("REPORT.md"),
149        svg: out.join("card.svg"),
150    };
151    card.enabled = card
152        .enabled
153        .filter(|_| crate::enable::is_supported(&manifest));
154    std::fs::write(&card.svg, svg(&card))?;
155    std::fs::write(&card.markdown, markdown(&card))?;
156    Ok(card)
157}
158
159fn cases_per_function(crate_dir: &Path) -> BTreeMap<String, usize> {
160    let mut out = BTreeMap::new();
161    let text = std::fs::read_to_string(crate_dir.join(harness::CASES)).unwrap_or_default();
162    for line in text.lines() {
163        if let Ok(case) = serde_json::from_str::<serde_json::Value>(line)
164            && let Some(name) = case["fn"].as_str()
165        {
166            *out.entry(name.to_string()).or_default() += 1;
167        }
168    }
169    out
170}
171
172/// The CPU's name and its core count, as `bench` numbers must be published with.
173pub fn machine() -> String {
174    let cores = std::thread::available_parallelism().map_or(0, std::num::NonZero::get);
175    let mut cmd = std::process::Command::new("sysctl");
176    cmd.args(["-n", "machdep.cpu.brand_string"]);
177    let name = crate::process::output(&mut cmd, crate::process::QUICK)
178        .ok()
179        .filter(crate::process::Output::success)
180        .map(|o| o.stdout_text().trim().to_string())
181        .filter(|s| !s.is_empty())
182        .or_else(|| {
183            std::fs::read_to_string("/proc/cpuinfo").ok().and_then(|t| {
184                t.lines()
185                    .find(|l| l.starts_with("model name"))
186                    .and_then(|l| l.split_once(':'))
187                    .map(|(_, v)| v.trim().to_string())
188            })
189        })
190        .unwrap_or_else(|| std::env::consts::ARCH.to_string());
191    let os = match std::env::consts::OS {
192        "macos" => "macOS",
193        "linux" => "Linux",
194        "windows" => "Windows",
195        other => other,
196    };
197    format!("{name}, {cores} cores, {os}")
198}
199
200fn times(x: f64) -> String {
201    // The boundary is where the one-decimal form would read `10.0x`: print the whole number it
202    // already shows instead of a decimal that adds nothing.
203    if x >= 9.95 {
204        format!("{x:.0}x")
205    } else {
206        format!("{x:.1}x")
207    }
208}
209
210/// What the card says instead of a speed when no function's cases all match.
211const NOTHING_TO_COMPARE: &str = "nothing to compare";
212
213/// "Nx faster" at or above parity, "Nx slower" below it, the way the card's headline reads.
214fn speed_phrase(speedup: f64) -> String {
215    if speedup >= 1.0 {
216        format!("{} faster", times(speedup))
217    } else {
218        format!("{} slower", times(1.0 / speedup.max(1e-9)))
219    }
220}
221
222/// A table cell keeps the bare `Nx` for a faster port; below parity it names the slowdown so a
223/// speedup like 0.04 can never print as `0.0x`.
224fn table_speed(speedup: f64) -> String {
225    if speedup >= 1.0 {
226        times(speedup)
227    } else {
228        speed_phrase(speedup)
229    }
230}
231
232/// Each threshold is the value at which the unit below it would print as `1000` of that unit,
233/// rounded: `999_999 ns` is `1000.0 µs`, so it belongs in `ms`.
234fn ns(v: f64) -> String {
235    if v >= 999_950_000.0 {
236        format!("{:.2} s", v / 1e9)
237    } else if v >= 999_950.0 {
238        format!("{:.1} ms", v / 1e6)
239    } else if v >= 999.5 {
240        format!("{:.1} µs", v / 1e3)
241    } else {
242        format!("{v:.0} ns")
243    }
244}
245
246/// Only none or all of the cases print as `0.0%` or `100.0%`; a share that rounds to either
247/// reads `<0.1%` or `>99.9%`.
248fn fallback_percent(card: &Card) -> String {
249    let share = format!("{:.1}", 100.0 * card.fallback_rate());
250    if card.fallback_cases > 0 && share == "0.0" {
251        "<0.1%".into()
252    } else if card.fallback_cases < card.cases && share == "100.0" {
253        ">99.9%".into()
254    } else {
255        format!("{share}%")
256    }
257}
258
259fn state(card: &Card) -> &'static str {
260    match card.enabled {
261        Some(true) => "on",
262        Some(false) => "off",
263        None => "not switched by `enable`",
264    }
265}
266
267pub fn markdown(card: &Card) -> String {
268    let mut out = format!(
269        "## `{}` in Rust\n\n![{} report card](card.svg)\n\n\
270         | | |\n| --- | --- |\n\
271         | Unit | `{}` ({}) |\n\
272         | Recorded cases matched | {} / {} |\n\
273         | Speedup, call included | {} |\n\
274         | Fallback to the original | {} ({} of {} cases) |\n\
275         | Switched on | {} |\n\
276         | End state | {} |\n\n",
277        card.crate_name,
278        card.crate_name,
279        card.unit,
280        card.language,
281        card.matched,
282        card.cases,
283        if card.nothing_timed() {
284            NOTHING_TO_COMPARE.to_string()
285        } else {
286            format!("{} (geometric mean)", table_speed(card.speedup))
287        },
288        fallback_percent(card),
289        card.fallback_cases,
290        card.cases,
291        state(card),
292        card.end_state.map_or_else(
293            || "not chosen".to_string(),
294            |e| format!("{}: {}", e.name(), e.after_cut_over())
295        ),
296    );
297    if !card.bench.is_empty() {
298        out.push_str(
299            "| Function | Cases | Original per call | Rust per call | Speedup |\n| --- | ---: | ---: | ---: | ---: |\n",
300        );
301        for r in &card.bench {
302            let speed = if r.failing {
303                "left out: cases do not match".to_string()
304            } else {
305                table_speed(r.speedup)
306            };
307            let _ = writeln!(
308                out,
309                "| `{}` | {} | {} | {} | {} |",
310                r.name,
311                r.cases,
312                ns(r.original_ns),
313                ns(r.rust_ns),
314                speed
315            );
316        }
317        out.push('\n');
318    }
319    if card.matched < card.cases && !card.differences.is_empty() {
320        out.push_str(
321            "### Remaining differences\n\n| Cases | Id | Difference |\n| ---: | --- | --- |\n",
322        );
323        for g in &card.differences {
324            let _ = writeln!(
325                out,
326                "| {} | `{}` | `{}` |",
327                g.cases,
328                g.id,
329                g.label().replace('`', "'").replace('|', "\\|")
330            );
331        }
332        out.push('\n');
333    }
334    if !card.intended.is_empty() {
335        let _ = writeln!(
336            out,
337            "### Intended differences\n\nFrom `{}`: the port is meant to differ on these \
338             inputs.\n\n| Function | Input | Reason |\n| --- | --- | --- |",
339            crate::recording::KNOWN_DIFFS
340        );
341        for i in &card.intended {
342            let _ = writeln!(
343                out,
344                "| `{}` | `{}` | {} |",
345                i.function,
346                cell(&i.args),
347                cell(&i.reason)
348            );
349        }
350        out.push('\n');
351    }
352    if !card.kept.is_empty() {
353        let _ = writeln!(
354            out,
355            "### Kept in {}\n\n| Export | Where | Reason |\n| --- | --- | --- |",
356            card.language
357        );
358        for k in &card.kept {
359            let _ = writeln!(
360                out,
361                "| `{}` | `{}:{}` | {} |",
362                k.name,
363                k.file,
364                k.line,
365                cell(&k.reason)
366            );
367        }
368        out.push('\n');
369    }
370    let _ = writeln!(
371        out,
372        "Measured with `rust-anything report` on {}: `diff` replays every recorded case, `bench` \
373         times them on both sides as callers call them. Reproduce: `rust-anything diff` and \
374         `rust-anything bench` in the crate folder.",
375        card.machine
376    );
377    out
378}
379
380/// Text safe inside a Markdown table cell, in or out of backticks.
381fn cell(s: &str) -> String {
382    s.replace('`', "'").replace('|', "\\|")
383}
384
385fn esc(s: &str) -> String {
386    s.replace('&', "&amp;")
387        .replace('<', "&lt;")
388        .replace('>', "&gt;")
389        .replace('"', "&quot;")
390}
391
392/// Light card in the v3 style: white, an outlined panel for the original, a tinted orange one
393/// for Rust, the headline result below.
394pub fn svg(card: &Card) -> String {
395    const W: u32 = 1200;
396    const H: u32 = 600;
397    let font = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif";
398    let mono = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
399    let timed: Vec<&BenchRow> = card.bench.iter().filter(|b| !b.failing).collect();
400    let (orig, rust) = timed
401        .iter()
402        .fold((0.0, 0.0), |(o, r), b| (o + b.original_ns, r + b.rust_ns));
403    let max = orig.max(rust).max(1.0);
404    let nothing_timed = card.nothing_timed();
405    let bar = |v: f64| {
406        if nothing_timed {
407            0.0
408        } else {
409            (5.0_f64).max(470.0 * v / max)
410        }
411    };
412    let timing = |v: f64| {
413        if nothing_timed {
414            "–".to_string()
415        } else {
416            ns(v)
417        }
418    };
419    let speed = if nothing_timed {
420        NOTHING_TO_COMPARE.to_string()
421    } else {
422        speed_phrase(card.speedup)
423    };
424    let all = card.matched == card.cases && card.cases > 0;
425    let headline = if all {
426        format!(
427            "Same result as the original on all {} recorded cases",
428            card.cases
429        )
430    } else {
431        format!(
432            "{} of {} recorded cases match the original",
433            card.matched, card.cases
434        )
435    };
436    let per_call = if timed.len() == 1 {
437        "per call"
438    } else if timed.len() < card.bench.len() {
439        "per call, matching functions"
440    } else {
441        "per call, all functions"
442    };
443    format!(
444        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="{label}">
445<rect width="{W}" height="{H}" fill="#ffffff"/>
446<g font-family="{font}">
447<svg x="64" y="52" width="60" height="60" viewBox="0 0 200 200">{crab}</svg>
448<text x="140" y="94" font-size="34" font-weight="700" fill="#1a1a1a">rust-anything</text>
449<text x="380" y="94" font-size="{title_size}" font-weight="700" fill="#1a1a1a">{name}, ported to <tspan fill="#e8561a">Rust</tspan></text>
450<text x="64" y="140" font-size="18" fill="#666666">{unit} ({lang}) · {functions}</text>
451<rect x="64" y="172" width="520" height="230" rx="20" fill="#ffffff" stroke="#e5e5e5" stroke-width="3"/>
452<text x="96" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Original</text>
453<text x="552" y="218" font-size="17" fill="#666666" text-anchor="end">{per_call}</text>
454<text x="96" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#1a1a1a">{orig_t}</text>
455<rect x="96" y="360" width="{orig_w:.0}" height="14" rx="7" fill="#9e9e9e"/>
456<rect x="616" y="172" width="520" height="230" rx="20" fill="#fdf4ef" stroke="#f2b89a" stroke-width="3"/>
457<text x="648" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Rust port</text>
458<text x="1104" y="218" font-size="17" fill="#666666" text-anchor="end">switched {state}</text>
459<text x="648" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#e8561a">{rust_t}</text>
460<rect x="648" y="360" width="{rust_w:.0}" height="14" rx="7" fill="#e8561a"/>
461<text x="600" y="460" font-size="28" fill="#1a1a1a" text-anchor="middle">{headline}: <tspan font-weight="700" fill="#e8561a">{speed}</tspan></text>
462<text x="600" y="500" font-size="18" fill="#777777" text-anchor="middle">Fallback to the original: {fallback} of cases · call included · {machine}</text>
463<text x="600" y="556" font-size="17" fill="#888888" text-anchor="middle">github.com/erkamyaman/rust-anything</text>
464</g>
465</svg>
466"##,
467        label = esc(&format!(
468            "{}: {} of {} recorded cases match, {}",
469            card.crate_name, card.matched, card.cases, speed
470        )),
471        name = esc(&card.crate_name),
472        title_size = if card.crate_name.chars().count() > 22 {
473            24
474        } else {
475            34
476        },
477        unit = esc(&card.unit),
478        lang = esc(&card.language),
479        functions = esc(&card.functions.join(", ")),
480        orig_t = esc(&timing(orig)),
481        rust_t = esc(&timing(rust)),
482        orig_w = bar(orig),
483        rust_w = bar(rust),
484        state = if card.enabled == Some(true) {
485            "on"
486        } else {
487            "off"
488        },
489        speed = esc(&speed),
490        crab = include_str!("card_crab.svg").trim(),
491        fallback = esc(&fallback_percent(card)),
492        machine = esc(&card.machine),
493    )
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499
500    #[test]
501    fn a_value_that_rounds_up_to_the_next_unit_prints_in_that_unit() {
502        assert_eq!(ns(999.6), "1.0 µs");
503        assert_eq!(ns(999_999.0), "1.0 ms");
504        assert_eq!(ns(999_999_999.0), "1.00 s");
505        assert_eq!(times(9.96), "10x");
506        // Just under each boundary stays where it is.
507        assert_eq!(ns(999.0), "999 ns");
508        assert_eq!(ns(999_000.0), "999.0 µs");
509        assert_eq!(ns(999_000_000.0), "999.0 ms");
510        assert_eq!(times(9.94), "9.9x");
511        // The ordinary cases are unchanged.
512        assert_eq!(ns(500.0), "500 ns");
513        assert_eq!(ns(1_500_000.0), "1.5 ms");
514        assert_eq!(times(31.4), "31x");
515    }
516
517    fn card() -> Card {
518        Card {
519            schema: SCHEMA,
520            crate_name: "fuzzy-rs".into(),
521            unit: "app.py".into(),
522            language: "Python".into(),
523            functions: vec!["dedupe".into()],
524            cases: 412,
525            matched: 412,
526            speedup: 31.4,
527            bench: vec![BenchRow {
528                name: "dedupe".into(),
529                cases: 412,
530                original_ns: 9_120_000.0,
531                rust_ns: 290_000.0,
532                speedup: 31.4,
533                failing: false,
534            }],
535            fallback_cases: 0,
536            enabled: Some(true),
537            differences: Vec::new(),
538            end_state: None,
539            intended: Vec::new(),
540            kept: Vec::new(),
541            machine: "Apple M4, 10 cores, macOS".into(),
542            markdown: "REPORT.md".into(),
543            svg: "card.svg".into(),
544        }
545    }
546
547    #[test]
548    fn the_card_shows_what_was_measured() {
549        let svg = svg(&card());
550        assert!(svg.starts_with("<svg"), "{svg}");
551        for want in [
552            "fuzzy-rs",
553            "9.1 ms",
554            "290.0 µs",
555            "all 412 recorded cases",
556            "31x faster",
557            "switched on",
558            "0.0% of cases",
559            "Apple M4, 10 cores",
560        ] {
561            assert!(svg.contains(want), "{want} missing:\n{svg}");
562        }
563        let md = markdown(&card());
564        assert!(
565            md.contains("| Recorded cases matched | 412 / 412 |"),
566            "{md}"
567        );
568        assert!(
569            md.contains("| `dedupe` | 412 | 9.1 ms | 290.0 µs | 31x |"),
570            "{md}"
571        );
572    }
573
574    #[test]
575    fn reviewers_see_the_end_state_intended_differences_and_kept_exports() {
576        let md = markdown(&card());
577        assert!(md.contains("| End state | not chosen |"), "{md}");
578        assert!(!md.contains("### Intended differences"), "{md}");
579        assert!(!md.contains("### Kept in Python"), "{md}");
580
581        let mut c = card();
582        c.end_state = Some(crate::bridge::EndState::Replace);
583        c.intended = vec![Intended {
584            function: "dedupe".into(),
585            args: "[\"a|b\"]".into(),
586            reason: "keeps the first spelling, as the docs say".into(),
587        }];
588        c.kept = vec![crate::bridge::JsOnly {
589            name: "load".into(),
590            file: "app.py".into(),
591            line: 12,
592            reason: "reads files".into(),
593        }];
594        let md = markdown(&c);
595        assert!(
596            md.contains("| End state | replace: delete the original once callers use the Rust |"),
597            "{md}"
598        );
599        assert!(
600            md.contains(
601                "### Intended differences\n\nFrom `known-diffs.jsonl`: the port is meant to \
602                 differ on these inputs.\n\n| Function | Input | Reason |\n| --- | --- | --- \
603                 |\n| `dedupe` | `[\"a\\|b\"]` | keeps the first spelling, as the docs say |\n"
604            ),
605            "{md}"
606        );
607        assert!(
608            md.contains(
609                "### Kept in Python\n\n| Export | Where | Reason |\n| --- | --- | --- |\n\
610                 | `load` | `app.py:12` | reads files |\n"
611            ),
612            "{md}"
613        );
614    }
615
616    #[test]
617    fn a_fallback_rate_never_rounds_to_none_or_all() {
618        let mut c = card();
619        c.cases = 2001;
620        c.fallback_cases = 1;
621        assert!(svg(&c).contains("Fallback to the original: &lt;0.1% of cases"));
622        assert!(markdown(&c).contains("| Fallback to the original | <0.1% (1 of 2001 cases) |"));
623        c.cases = 2000;
624        c.fallback_cases = 1999;
625        assert!(svg(&c).contains("Fallback to the original: &gt;99.9% of cases"));
626        assert!(
627            markdown(&c).contains("| Fallback to the original | >99.9% (1999 of 2000 cases) |")
628        );
629        // None and all still print as they are, and so does a share that rounds to neither.
630        c.fallback_cases = 0;
631        assert!(svg(&c).contains("Fallback to the original: 0.0% of cases"));
632        c.fallback_cases = 2000;
633        assert!(svg(&c).contains("Fallback to the original: 100.0% of cases"));
634        c.fallback_cases = 1;
635        assert!(svg(&c).contains("Fallback to the original: 0.1% of cases"));
636    }
637
638    #[test]
639    fn a_card_whose_functions_all_fail_claims_no_speed() {
640        // #341 review: every row left out of the timing left verdict's 1.0 as a speed claim.
641        let mut c = card();
642        c.bench[0].failing = true;
643        c.speedup = 1.0;
644        let svg = svg(&c);
645        assert!(
646            svg.contains("<tspan font-weight=\"700\" fill=\"#e8561a\">nothing to compare</tspan>"),
647            "{svg}"
648        );
649        assert!(
650            svg.contains("recorded cases match, nothing to compare\""),
651            "{svg}"
652        );
653        assert!(!svg.contains("faster") && !svg.contains("slower"), "{svg}");
654        assert!(svg.contains("width=\"0\" height=\"14\""), "{svg}");
655        let md = markdown(&c);
656        assert!(
657            md.contains("| Speedup, call included | nothing to compare |"),
658            "{md}"
659        );
660        assert!(
661            md.contains("| `dedupe` | 412 | 9.1 ms | 290.0 µs | left out: cases do not match |"),
662            "{md}"
663        );
664    }
665
666    #[test]
667    fn a_slower_port_says_slower_in_the_label_and_tables_too() {
668        let mut c = card();
669        c.speedup = 0.04;
670        c.bench[0].original_ns = 290_000.0;
671        c.bench[0].rust_ns = 9_120_000.0;
672        c.bench[0].speedup = 0.04;
673        let svg = svg(&c);
674        for want in [
675            "aria-label=\"fuzzy-rs: 412 of 412 recorded cases match, 25x slower\"",
676            "<tspan font-weight=\"700\" fill=\"#e8561a\">25x slower</tspan>",
677        ] {
678            assert!(svg.contains(want), "{want} missing:\n{svg}");
679        }
680        assert!(!svg.contains("0.0x"), "{svg}");
681        let md = markdown(&c);
682        assert!(
683            md.contains("| Speedup, call included | 25x slower (geometric mean) |"),
684            "{md}"
685        );
686        assert!(
687            md.contains("| `dedupe` | 412 | 290.0 µs | 9.1 ms | 25x slower |"),
688            "{md}"
689        );
690    }
691
692    #[test]
693    fn text_from_the_project_is_escaped() {
694        let mut c = card();
695        c.unit = "src/<a&b>.ts".into();
696        c.matched = 400;
697        let svg = svg(&c);
698        assert!(svg.contains("src/&lt;a&amp;b&gt;.ts"));
699        assert!(svg.contains("400 of 412 recorded cases match"));
700    }
701
702    #[test]
703    fn remaining_differences_are_listed_while_cases_differ() {
704        let mut c = card();
705        assert!(!markdown(&c).contains("Remaining differences"));
706        c.matched = 400;
707        c.differences = vec![crate::mismatch::Group {
708            id: "a1b2c3d4".into(),
709            function: Some("dedupe".into()),
710            channel: "return".into(),
711            path: Some("$[]".into()),
712            kind: "value".into(),
713            cases: 12,
714            example: serde_json::Value::Null,
715        }];
716        let md = markdown(&c);
717        assert!(md.contains("### Remaining differences"), "{md}");
718        assert!(
719            md.contains("| 12 | `a1b2c3d4` | `dedupe: return $[] (value)` |"),
720            "{md}"
721        );
722        c.matched = c.cases;
723        assert!(!markdown(&c).contains("Remaining differences"));
724    }
725}