use std::collections::BTreeMap;
#[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())
}
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
}
pub fn push(mut self, value: Json) -> Json {
if let Json::Array(ref mut a) = self {
a.push(value);
}
self
}
pub fn to_string_compact(&self) -> String {
let mut out = String::new();
self.write(&mut out, None, 0);
out
}
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)]));
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'));
}
}