use super::Value; fn escape_char(c: char, out: &mut String) { match c { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), '\u{8}' => out.push_str("\\b"), '\u{c}' => out.push_str("\\f"), c if (c as u32) < 0x20 || c == '\u{2028}' || c == '\u{2029}' => { out.push_str(&format!("\\u{:04x}", c as u32)) } c => out.push(c), } } fn quoted(text: &str) -> String { let mut out = String::with_capacity(text.len() + 2); out.push('"'); text.chars().for_each(|c| escape_char(c, &mut out)); out.push('"'); out } fn number(n: f64) -> String { if n.is_finite() { // Rust's Display is the shortest representation that round-trips. format!("{n}") } else { "null".to_string() } } fn joined(parts: impl Iterator) -> String { parts.collect::>().join(",") } /// Compact, single-line JSON. pub fn render(value: &Value) -> String { match value { Value::Null => "null".to_string(), Value::Bool(b) => b.to_string(), Value::Number(n) => number(*n), Value::String(s) => quoted(s), Value::Array(items) => format!("[{}]", joined(items.iter().map(render))), Value::Object(members) => { let parts = members.iter().map(|(k, v)| format!("{}:{}", quoted(k), render(v))); format!("{{{}}}", joined(parts)) } } }