🏡 index : quine-global/quorum.git

//! Canonical JSON, as TUF (securesystemslib, OLPC) signs it: object keys
//! sorted by their bytes, no whitespace, strings escaping only `\` and `"`,
//! integers only.

use anyhow::{Result, bail};
use serde_json::Value;

pub fn encode(v: &Value) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    write(v, &mut out)?;
    Ok(out)
}

fn write(v: &Value, out: &mut Vec<u8>) -> Result<()> {
    match v {
        Value::Null => out.extend_from_slice(b"null"),
        Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                out.extend_from_slice(i.to_string().as_bytes());
            } else if let Some(u) = n.as_u64() {
                out.extend_from_slice(u.to_string().as_bytes());
            } else {
                bail!("canonical JSON has no floating-point numbers ({n})");
            }
        }
        Value::String(s) => string(s, out),
        Value::Array(a) => {
            out.push(b'[');
            for (i, x) in a.iter().enumerate() {
                if i > 0 {
                    out.push(b',');
                }
                write(x, out)?;
            }
            out.push(b']');
        }
        Value::Object(o) => {
            let mut keys: Vec<&String> = o.keys().collect();
            keys.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
            out.push(b'{');
            for (i, k) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(b',');
                }
                string(k, out);
                out.push(b':');
                write(&o[k.as_str()], out)?;
            }
            out.push(b'}');
        }
    }
    Ok(())
}

fn string(s: &str, out: &mut Vec<u8>) {
    out.push(b'"');
    for b in s.bytes() {
        if b == b'"' || b == b'\\' {
            out.push(b'\\');
        }
        out.push(b);
    }
    out.push(b'"');
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    #[test]
    fn sorted_compact_minimal_escapes() {
        let v = json!({"b": [1, true, null], "a": "x\"y\\z\n", "A": {"d": -2, "c": 3}});
        assert_eq!(
            String::from_utf8(super::encode(&v).unwrap()).unwrap(),
            "{\"A\":{\"c\":3,\"d\":-2},\"a\":\"x\\\"y\\\\z\n\",\"b\":[1,true,null]}"
        );
        assert!(super::encode(&json!(1.5)).is_err());
    }
}