cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
//! Minimal JSON output. A small `Json` value type with a builder and a correct
//! serializer, so commands can emit structured `--json` output without a serde
//! dependency and without hand-assembling strings (which is where escaping bugs
//! live). This is output-only — for *parsing* config JSON, see [`crate::config`].
//!
//! ```ignore
//! use cornerstone::prelude::*;
//! let doc = Json::object()
//!     .set("name", Json::str("demo"))
//!     .set("count", Json::from(3))
//!     .set("tags", Json::array(vec![Json::str("a"), Json::str("b")]));
//! println!("{}", doc.to_string_pretty());
//! ```

use std::collections::BTreeMap;

/// A JSON value.
#[derive(Debug, Clone)]
pub enum Json {
    Null,
    Bool(bool),
    Num(f64),
    Str(String),
    Array(Vec<Json>),
    Object(BTreeMap<String, Json>),
}

impl Json {
    pub fn str<S: Into<String>>(s: S) -> Json {
        Json::Str(s.into())
    }
    pub fn array(items: Vec<Json>) -> Json {
        Json::Array(items)
    }
    pub fn object() -> Json {
        Json::Object(BTreeMap::new())
    }
    /// Insert into an object (no-op if this isn't an object). Chainable.
    pub fn set<K: Into<String>>(mut self, key: K, value: Json) -> Json {
        if let Json::Object(ref mut m) = self {
            m.insert(key.into(), value);
        }
        self
    }
    /// Push onto an array (no-op if this isn't an array). Chainable.
    pub fn push(mut self, value: Json) -> Json {
        if let Json::Array(ref mut a) = self {
            a.push(value);
        }
        self
    }

    /// Serialize compactly (single line).
    pub fn to_string_compact(&self) -> String {
        let mut out = String::new();
        self.write(&mut out, None, 0);
        out
    }
    /// Serialize with two-space indentation.
    pub fn to_string_pretty(&self) -> String {
        let mut out = String::new();
        self.write(&mut out, Some(2), 0);
        out
    }

    fn write(&self, out: &mut String, indent: Option<usize>, depth: usize) {
        match self {
            Json::Null => out.push_str("null"),
            Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
            Json::Num(n) => {
                if n.fract() == 0.0 && n.is_finite() {
                    out.push_str(&format!("{}", *n as i64));
                } else {
                    out.push_str(&format!("{}", n));
                }
            }
            Json::Str(s) => write_json_string(out, s),
            Json::Array(items) => {
                if items.is_empty() {
                    out.push_str("[]");
                    return;
                }
                out.push('[');
                for (i, item) in items.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    newline_indent(out, indent, depth + 1);
                    item.write(out, indent, depth + 1);
                }
                newline_indent(out, indent, depth);
                out.push(']');
            }
            Json::Object(map) => {
                if map.is_empty() {
                    out.push_str("{}");
                    return;
                }
                out.push('{');
                for (i, (k, v)) in map.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    newline_indent(out, indent, depth + 1);
                    write_json_string(out, k);
                    out.push(':');
                    if indent.is_some() {
                        out.push(' ');
                    }
                    v.write(out, indent, depth + 1);
                }
                newline_indent(out, indent, depth);
                out.push('}');
            }
        }
    }
}

impl From<i64> for Json {
    fn from(n: i64) -> Self {
        Json::Num(n as f64)
    }
}
impl From<f64> for Json {
    fn from(n: f64) -> Self {
        Json::Num(n)
    }
}
impl From<bool> for Json {
    fn from(b: bool) -> Self {
        Json::Bool(b)
    }
}
impl From<&str> for Json {
    fn from(s: &str) -> Self {
        Json::Str(s.to_string())
    }
}
impl From<String> for Json {
    fn from(s: String) -> Self {
        Json::Str(s)
    }
}

fn newline_indent(out: &mut String, indent: Option<usize>, depth: usize) {
    if let Some(n) = indent {
        out.push('\n');
        for _ in 0..(n * depth) {
            out.push(' ');
        }
    }
}

fn write_json_string(out: &mut String, s: &str) {
    out.push('"');
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
}

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

    #[test]
    fn scalars() {
        assert_eq!(Json::Null.to_string_compact(), "null");
        assert_eq!(Json::from(true).to_string_compact(), "true");
        assert_eq!(Json::from(42_i64).to_string_compact(), "42");
        assert_eq!(Json::from(3.5_f64).to_string_compact(), "3.5");
    }

    #[test]
    fn string_escaping() {
        assert_eq!(Json::str("a\"b").to_string_compact(), r#""a\"b""#);
        assert_eq!(Json::str("tab\there").to_string_compact(), r#""tab\there""#);
        assert_eq!(Json::str("new\nline").to_string_compact(), r#""new\nline""#);
    }

    #[test]
    fn nested_structure() {
        let doc = Json::object()
            .set("a", Json::from(1_i64))
            .set("b", Json::array(vec![Json::from(2_i64), Json::from(3_i64)]));
        // BTreeMap orders keys, so a before b deterministically.
        assert_eq!(doc.to_string_compact(), r#"{"a":1,"b":[2,3]}"#);
    }

    #[test]
    fn empty_containers() {
        assert_eq!(Json::object().to_string_compact(), "{}");
        assert_eq!(Json::array(vec![]).to_string_compact(), "[]");
    }

    #[test]
    fn pretty_has_newlines() {
        let doc = Json::object().set("x", Json::from(1_i64));
        assert!(doc.to_string_pretty().contains('\n'));
    }
}