garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /json/src/lib.rs

raw

//! JSON, read and written (RFC 8259), with no outside crate: what a model
//! provider's API speaks, and what the agent's tool calls arrive in
//! (`docs/agent-environment.md`).
//!
//! Everything read is untrusted: the network's bytes or a model's output.
//! So the reader is strict (no trailing commas, no leading zeros, no lone
//! surrogates, no control characters in strings, nothing after the value)
//! and bounded: nesting deeper than [`MAX_DEPTH`] is an error rather than a
//! stack overflow. Objects keep their keys in the order read, so what is
//! written back out is what came in.

#![no_std]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

/// How deep arrays and objects may nest.
pub const MAX_DEPTH: usize = 128;

#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Null,
    Bool(bool),
    Number(f64),
    String(String),
    Array(Vec<Value>),
    /// Keys in the order they came; a repeated key keeps both, and
    /// [`Value::get`] finds the first.
    Object(Vec<(String, Value)>),
}

/// What [`Value::get`] answers for a key that is not there.
pub static NULL: Value = Value::Null;

/// Where reading stopped, and why.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Error {
    /// The byte offset in the text.
    pub at: usize,
    pub kind: ErrorKind,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
    /// The text ended inside a value.
    End,
    /// A byte that cannot be here.
    Unexpected,
    /// Nested deeper than [`MAX_DEPTH`].
    TooDeep,
    /// A number that is not one, or does not fit an f64.
    Number,
    /// A bad escape, a lone surrogate, or a control character in a string.
    String,
    /// Something after the value.
    Trailing,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} at byte {}", self.kind, self.at)
    }
}

/// The one value in `text`.
pub fn parse(text: &str) -> Result<Value, Error> {
    let mut reader = Reader {
        bytes: text.as_bytes(),
        at: 0,
    };
    let value = reader.value(0)?;
    reader.space();
    if reader.at < reader.bytes.len() {
        return Err(reader.error(ErrorKind::Trailing));
    }
    Ok(value)
}

struct Reader<'a> {
    bytes: &'a [u8],
    at: usize,
}

impl Reader<'_> {
    fn error(&self, kind: ErrorKind) -> Error {
        Error { at: self.at, kind }
    }

    fn space(&mut self) {
        while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.bytes.get(self.at) {
            self.at += 1;
        }
    }

    fn peek(&self) -> Result<u8, Error> {
        self.bytes.get(self.at).copied().ok_or(self.error(ErrorKind::End))
    }

    fn literal(&mut self, word: &[u8], value: Value) -> Result<Value, Error> {
        match self.bytes.get(self.at..self.at + word.len()) {
            Some(w) if w == word => {
                self.at += word.len();
                Ok(value)
            }
            Some(_) => Err(self.error(ErrorKind::Unexpected)),
            None => Err(self.error(ErrorKind::End)),
        }
    }

    fn value(&mut self, depth: usize) -> Result<Value, Error> {
        self.space();
        match self.peek()? {
            b'n' => self.literal(b"null", Value::Null),
            b't' => self.literal(b"true", Value::Bool(true)),
            b'f' => self.literal(b"false", Value::Bool(false)),
            b'"' => self.string().map(Value::String),
            b'-' | b'0'..=b'9' => self.number(),
            b'[' | b'{' if depth >= MAX_DEPTH => Err(self.error(ErrorKind::TooDeep)),
            b'[' => {
                self.at += 1;
                let mut items = Vec::new();
                self.space();
                if self.peek()? == b']' {
                    self.at += 1;
                    return Ok(Value::Array(items));
                }
                loop {
                    items.push(self.value(depth + 1)?);
                    self.space();
                    match self.peek()? {
                        b',' => self.at += 1,
                        b']' => {
                            self.at += 1;
                            return Ok(Value::Array(items));
                        }
                        _ => return Err(self.error(ErrorKind::Unexpected)),
                    }
                }
            }
            b'{' => {
                self.at += 1;
                let mut fields = Vec::new();
                self.space();
                if self.peek()? == b'}' {
                    self.at += 1;
                    return Ok(Value::Object(fields));
                }
                loop {
                    self.space();
                    if self.peek()? != b'"' {
                        return Err(self.error(ErrorKind::Unexpected));
                    }
                    let key = self.string()?;
                    self.space();
                    if self.peek()? != b':' {
                        return Err(self.error(ErrorKind::Unexpected));
                    }
                    self.at += 1;
                    fields.push((key, self.value(depth + 1)?));
                    self.space();
                    match self.peek()? {
                        b',' => self.at += 1,
                        b'}' => {
                            self.at += 1;
                            return Ok(Value::Object(fields));
                        }
                        _ => return Err(self.error(ErrorKind::Unexpected)),
                    }
                }
            }
            _ => Err(self.error(ErrorKind::Unexpected)),
        }
    }

    fn digits(&mut self) -> usize {
        let start = self.at;
        while let Some(b'0'..=b'9') = self.bytes.get(self.at) {
            self.at += 1;
        }
        self.at - start
    }

    fn number(&mut self) -> Result<Value, Error> {
        let start = self.at;
        if self.bytes[self.at] == b'-' {
            self.at += 1;
        }
        let first = self.at;
        match self.digits() {
            0 => return Err(self.error(ErrorKind::Number)),
            n if n > 1 && self.bytes[first] == b'0' => {
                return Err(Error {
                    at: first,
                    kind: ErrorKind::Number,
                });
            }
            _ => {}
        }
        if self.bytes.get(self.at) == Some(&b'.') {
            self.at += 1;
            if self.digits() == 0 {
                return Err(self.error(ErrorKind::Number));
            }
        }
        if let Some(b'e' | b'E') = self.bytes.get(self.at) {
            self.at += 1;
            if let Some(b'+' | b'-') = self.bytes.get(self.at) {
                self.at += 1;
            }
            if self.digits() == 0 {
                return Err(self.error(ErrorKind::Number));
            }
        }
        // The text is ASCII digits and signs, so it is a str.
        let text = core::str::from_utf8(&self.bytes[start..self.at]).unwrap();
        match text.parse::<f64>() {
            Ok(n) if n.is_finite() => Ok(Value::Number(n)),
            _ => Err(Error {
                at: start,
                kind: ErrorKind::Number,
            }),
        }
    }

    fn hex4(&mut self) -> Result<u32, Error> {
        let digits = self
            .bytes
            .get(self.at..self.at + 4)
            .ok_or(self.error(ErrorKind::End))?;
        let mut n = 0;
        for &d in digits {
            n = n * 16 + (d as char).to_digit(16).ok_or(self.error(ErrorKind::String))?;
        }
        self.at += 4;
        Ok(n)
    }

    fn string(&mut self) -> Result<String, Error> {
        self.at += 1; // the opening quote
        let mut out = String::new();
        loop {
            // Plain bytes up to a quote, a backslash or a control character
            // are copied as they are: the input is a str, so whole UTF-8.
            let start = self.at;
            while let Some(&b) = self.bytes.get(self.at) {
                if b == b'"' || b == b'\\' || b < 0x20 {
                    break;
                }
                self.at += 1;
            }
            out.push_str(core::str::from_utf8(&self.bytes[start..self.at]).unwrap());
            match self.peek()? {
                b'"' => {
                    self.at += 1;
                    return Ok(out);
                }
                b'\\' => {
                    self.at += 1;
                    let escape = self.peek()?;
                    self.at += 1;
                    match escape {
                        b'"' => out.push('"'),
                        b'\\' => out.push('\\'),
                        b'/' => out.push('/'),
                        b'b' => out.push('\u{8}'),
                        b'f' => out.push('\u{c}'),
                        b'n' => out.push('\n'),
                        b'r' => out.push('\r'),
                        b't' => out.push('\t'),
                        b'u' => {
                            let mut code = self.hex4()?;
                            if (0xD800..0xDC00).contains(&code) {
                                // A high surrogate: its low half must follow.
                                if self.bytes.get(self.at..self.at + 2) != Some(b"\\u") {
                                    return Err(self.error(ErrorKind::String));
                                }
                                self.at += 2;
                                let low = self.hex4()?;
                                if !(0xDC00..0xE000).contains(&low) {
                                    return Err(self.error(ErrorKind::String));
                                }
                                code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00);
                            }
                            out.push(char::from_u32(code).ok_or(self.error(ErrorKind::String))?);
                        }
                        _ => return Err(self.error(ErrorKind::String)),
                    }
                }
                _ => return Err(self.error(ErrorKind::String)),
            }
        }
    }
}

impl Value {
    /// An object's field, or [`NULL`].
    pub fn get(&self, key: &str) -> &Value {
        match self {
            Value::Object(fields) => fields.iter().find(|(k, _)| k == key).map_or(&NULL, |(_, v)| v),
            _ => &NULL,
        }
    }

    /// An array's item, or [`NULL`].
    pub fn at(&self, index: usize) -> &Value {
        match self {
            Value::Array(items) => items.get(index).unwrap_or(&NULL),
            _ => &NULL,
        }
    }

    pub fn is_null(&self) -> bool {
        matches!(self, Value::Null)
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            _ => None,
        }
    }

    /// A whole number from 0 to 2^53, the integers an f64 holds exactly.
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Value::Number(n) if *n >= 0.0 && *n <= 9_007_199_254_740_992.0 && *n == (*n as u64) as f64 => {
                Some(*n as u64)
            }
            _ => None,
        }
    }

    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Value::Number(n) if n.abs() <= 9_007_199_254_740_992.0 && *n == (*n as i64) as f64 => {
                Some(*n as i64)
            }
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&[Value]> {
        match self {
            Value::Array(items) => Some(items),
            _ => None,
        }
    }

    pub fn as_object(&self) -> Option<&[(String, Value)]> {
        match self {
            Value::Object(fields) => Some(fields),
            _ => None,
        }
    }

    /// An object built from its fields, in this order.
    pub fn object<K: Into<String>>(fields: impl IntoIterator<Item = (K, Value)>) -> Value {
        Value::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
    }

    /// Sets a field of an object, replacing the first of that key or
    /// adding it at the end. Does nothing to anything else.
    pub fn set(&mut self, key: &str, value: Value) {
        if let Value::Object(fields) = self {
            match fields.iter_mut().find(|(k, _)| k == key) {
                Some((_, v)) => *v = value,
                None => fields.push((key.into(), value)),
            }
        }
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Value {
        Value::String(s.into())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Value {
        Value::String(s)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Value {
        Value::Bool(b)
    }
}

impl From<f64> for Value {
    fn from(n: f64) -> Value {
        Value::Number(n)
    }
}

impl From<u64> for Value {
    fn from(n: u64) -> Value {
        Value::Number(n as f64)
    }
}

impl From<i64> for Value {
    fn from(n: i64) -> Value {
        Value::Number(n as f64)
    }
}

impl From<Vec<Value>> for Value {
    fn from(items: Vec<Value>) -> Value {
        Value::Array(items)
    }
}

/// Writes `s` as a JSON string, quotes included.
pub fn write_string(out: &mut impl fmt::Write, s: &str) -> fmt::Result {
    out.write_char('"')?;
    let mut start = 0;
    for (i, c) in s.char_indices() {
        let escape = match c {
            '"' => "\\\"",
            '\\' => "\\\\",
            '\n' => "\\n",
            '\r' => "\\r",
            '\t' => "\\t",
            c if (c as u32) < 0x20 => "",
            _ => continue,
        };
        out.write_str(&s[start..i])?;
        if escape.is_empty() {
            write!(out, "\\u{:04x}", c as u32)?;
        } else {
            out.write_str(escape)?;
        }
        start = i + c.len_utf8();
    }
    out.write_str(&s[start..])?;
    out.write_char('"')
}

/// Compact JSON: no space between tokens. A whole number is written
/// without a fraction.
impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Value::Null => f.write_str("null"),
            Value::Bool(b) => f.write_str(if *b { "true" } else { "false" }),
            Value::Number(n) if *n == (*n as i64) as f64 && n.abs() < 1e15 => write!(f, "{}", *n as i64),
            Value::Number(n) => write!(f, "{n}"),
            Value::String(s) => write_string(f, s),
            Value::Array(items) => {
                f.write_str("[")?;
                for (i, item) in items.iter().enumerate() {
                    if i > 0 {
                        f.write_str(",")?;
                    }
                    write!(f, "{item}")?;
                }
                f.write_str("]")
            }
            Value::Object(fields) => {
                f.write_str("{")?;
                for (i, (key, value)) in fields.iter().enumerate() {
                    if i > 0 {
                        f.write_str(",")?;
                    }
                    write_string(f, key)?;
                    write!(f, ":{value}")?;
                }
                f.write_str("}")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use alloc::string::ToString;
    use alloc::vec;

    fn kind(text: &str) -> ErrorKind {
        parse(text).unwrap_err().kind
    }

    #[test]
    fn reads_every_kind_of_value() {
        let v = parse(r#" {"a": [1, -2.5, 3e2, true, false, null], "b": {"c": "d"}} "#).unwrap();
        assert_eq!(v.get("a").at(0).as_u64(), Some(1));
        assert_eq!(v.get("a").at(1).as_f64(), Some(-2.5));
        assert_eq!(v.get("a").at(2).as_u64(), Some(300));
        assert_eq!(v.get("a").at(3).as_bool(), Some(true));
        assert_eq!(v.get("a").at(4).as_bool(), Some(false));
        assert!(v.get("a").at(5).is_null());
        assert_eq!(v.get("b").get("c").as_str(), Some("d"));
        assert!(v.get("missing").get("deeper").is_null());
        assert_eq!(parse("[]").unwrap(), Value::Array(vec![]));
        assert_eq!(parse("{}").unwrap(), Value::Object(vec![]));
    }

    #[test]
    fn strings_unescape() {
        let v = parse(r#""a\"b\\c\/d\n\t\u00e9\ud83d\ude00 é""#).unwrap();
        assert_eq!(v.as_str(), Some("a\"b\\c/d\n\té😀 é"));
    }

    #[test]
    fn refuses_what_rfc_8259_refuses() {
        assert_eq!(kind("[1,]"), ErrorKind::Unexpected);
        assert_eq!(kind("{\"a\":1,}"), ErrorKind::Unexpected);
        assert_eq!(kind("01"), ErrorKind::Number);
        assert_eq!(kind("1."), ErrorKind::Number);
        assert_eq!(kind("-"), ErrorKind::Number);
        assert_eq!(kind("1e"), ErrorKind::Number);
        assert_eq!(kind("1e999"), ErrorKind::Number);
        assert_eq!(kind("\"\\ud83d\""), ErrorKind::String);
        assert_eq!(kind("\"\\udc00\""), ErrorKind::String);
        assert_eq!(kind("\"a\nb\""), ErrorKind::String);
        assert_eq!(kind("\"\\x\""), ErrorKind::String);
        assert_eq!(kind("{1:2}"), ErrorKind::Unexpected);
        assert_eq!(kind("tru"), ErrorKind::End);
        assert_eq!(kind("nul!"), ErrorKind::Unexpected);
        assert_eq!(kind("[1"), ErrorKind::End);
        assert_eq!(kind("\"abc"), ErrorKind::End);
        assert_eq!(kind("1 2"), ErrorKind::Trailing);
        assert_eq!(kind(""), ErrorKind::End);
    }

    #[test]
    fn deep_nesting_is_an_error_not_a_crash() {
        let ok = "[".repeat(MAX_DEPTH) + &"]".repeat(MAX_DEPTH);
        assert!(parse(&ok).is_ok());
        let deep = "[".repeat(100_000);
        assert_eq!(kind(&deep), ErrorKind::TooDeep);
    }

    #[test]
    fn written_back_as_read() {
        for text in [
            r#"{"b":1,"a":[true,null,"x"],"c":{"d":-2.5}}"#,
            r#""quote \" backslash \\ line \n tab \t bell \u0007 é""#,
            "[0,-1,1000000,0.125,1e+300]",
        ] {
            let v = parse(text).unwrap();
            assert_eq!(parse(&v.to_string()).unwrap(), v, "{text}");
        }
        assert_eq!(parse("1.0").unwrap().to_string(), "1");
        assert_eq!(Value::from("a\u{1}").to_string(), "\"a\\u0001\"");
    }

    #[test]
    fn built_and_changed() {
        let mut v = Value::object([("model", Value::from("m")), ("n", Value::from(2u64))]);
        v.set("n", 3u64.into());
        v.set("stream", true.into());
        assert_eq!(v.to_string(), r#"{"model":"m","n":3,"stream":true}"#);
    }

    #[test]
    fn whole_numbers_only_where_exact() {
        assert_eq!(parse("2.5").unwrap().as_u64(), None);
        assert_eq!(parse("-1").unwrap().as_u64(), None);
        assert_eq!(parse("-1").unwrap().as_i64(), Some(-1));
        assert_eq!(parse("1e20").unwrap().as_u64(), None);
    }
}