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