1//! The JSON writer.2//!3//! The output is compact: no spaces, no newline, keys in the sorted order that4//! [`Value::Object`] already holds. Only `"`, `\` and the bytes below 0x20 are5//! escaped, so text stays readable and stays UTF-8.6//!7//! JSON has no infinity, so a non-finite float writes as `null`. A float whose8//! value is whole writes as an integer and therefore reads back as9//! [`Value::Int`].1011usecrate::value::Value;1213/// The hex digits used by `\u00XX`.14constHEX: [char; 16] = [15 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',16 ];1718/// Appends the compact JSON form of `value` to `out`.19pubfnencode(value: &Value, out: &mutString) {20match value {21Value::Null => out.push_str("null"),22Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),23Value::Int(n) => out.push_str(&n.to_string()),24Value::Float(x) => {25// Rust's Display gives the shortest form that reads back as the26// same bits.27if x.is_finite() {28 out.push_str(&x.to_string());29 } else {30 out.push_str("null");31 }32 }33Value::Str(s) => write_string(s, out),34Value::Array(items) => {35 out.push('[');36for (index, item) in items.iter().enumerate() {37if index > 0 {38 out.push(',');39 }40encode(item, out);41 }42 out.push(']');43 }44Value::Object(map) => {45 out.push('{');46for (index, (key, value)) in map.iter().enumerate() {47if index > 0 {48 out.push(',');49 }50write_string(key, out);51 out.push(':');52encode(value, out);53 }54 out.push('}');55 }56 }57 }5859/// Appends `value` as a JSON string.60fnwrite_string(value: &str, out: &mutString) {61 out.push('"');62for c in value.chars() {63match c {64 '"' => out.push_str("\\\""),65 '\\' => out.push_str("\\\\"),66 '\u{08}' => out.push_str("\\b"),67 '\u{0c}' => out.push_str("\\f"),68 '\n' => out.push_str("\\n"),69 '\r' => out.push_str("\\r"),70 '\t' => out.push_str("\\t"),71 c => {72let code = c as u32;73if code < 0x20 {74 out.push_str("\\u00");75 out.push(HEX[((code >> 4) & 0xf) as usize]);76 out.push(HEX[(code & 0xf) as usize]);77 } else {78 out.push(c);79 }80 }81 }82 }83 out.push('"');84 }8586/// The compact JSON form of `value`.87pubfnto_string(value: &Value) -> String {88letmut out = String::new();89encode(value, &mut out);90 out91 }