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 {
pub title: String,
pub meta: String,
}
impl Default for RenderOptions {
fn default() -> Self {
Self {
title: "Cargo Bloat Treemap".to_owned(),
meta: String::new(),
}
}
}
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)),
],
)
}
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;
}
}
let skip = at + PLACEHOLDER_PREFIX.len();
out.push_str(&rest[..skip]);
rest = &rest[skip..];
}
out.push_str(rest);
out
}
fn escape_for_script(json: &str) -> String {
json.replace('<', "\\u003c")
.replace('>', "\\u003e")
.replace('&', "\\u0026")
}
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"),
'<' => out.push_str("\\u003c"),
'>' => out.push_str("\\u003e"),
'&' => out.push_str("\\u0026"),
_ => out.push(ch),
}
}
out
}
fn escape_html_text(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
#[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 <script>alert(1)</script> 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() {
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() {
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}"
);
}
}
}