bloat-show 0.1.0

Render `cargo bloat` JSON output as a self-contained, interactive HTML treemap
Documentation
//! The `cargo bloat --message-format=json` data format.

use core::fmt;

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BloatJson {
    /// Whole executable, in bytes.
    #[serde(rename = "file-size")]
    pub file_size: u64,
    /// Text section, in bytes.
    #[serde(rename = "text-section-size")]
    pub text_section_size: u64,
    /// Largest first.
    pub functions: Vec<Function>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Function {
    /// `cargo bloat` suffixes `?` when the attribution is a guess, and omits the
    /// field when it cannot attribute the symbol at all.
    #[serde(rename = "crate", skip_serializing_if = "Option::is_none")]
    pub krate: Option<String>,
    /// Demangled, e.g. `<wasmi_ir::op::Op as core::fmt::Debug>::fmt`.
    pub name: String,
    /// Machine code, in bytes.
    pub size: u64,
}

#[derive(Debug)]
pub enum ParseError {
    /// Not JSON.
    Syntax(serde_json::Error),
    /// JSON, but the wrong shape.
    Schema(serde_json::Error),
    /// `cargo bloat --crates` output.
    CratesMode,
    /// JSON, but not an object.
    NotAnObject,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::Syntax(err) => {
                write!(f, "input is not valid JSON: {err}")
            }
            ParseError::Schema(err) => write!(
                f,
                "input is not `cargo bloat` JSON output: {err}\n\
                 help:  generate it with `cargo bloat --message-format=json -n 0`"
            ),
            ParseError::CratesMode => write!(
                f,
                "this is `cargo bloat --crates` output (has `crates`, expected `functions`)\n\
                 help:  drop `--crates` - bloat-show builds its own per-crate view from function data"
            ),
            ParseError::NotAnObject => write!(
                f,
                "expected a JSON object at the top level\n\
                 help:  generate it with `cargo bloat --message-format=json -n 0`"
            ),
        }
    }
}

impl core::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            ParseError::Syntax(err) | ParseError::Schema(err) => Some(err),
            ParseError::CratesMode | ParseError::NotAnObject => None,
        }
    }
}

impl BloatJson {
    pub fn from_json_str(json: &str) -> Result<Self, ParseError> {
        // The happy path parses straight into the model; a second `Value` pass runs
        // only to classify a failure, so `--crates` output gets a precise diagnostic
        // instead of `missing field \`functions\``.
        match serde_json::from_str(json) {
            Ok(data) => Ok(data),
            Err(err) => Err(classify(json, err)),
        }
    }

    /// Extracts the JSON embedded in a page produced by [`crate::render()`].
    pub fn from_rendered_html(html: &str) -> Option<&str> {
        const OPEN: &str = "<script id=\"bloat-data\" type=\"application/json\">";
        const CLOSE: &str = "</script>";
        let start = html.find(OPEN)? + OPEN.len();
        let len = html[start..].find(CLOSE)?;
        Some(html[start..start + len].trim())
    }

    /// Distinct crates, ignoring the `?` marker.
    pub fn crate_count(&self) -> usize {
        let mut names: Vec<&str> = self.functions.iter().map(Function::crate_name).collect();
        names.sort_unstable();
        names.dedup();
        names.len()
    }
}

/// Turns a deserialization failure into the most specific [`ParseError`] we can.
fn classify(json: &str, err: serde_json::Error) -> ParseError {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(json) else {
        return ParseError::Syntax(err);
    };
    let serde_json::Value::Object(obj) = value else {
        return ParseError::NotAnObject;
    };
    match !obj.contains_key("functions") && obj.contains_key("crates") {
        true => ParseError::CratesMode,
        false => ParseError::Schema(err),
    }
}

impl Function {
    /// Owning crate with the `?` marker stripped. Matches what the frontend does.
    pub fn crate_name(&self) -> &str {
        match self.krate.as_deref() {
            None => "[unknown]",
            Some(name) => name.strip_suffix('?').unwrap_or(name),
        }
    }
}

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

    #[test]
    fn parses_minimal_document() {
        let json = r#"{
            "file-size": 100,
            "text-section-size": 60,
            "functions": [{ "crate": "wasmi", "name": "wasmi::run", "size": 40 }]
        }"#;
        let data = BloatJson::from_json_str(json).unwrap();
        assert_eq!(data.file_size, 100);
        assert_eq!(data.text_section_size, 60);
        assert_eq!(data.functions.len(), 1);
        assert_eq!(data.functions[0].size, 40);
    }

    #[test]
    fn crates_mode_gets_a_dedicated_error() {
        let json = r#"{
            "file-size": 100,
            "text-section-size": 60,
            "crates": [{ "name": "wasmi", "size": 40 }]
        }"#;
        let err = BloatJson::from_json_str(json).unwrap_err();
        assert!(matches!(err, ParseError::CratesMode), "got {err:?}");
        assert!(err.to_string().contains("drop `--crates`"));
    }

    #[test]
    fn missing_crate_field_is_tolerated() {
        let json = r#"{
            "file-size": 1,
            "text-section-size": 1,
            "functions": [{ "name": "anon", "size": 1 }]
        }"#;
        let data = BloatJson::from_json_str(json).unwrap();
        assert_eq!(data.functions[0].crate_name(), "[unknown]");
    }

    #[test]
    fn crate_count_ignores_the_guessed_marker() {
        let json = r#"{
            "file-size": 1,
            "text-section-size": 1,
            "functions": [
                { "crate": "wasmi",  "name": "a", "size": 1 },
                { "crate": "wasmi?", "name": "b", "size": 1 },
                { "crate": "std",    "name": "c", "size": 1 }
            ]
        }"#;
        let data = BloatJson::from_json_str(json).unwrap();
        assert_eq!(data.crate_count(), 2);
    }

    #[test]
    fn non_object_input_is_rejected() {
        let err = BloatJson::from_json_str("[]").unwrap_err();
        assert!(matches!(err, ParseError::NotAnObject), "got {err:?}");
    }

    #[test]
    fn invalid_json_is_reported_as_syntax_error() {
        let err = BloatJson::from_json_str("{").unwrap_err();
        assert!(matches!(err, ParseError::Syntax(_)), "got {err:?}");
    }
}