instruction-md 0.4.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
//! What the specification's reference computes with ECMAScript's built-ins, which the port has to agree with byte for
//! byte: its whitespace, its trim, how it writes a number and a value, and how it orders strings.

use serde_json::{Number, Value};

/// ECMAScript whitespace (what `\s` matches): the WhiteSpace and LineTerminator characters.
pub(crate) fn js_space(c: char) -> bool {
    matches!(
        c,
        '\t' | '\n'
            | '\u{b}'
            | '\u{c}'
            | '\r'
            | ' '
            | '\u{a0}'
            | '\u{1680}'
            | '\u{2028}'
            | '\u{2029}'
            | '\u{202f}'
            | '\u{205f}'
            | '\u{3000}'
            | '\u{feff}'
    ) || ('\u{2000}'..='\u{200a}').contains(&c)
}

/// `String.prototype.trim`.
pub(crate) fn js_trim(s: &str) -> &str {
    s.trim_matches(js_space)
}

/// Nothing but whitespace.
pub(crate) fn blank(s: &str) -> bool {
    js_trim(s).is_empty()
}

/// ECMAScript's `\s` as a class body, for the reader's patterns.
pub(crate) const JS_SPACES: &str = r"\t\n\x{b}\x{c}\r \x{a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}\x{feff}";
/// ECMAScript's `.`.
pub(crate) const JS_DOT: &str = r"[^\n\r\x{2028}\x{2029}]";

/// `[^\s]`, as a class.
pub(crate) fn js_not_space() -> String {
    format!("[^{JS_SPACES}]")
}

/// How ECMAScript writes a number (`Number.prototype.toString`, which JSON and RFC 8785 also use).
pub fn js_number(f: f64) -> String {
    if f == 0.0 {
        return "0".into();
    }
    if f.is_nan() {
        return "NaN".into();
    }
    if f.is_infinite() {
        return if f > 0.0 { "Infinity".into() } else { "-Infinity".into() };
    }
    let abs = f.abs();
    if (1e-6..1e21).contains(&abs) {
        return format!("{f}");
    }
    let e = format!("{f:e}");
    match e.split_once('e') {
        Some((mantissa, exp)) if !exp.starts_with('-') => format!("{mantissa}e+{exp}"),
        _ => e,
    }
}

/// A JSON number value: an integral one as an integer (so that it writes as ECMAScript does), else a float; a
/// non-finite one (which JSON cannot carry) is null.
pub(crate) fn num(f: f64) -> Value {
    let f = if f == 0.0 { 0.0 } else { f };
    if f.fract() == 0.0 && f.abs() < 9_007_199_254_740_992.0 {
        return Value::Number(Number::from(f as i64));
    }
    Number::from_f64(f).map_or(Value::Null, Value::Number)
}

/// How a template literal writes a decoded JSON value (`String(v)`); `None` is a missing one (`undefined`).
pub(crate) fn js_value(v: Option<&Value>) -> String {
    match v {
        None => "undefined".into(),
        Some(Value::Null) => "null".into(),
        Some(Value::String(s)) => s.clone(),
        Some(Value::Bool(b)) => b.to_string(),
        Some(Value::Number(n)) => js_number(n.as_f64().unwrap_or(0.0)),
        Some(Value::Array(list)) => {
            list.iter().map(|e| if e.is_null() { String::new() } else { js_value(Some(e)) }).collect::<Vec<_>>().join(",")
        }
        Some(Value::Object(_)) => "[object Object]".into(),
    }
}

/// ECMAScript's truthiness for a decoded JSON value.
pub(crate) fn truthy(v: Option<&Value>) -> bool {
    match v {
        None | Some(Value::Null) => false,
        Some(Value::Bool(b)) => *b,
        Some(Value::String(s)) => !s.is_empty(),
        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
        Some(_) => true,
    }
}

/// Orders strings by their UTF-16 code units, as ECMAScript's default sort does.
pub(crate) fn utf16_less(a: &str, b: &str) -> bool {
    utf16_cmp(a, b) == std::cmp::Ordering::Less
}

pub(crate) fn utf16_cmp(a: &str, b: &str) -> std::cmp::Ordering {
    a.encode_utf16().cmp(b.encode_utf16())
}

/// Is the value this string (a JSON string equal to it)?
pub(crate) fn is_str(v: Option<&Value>, s: &str) -> bool {
    matches!(v, Some(Value::String(x)) if x == s)
}

/// Two JSON values equal as ECMAScript's `===` compares scalars (numbers by value); containers never.
#[cfg(feature = "verify")]
pub(crate) fn same_scalar(a: Option<&Value>, b: Option<&Value>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(Value::Null), Some(Value::Null)) => true,
        (Some(Value::Bool(x)), Some(Value::Bool(y))) => x == y,
        (Some(Value::String(x)), Some(Value::String(y))) => x == y,
        (Some(Value::Number(x)), Some(Value::Number(y))) => x.as_f64() == y.as_f64(),
        _ => false,
    }
}

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

    #[test]
    fn numbers_as_ecmascript_writes_them() {
        for (f, s) in [
            (1.0, "1"),
            (-0.0, "0"),
            (0.5, "0.5"),
            (1e21, "1e+21"),
            (1.5e-7, "1.5e-7"),
            (123456789.0, "123456789"),
            (1e-6, "0.000001"),
            (0.1 + 0.2, "0.30000000000000004"),
            (5e-5, "0.00005"),
        ] {
            assert_eq!(js_number(f), s);
        }
    }
}