bloat-show 0.1.0

Render `cargo bloat` JSON output as a self-contained, interactive HTML treemap
Documentation
//! [`BloatJson`] to a self-contained HTML page.

use crate::model::BloatJson;

const TEMPLATE: &str = include_str!("../assets/treemap.html");

const PLACEHOLDER_PREFIX: &str = "__BLOAT_SHOW_";
const PLACEHOLDER_TITLE: &str = "__BLOAT_SHOW_TITLE__";
const PLACEHOLDER_DATA: &str = "__BLOAT_SHOW_DATA__";
const PLACEHOLDER_META: &str = "__BLOAT_SHOW_META__";

#[derive(Debug, Clone)]
pub struct RenderOptions {
    /// Page `<title>`.
    pub title: String,
    /// Provenance line for the info bar.
    pub meta: String,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            title: "Cargo Bloat Treemap".to_owned(),
            meta: String::new(),
        }
    }
}

/// Renders `data` into a standalone HTML page with the data embedded.
pub fn render(data: &BloatJson, opts: &RenderOptions) -> String {
    let json = serde_json::to_string(data).expect("BloatJson always serializes");
    substitute(
        TEMPLATE,
        &[
            (PLACEHOLDER_TITLE, &escape_html_text(&opts.title)),
            (PLACEHOLDER_DATA, &escape_for_script(&json)),
            (PLACEHOLDER_META, &escape_js_string(&opts.meta)),
        ],
    )
}

/// Replaces every placeholder in one pass.
///
/// Sequential `str::replace` calls would rescan what earlier ones substituted, so a
/// title of `__BLOAT_SHOW_DATA__` would pull the whole JSON payload into `<title>`.
fn substitute(template: &str, values: &[(&str, &str)]) -> String {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    'outer: while let Some(at) = rest.find(PLACEHOLDER_PREFIX) {
        for (placeholder, value) in values {
            if rest[at..].starts_with(placeholder) {
                out.push_str(&rest[..at]);
                out.push_str(value);
                rest = &rest[at + placeholder.len()..];
                continue 'outer;
            }
        }
        // A `__BLOAT_SHOW_` that is not one of ours: copy it and move past it.
        let skip = at + PLACEHOLDER_PREFIX.len();
        out.push_str(&rest[..skip]);
        rest = &rest[skip..];
    }
    out.push_str(rest);
    out
}

/// Escapes JSON for embedding in a `<script>` block.
///
/// Symbol names contain `<` and `>`, so an accidental `</script` would end the block
/// early. `serde_json` only ever emits these inside string literals, so `\uXXXX`
/// stays valid JSON.
fn escape_for_script(json: &str) -> String {
    json.replace('<', "\\u003c")
        .replace('>', "\\u003e")
        .replace('&', "\\u0026")
}

/// Escapes text for a double-quoted JavaScript string literal.
fn escape_js_string(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            // Would otherwise close the enclosing <script>.
            '<' => out.push_str("\\u003c"),
            '>' => out.push_str("\\u003e"),
            '&' => out.push_str("\\u0026"),
            _ => out.push(ch),
        }
    }
    out
}

/// Escapes text for HTML character data.
fn escape_html_text(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Function;

    fn sample(name: &str) -> BloatJson {
        BloatJson {
            file_size: 2337496,
            text_section_size: 1340108,
            functions: vec![Function {
                krate: Some("wasmi".to_owned()),
                name: name.to_owned(),
                size: 39152,
            }],
        }
    }

    #[test]
    fn no_placeholder_survives_rendering() {
        let html = render(&sample("wasmi::run"), &RenderOptions::default());
        assert!(!html.contains("__BLOAT_SHOW"), "unreplaced placeholder");
    }

    #[test]
    fn rust_symbols_do_not_break_out_of_the_script_block() {
        let html = render(&sample("<T as </script>>::hack"), &RenderOptions::default());
        let data = BloatJson::from_rendered_html(&html).expect("data block intact");
        assert!(!data.contains('<'), "raw `<` left inside the data block");

        let parsed = BloatJson::from_json_str(data).expect("embedded JSON round-trips");
        assert_eq!(parsed.functions[0].name, "<T as </script>>::hack");
    }

    #[test]
    fn angle_brackets_round_trip_through_json_parse() {
        let name = "<wasmi_ir::op::Op as core::fmt::Debug>::fmt";
        let html = render(&sample(name), &RenderOptions::default());
        let data = BloatJson::from_rendered_html(&html).unwrap();
        let parsed = BloatJson::from_json_str(data).unwrap();

        assert_eq!(parsed.functions[0].name, name);
        assert_eq!(parsed.file_size, 2337496);
        assert_eq!(parsed.text_section_size, 1340108);
    }

    #[test]
    fn title_is_html_escaped() {
        let opts = RenderOptions {
            title: "a <script>alert(1)</script> b".to_owned(),
            ..RenderOptions::default()
        };
        let html = render(&sample("wasmi::run"), &opts);
        assert!(html.contains("<title>a &lt;script&gt;alert(1)&lt;/script&gt; b</title>"));
    }

    #[test]
    fn meta_is_js_escaped() {
        let opts = RenderOptions {
            meta: r#"cargo bloat --config 'k="v"'"#.to_owned(),
            ..RenderOptions::default()
        };
        let html = render(&sample("wasmi::run"), &opts);
        assert!(html.contains(r#"cargo bloat --config 'k=\"v\"'"#));
    }

    #[test]
    fn a_substituted_value_is_not_rescanned() {
        // Sequential `str::replace` passes would let the title's literal pull the
        // whole JSON payload into `<title>`.
        let opts = RenderOptions {
            title: "Bloat: __BLOAT_SHOW_DATA__".to_owned(),
            meta: "__BLOAT_SHOW_TITLE__".to_owned(),
        };
        let html = render(&sample("wasmi::run"), &opts);
        assert!(html.contains("<title>Bloat: __BLOAT_SHOW_DATA__</title>"),);
        assert!(html.contains(r#"textContent = "__BLOAT_SHOW_TITLE__""#));

        let embedded = BloatJson::from_rendered_html(&html).unwrap();
        assert_eq!(
            BloatJson::from_json_str(embedded).unwrap().functions.len(),
            1
        );
    }

    #[test]
    fn substitute_is_single_pass() {
        // The title's value contains the meta placeholder; it must survive verbatim.
        let out = substitute(
            "[title] [meta]"
                .replace("[title]", PLACEHOLDER_TITLE)
                .replace("[meta]", PLACEHOLDER_META)
                .as_str(),
            &[
                (PLACEHOLDER_TITLE, PLACEHOLDER_META),
                (PLACEHOLDER_META, "!"),
            ],
        );
        assert_eq!(out, format!("{PLACEHOLDER_META} !"));
    }

    #[test]
    fn an_unknown_placeholder_is_left_alone() {
        let out = substitute("a __BLOAT_SHOW_NOPE__ b", &[(PLACEHOLDER_TITLE, "!")]);
        assert_eq!(out, "a __BLOAT_SHOW_NOPE__ b");
    }

    #[test]
    fn template_contains_every_placeholder() {
        for placeholder in [PLACEHOLDER_TITLE, PLACEHOLDER_DATA, PLACEHOLDER_META] {
            assert!(
                TEMPLATE.contains(placeholder),
                "template lost {placeholder}"
            );
        }
    }
}