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    pub machine: String,
37    pub markdown: PathBuf,
38    pub svg: PathBuf,
39}
40
41impl Card {
42    pub fn fallback_rate(&self) -> f64 {
43        if self.cases == 0 {
44            0.0
45        } else {
46            self.fallback_cases as f64 / self.cases as f64
47        }
48    }
49}
50
51pub struct Options<'a> {
52    pub crate_dir: &'a Path,
53    pub out: Option<&'a Path>,
54    pub min_ms: u64,
55    pub node_args: &'a [String],
56}
57
58pub fn report(opts: &Options) -> Result<Card> {
59    let crate_dir = opts.crate_dir.canonical().with_context(|| {
60        format!(
61            "resolving {} (run `rust-anything bridge` first)",
62            opts.crate_dir.display()
63        )
64    })?;
65    let manifest = Manifest::load(&crate_dir)?;
66    harness::build(&crate_dir)?;
67    let diff = harness::diff(&harness::DiffOptions {
68        crate_dir: &crate_dir,
69        module: None,
70        ignore_key_order: false,
71        node_args: opts.node_args,
72        float_tolerance: None,
73    })?;
74    let bench = harness::bench(&harness::BenchOptions {
75        crate_dir: &crate_dir,
76        min_ms: opts.min_ms,
77        resolve_from: None,
78        node_args: opts.node_args,
79    })?;
80    let verdict = harness::verdict(&bench, manifest.language);
81    let per_function = cases_per_function(&crate_dir);
82    let fallback_cases = diff
83        .missing
84        .iter()
85        .map(|f| per_function.get(f).copied().unwrap_or(0))
86        .sum();
87    let out = opts
88        .out
89        .map_or_else(|| crate_dir.join("report"), Path::to_path_buf);
90    std::fs::create_dir_all(&out).with_context(|| format!("creating {}", out.display()))?;
91    let mut card = Card {
92        schema: SCHEMA,
93        crate_name: manifest.crate_name.clone(),
94        unit: manifest.unit.clone(),
95        language: manifest.language.name().to_string(),
96        functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
97        cases: diff.total,
98        matched: diff.passed,
99        speedup: verdict.speedup,
100        bench,
101        fallback_cases,
102        enabled: crate::enable::is_enabled(&crate_dir).ok(),
103        machine: machine(),
104        markdown: out.join("REPORT.md"),
105        svg: out.join("card.svg"),
106    };
107    card.enabled = card
108        .enabled
109        .filter(|_| crate::enable::is_supported(&manifest));
110    std::fs::write(&card.svg, svg(&card))?;
111    std::fs::write(&card.markdown, markdown(&card))?;
112    Ok(card)
113}
114
115fn cases_per_function(crate_dir: &Path) -> BTreeMap<String, usize> {
116    let mut out = BTreeMap::new();
117    let text = std::fs::read_to_string(crate_dir.join(harness::CASES)).unwrap_or_default();
118    for line in text.lines() {
119        if let Ok(case) = serde_json::from_str::<serde_json::Value>(line)
120            && let Some(name) = case["fn"].as_str()
121        {
122            *out.entry(name.to_string()).or_default() += 1;
123        }
124    }
125    out
126}
127
128/// The CPU's name and its core count, as `bench` numbers must be published with.
129pub fn machine() -> String {
130    let cores = std::thread::available_parallelism().map_or(0, std::num::NonZero::get);
131    let mut cmd = std::process::Command::new("sysctl");
132    cmd.args(["-n", "machdep.cpu.brand_string"]);
133    let name = crate::process::output(&mut cmd, crate::process::QUICK)
134        .ok()
135        .filter(crate::process::Output::success)
136        .map(|o| o.stdout_text().trim().to_string())
137        .filter(|s| !s.is_empty())
138        .or_else(|| {
139            std::fs::read_to_string("/proc/cpuinfo").ok().and_then(|t| {
140                t.lines()
141                    .find(|l| l.starts_with("model name"))
142                    .and_then(|l| l.split_once(':'))
143                    .map(|(_, v)| v.trim().to_string())
144            })
145        })
146        .unwrap_or_else(|| std::env::consts::ARCH.to_string());
147    let os = match std::env::consts::OS {
148        "macos" => "macOS",
149        "linux" => "Linux",
150        "windows" => "Windows",
151        other => other,
152    };
153    format!("{name}, {cores} cores, {os}")
154}
155
156fn times(x: f64) -> String {
157    // The boundary is where the one-decimal form would read `10.0x`: print the whole number it
158    // already shows instead of a decimal that adds nothing.
159    if x >= 9.95 {
160        format!("{x:.0}x")
161    } else {
162        format!("{x:.1}x")
163    }
164}
165
166/// Each threshold is the value at which the unit below it would print as `1000` of that unit,
167/// rounded: `999_999 ns` is `1000.0 µs`, so it belongs in `ms`.
168fn ns(v: f64) -> String {
169    if v >= 999_950_000.0 {
170        format!("{:.2} s", v / 1e9)
171    } else if v >= 999_950.0 {
172        format!("{:.1} ms", v / 1e6)
173    } else if v >= 999.5 {
174        format!("{:.1} µs", v / 1e3)
175    } else {
176        format!("{v:.0} ns")
177    }
178}
179
180/// Only none or all of the cases print as `0.0%` or `100.0%`; a share that rounds to either
181/// reads `<0.1%` or `>99.9%`.
182fn fallback_percent(card: &Card) -> String {
183    let share = format!("{:.1}", 100.0 * card.fallback_rate());
184    if card.fallback_cases > 0 && share == "0.0" {
185        "<0.1%".into()
186    } else if card.fallback_cases < card.cases && share == "100.0" {
187        ">99.9%".into()
188    } else {
189        format!("{share}%")
190    }
191}
192
193fn state(card: &Card) -> &'static str {
194    match card.enabled {
195        Some(true) => "on",
196        Some(false) => "off",
197        None => "not switched by `enable`",
198    }
199}
200
201pub fn markdown(card: &Card) -> String {
202    let mut out = format!(
203        "## `{}` in Rust\n\n![{} report card](card.svg)\n\n\
204         | | |\n| --- | --- |\n\
205         | Unit | `{}` ({}) |\n\
206         | Recorded cases matched | {} / {} |\n\
207         | Speedup, call included | {} (geometric mean) |\n\
208         | Fallback to the original | {} ({} of {} cases) |\n\
209         | Switched on | {} |\n\n",
210        card.crate_name,
211        card.crate_name,
212        card.unit,
213        card.language,
214        card.matched,
215        card.cases,
216        times(card.speedup),
217        fallback_percent(card),
218        card.fallback_cases,
219        card.cases,
220        state(card),
221    );
222    if !card.bench.is_empty() {
223        out.push_str(
224            "| Function | Cases | Original per call | Rust per call | Speedup |\n| --- | ---: | ---: | ---: | ---: |\n",
225        );
226        for r in &card.bench {
227            let _ = writeln!(
228                out,
229                "| `{}` | {} | {} | {} | {} |",
230                r.name,
231                r.cases,
232                ns(r.original_ns),
233                ns(r.rust_ns),
234                times(r.speedup)
235            );
236        }
237        out.push('\n');
238    }
239    let _ = writeln!(
240        out,
241        "Measured with `rust-anything report` on {}: `diff` replays every recorded case, `bench` \
242         times them on both sides as callers call them. Reproduce: `rust-anything diff` and \
243         `rust-anything bench` in the crate folder.",
244        card.machine
245    );
246    out
247}
248
249fn esc(s: &str) -> String {
250    s.replace('&', "&amp;")
251        .replace('<', "&lt;")
252        .replace('>', "&gt;")
253        .replace('"', "&quot;")
254}
255
256/// Light card in the v3 style: white, an outlined panel for the original, a tinted orange one
257/// for Rust, the headline result below.
258pub fn svg(card: &Card) -> String {
259    const W: u32 = 1200;
260    const H: u32 = 600;
261    let font = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif";
262    let mono = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
263    let (orig, rust) = card
264        .bench
265        .iter()
266        .fold((0.0, 0.0), |(o, r), b| (o + b.original_ns, r + b.rust_ns));
267    let max = orig.max(rust).max(1.0);
268    let bar = |v: f64| (5.0_f64).max(470.0 * v / max);
269    let all = card.matched == card.cases && card.cases > 0;
270    let headline = if all {
271        format!(
272            "Same result as the original on all {} recorded cases",
273            card.cases
274        )
275    } else {
276        format!(
277            "{} of {} recorded cases match the original",
278            card.matched, card.cases
279        )
280    };
281    let per_call = if card.bench.len() == 1 {
282        "per call"
283    } else {
284        "per call, all functions"
285    };
286    format!(
287        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="{label}">
288<rect width="{W}" height="{H}" fill="#ffffff"/>
289<g font-family="{font}">
290<svg x="64" y="52" width="60" height="60" viewBox="0 0 200 200">{crab}</svg>
291<text x="140" y="94" font-size="34" font-weight="700" fill="#1a1a1a">rust-anything</text>
292<text x="380" y="94" font-size="{title_size}" font-weight="700" fill="#1a1a1a">{name}, ported to <tspan fill="#e8561a">Rust</tspan></text>
293<text x="64" y="140" font-size="18" fill="#666666">{unit} ({lang}) · {functions}</text>
294<rect x="64" y="172" width="520" height="230" rx="20" fill="#ffffff" stroke="#e5e5e5" stroke-width="3"/>
295<text x="96" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Original</text>
296<text x="552" y="218" font-size="17" fill="#666666" text-anchor="end">{per_call}</text>
297<text x="96" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#1a1a1a">{orig_t}</text>
298<rect x="96" y="360" width="{orig_w:.0}" height="14" rx="7" fill="#9e9e9e"/>
299<rect x="616" y="172" width="520" height="230" rx="20" fill="#fdf4ef" stroke="#f2b89a" stroke-width="3"/>
300<text x="648" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Rust port</text>
301<text x="1104" y="218" font-size="17" fill="#666666" text-anchor="end">switched {state}</text>
302<text x="648" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#e8561a">{rust_t}</text>
303<rect x="648" y="360" width="{rust_w:.0}" height="14" rx="7" fill="#e8561a"/>
304<text x="600" y="460" font-size="28" fill="#1a1a1a" text-anchor="middle">{headline}: <tspan font-weight="700" fill="#e8561a">{speed}</tspan></text>
305<text x="600" y="500" font-size="18" fill="#777777" text-anchor="middle">Fallback to the original: {fallback} of cases · call included · {machine}</text>
306<text x="600" y="556" font-size="17" fill="#888888" text-anchor="middle">github.com/erkamyaman/rust-anything</text>
307</g>
308</svg>
309"##,
310        label = esc(&format!(
311            "{}: {} of {} recorded cases match, {} faster",
312            card.crate_name,
313            card.matched,
314            card.cases,
315            times(card.speedup)
316        )),
317        name = esc(&card.crate_name),
318        title_size = if card.crate_name.chars().count() > 22 {
319            24
320        } else {
321            34
322        },
323        unit = esc(&card.unit),
324        lang = esc(&card.language),
325        functions = esc(&card.functions.join(", ")),
326        orig_t = esc(&ns(orig)),
327        rust_t = esc(&ns(rust)),
328        orig_w = bar(orig),
329        rust_w = bar(rust),
330        state = if card.enabled == Some(true) {
331            "on"
332        } else {
333            "off"
334        },
335        speed = if card.speedup >= 1.0 {
336            format!("{} faster", times(card.speedup))
337        } else {
338            format!("{} slower", times(1.0 / card.speedup.max(1e-9)))
339        },
340        crab = include_str!("card_crab.svg").trim(),
341        fallback = esc(&fallback_percent(card)),
342        machine = esc(&card.machine),
343    )
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[test]
351    fn a_value_that_rounds_up_to_the_next_unit_prints_in_that_unit() {
352        assert_eq!(ns(999.6), "1.0 µs");
353        assert_eq!(ns(999_999.0), "1.0 ms");
354        assert_eq!(ns(999_999_999.0), "1.00 s");
355        assert_eq!(times(9.96), "10x");
356        // Just under each boundary stays where it is.
357        assert_eq!(ns(999.0), "999 ns");
358        assert_eq!(ns(999_000.0), "999.0 µs");
359        assert_eq!(ns(999_000_000.0), "999.0 ms");
360        assert_eq!(times(9.94), "9.9x");
361        // The ordinary cases are unchanged.
362        assert_eq!(ns(500.0), "500 ns");
363        assert_eq!(ns(1_500_000.0), "1.5 ms");
364        assert_eq!(times(31.4), "31x");
365    }
366
367    fn card() -> Card {
368        Card {
369            schema: SCHEMA,
370            crate_name: "fuzzy-rs".into(),
371            unit: "app.py".into(),
372            language: "Python".into(),
373            functions: vec!["dedupe".into()],
374            cases: 412,
375            matched: 412,
376            speedup: 31.4,
377            bench: vec![BenchRow {
378                name: "dedupe".into(),
379                cases: 412,
380                original_ns: 9_120_000.0,
381                rust_ns: 290_000.0,
382                speedup: 31.4,
383            }],
384            fallback_cases: 0,
385            enabled: Some(true),
386            machine: "Apple M4, 10 cores, macOS".into(),
387            markdown: "REPORT.md".into(),
388            svg: "card.svg".into(),
389        }
390    }
391
392    #[test]
393    fn the_card_shows_what_was_measured() {
394        let svg = svg(&card());
395        assert!(svg.starts_with("<svg"), "{svg}");
396        for want in [
397            "fuzzy-rs",
398            "9.1 ms",
399            "290.0 µs",
400            "all 412 recorded cases",
401            "31x faster",
402            "switched on",
403            "0.0% of cases",
404            "Apple M4, 10 cores",
405        ] {
406            assert!(svg.contains(want), "{want} missing:\n{svg}");
407        }
408        let md = markdown(&card());
409        assert!(
410            md.contains("| Recorded cases matched | 412 / 412 |"),
411            "{md}"
412        );
413        assert!(
414            md.contains("| `dedupe` | 412 | 9.1 ms | 290.0 µs | 31x |"),
415            "{md}"
416        );
417    }
418
419    #[test]
420    fn a_fallback_rate_never_rounds_to_none_or_all() {
421        let mut c = card();
422        c.cases = 2001;
423        c.fallback_cases = 1;
424        assert!(svg(&c).contains("Fallback to the original: &lt;0.1% of cases"));
425        assert!(markdown(&c).contains("| Fallback to the original | <0.1% (1 of 2001 cases) |"));
426        c.cases = 2000;
427        c.fallback_cases = 1999;
428        assert!(svg(&c).contains("Fallback to the original: &gt;99.9% of cases"));
429        assert!(
430            markdown(&c).contains("| Fallback to the original | >99.9% (1999 of 2000 cases) |")
431        );
432        // None and all still print as they are, and so does a share that rounds to neither.
433        c.fallback_cases = 0;
434        assert!(svg(&c).contains("Fallback to the original: 0.0% of cases"));
435        c.fallback_cases = 2000;
436        assert!(svg(&c).contains("Fallback to the original: 100.0% of cases"));
437        c.fallback_cases = 1;
438        assert!(svg(&c).contains("Fallback to the original: 0.1% of cases"));
439    }
440
441    #[test]
442    fn text_from_the_project_is_escaped() {
443        let mut c = card();
444        c.unit = "src/<a&b>.ts".into();
445        c.matched = 400;
446        let svg = svg(&c);
447        assert!(svg.contains("src/&lt;a&amp;b&gt;.ts"));
448        assert!(svg.contains("400 of 412 recorded cases match"));
449    }
450}