instruction-md 0.6.0

Read, check, resolve and verify instruction.md documents (the specification's first edition, instruction/1): the reader, the agent text, composition and signature verification
Documentation
//! RFC 8785 (JCS), the canonical JSON the resolved artifact's digest and the text profile's attribute lines use
//! (§14.1, §14.2): object keys in UTF-16 code-unit order, no whitespace, ECMAScript's number and string serialization.

use serde_json::Value;

use crate::digest::sha256_hex;
use crate::js::{js_number, utf16_cmp};

/// A value in RFC 8785 form. (A JSON value holds no non-finite number, so this cannot fail.)
pub fn canonical_json(value: &Value) -> String {
    let mut out = String::new();
    write(&mut out, value);
    out
}

/// `sha256:<hex>` of a value's canonical JSON, as UTF-8.
pub fn json_digest(value: &Value) -> String {
    format!("sha256:{}", sha256_hex(canonical_json(value).as_bytes()))
}

fn write(out: &mut String, value: &Value) {
    match value {
        Value::Null => out.push_str("null"),
        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Value::Number(n) => match n.as_f64() {
            Some(f) if f.is_finite() => out.push_str(&js_number(f)),
            _ => out.push_str("null"),
        },
        Value::String(s) => write_string(out, s),
        Value::Array(list) => {
            out.push('[');
            for (i, e) in list.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write(out, e);
            }
            out.push(']');
        }
        Value::Object(m) => {
            let mut keys: Vec<&String> = m.keys().collect();
            keys.sort_by(|a, b| utf16_cmp(a, b));
            out.push('{');
            for (i, k) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_string(out, k);
                out.push(':');
                write(out, &m[k.as_str()]);
            }
            out.push('}');
        }
    }
}

/// A string as `JSON.stringify` writes it: only quotes, backslashes and control characters escaped.
pub(crate) fn write_string(out: &mut String, s: &str) {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                out.push_str("\\u00");
                out.push(HEX[(c as usize) >> 4] as char);
                out.push(HEX[(c as usize) & 0xf] as char);
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

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

    #[test]
    fn canonical_form() {
        assert_eq!(
            canonical_json(&json!({"b": [1, 2.5, "x\n"], "a": {"\u{e000}": 1, "\u{1f600}": 2}, "c": null})),
            "{\"a\":{\"\u{1f600}\":2,\"\u{e000}\":1},\"b\":[1,2.5,\"x\\n\"],\"c\":null}"
        );
    }
}