1use std::collections::BTreeMap;
16
17#[derive(Debug, Clone)]
19pub enum Json {
20 Null,
21 Bool(bool),
22 Num(f64),
23 Str(String),
24 Array(Vec<Json>),
25 Object(BTreeMap<String, Json>),
26}
27
28impl Json {
29 pub fn str<S: Into<String>>(s: S) -> Json {
30 Json::Str(s.into())
31 }
32 pub fn array(items: Vec<Json>) -> Json {
33 Json::Array(items)
34 }
35 pub fn object() -> Json {
36 Json::Object(BTreeMap::new())
37 }
38 pub fn set<K: Into<String>>(mut self, key: K, value: Json) -> Json {
40 if let Json::Object(ref mut m) = self {
41 m.insert(key.into(), value);
42 }
43 self
44 }
45 pub fn push(mut self, value: Json) -> Json {
47 if let Json::Array(ref mut a) = self {
48 a.push(value);
49 }
50 self
51 }
52
53 pub fn to_string_compact(&self) -> String {
55 let mut out = String::new();
56 self.write(&mut out, None, 0);
57 out
58 }
59 pub fn to_string_pretty(&self) -> String {
61 let mut out = String::new();
62 self.write(&mut out, Some(2), 0);
63 out
64 }
65
66 fn write(&self, out: &mut String, indent: Option<usize>, depth: usize) {
67 match self {
68 Json::Null => out.push_str("null"),
69 Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
70 Json::Num(n) => {
71 if n.fract() == 0.0 && n.is_finite() {
72 out.push_str(&format!("{}", *n as i64));
73 } else {
74 out.push_str(&format!("{}", n));
75 }
76 }
77 Json::Str(s) => write_json_string(out, s),
78 Json::Array(items) => {
79 if items.is_empty() {
80 out.push_str("[]");
81 return;
82 }
83 out.push('[');
84 for (i, item) in items.iter().enumerate() {
85 if i > 0 {
86 out.push(',');
87 }
88 newline_indent(out, indent, depth + 1);
89 item.write(out, indent, depth + 1);
90 }
91 newline_indent(out, indent, depth);
92 out.push(']');
93 }
94 Json::Object(map) => {
95 if map.is_empty() {
96 out.push_str("{}");
97 return;
98 }
99 out.push('{');
100 for (i, (k, v)) in map.iter().enumerate() {
101 if i > 0 {
102 out.push(',');
103 }
104 newline_indent(out, indent, depth + 1);
105 write_json_string(out, k);
106 out.push(':');
107 if indent.is_some() {
108 out.push(' ');
109 }
110 v.write(out, indent, depth + 1);
111 }
112 newline_indent(out, indent, depth);
113 out.push('}');
114 }
115 }
116 }
117}
118
119impl From<i64> for Json {
120 fn from(n: i64) -> Self {
121 Json::Num(n as f64)
122 }
123}
124impl From<f64> for Json {
125 fn from(n: f64) -> Self {
126 Json::Num(n)
127 }
128}
129impl From<bool> for Json {
130 fn from(b: bool) -> Self {
131 Json::Bool(b)
132 }
133}
134impl From<&str> for Json {
135 fn from(s: &str) -> Self {
136 Json::Str(s.to_string())
137 }
138}
139impl From<String> for Json {
140 fn from(s: String) -> Self {
141 Json::Str(s)
142 }
143}
144
145fn newline_indent(out: &mut String, indent: Option<usize>, depth: usize) {
146 if let Some(n) = indent {
147 out.push('\n');
148 for _ in 0..(n * depth) {
149 out.push(' ');
150 }
151 }
152}
153
154fn write_json_string(out: &mut String, s: &str) {
155 out.push('"');
156 for ch in s.chars() {
157 match ch {
158 '"' => out.push_str("\\\""),
159 '\\' => out.push_str("\\\\"),
160 '\n' => out.push_str("\\n"),
161 '\r' => out.push_str("\\r"),
162 '\t' => out.push_str("\\t"),
163 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
164 c => out.push(c),
165 }
166 }
167 out.push('"');
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn scalars() {
176 assert_eq!(Json::Null.to_string_compact(), "null");
177 assert_eq!(Json::from(true).to_string_compact(), "true");
178 assert_eq!(Json::from(42_i64).to_string_compact(), "42");
179 assert_eq!(Json::from(3.5_f64).to_string_compact(), "3.5");
180 }
181
182 #[test]
183 fn string_escaping() {
184 assert_eq!(Json::str("a\"b").to_string_compact(), r#""a\"b""#);
185 assert_eq!(Json::str("tab\there").to_string_compact(), r#""tab\there""#);
186 assert_eq!(Json::str("new\nline").to_string_compact(), r#""new\nline""#);
187 }
188
189 #[test]
190 fn nested_structure() {
191 let doc = Json::object()
192 .set("a", Json::from(1_i64))
193 .set("b", Json::array(vec![Json::from(2_i64), Json::from(3_i64)]));
194 assert_eq!(doc.to_string_compact(), r#"{"a":1,"b":[2,3]}"#);
196 }
197
198 #[test]
199 fn empty_containers() {
200 assert_eq!(Json::object().to_string_compact(), "{}");
201 assert_eq!(Json::array(vec![]).to_string_compact(), "[]");
202 }
203
204 #[test]
205 fn pretty_has_newlines() {
206 let doc = Json::object().set("x", Json::from(1_i64));
207 assert!(doc.to_string_pretty().contains('\n'));
208 }
209}