pub fn quote(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"),
'\u{08}' => out.push_str("\\b"),
'\u{0c}' => out.push_str("\\f"),
c if (c as u32) < 0x20 => {
out.push_str(&format!("\\u{:04x}", c as u32));
}
c => out.push(c),
}
}
out.push('"');
}
pub struct Obj {
buf: String,
empty: bool,
}
impl Default for Obj {
fn default() -> Obj {
Obj::new()
}
}
impl Obj {
pub fn new() -> Obj {
Obj {
buf: String::from("{"),
empty: true,
}
}
fn key(&mut self, key: &str) {
if !self.empty {
self.buf.push(',');
}
self.empty = false;
quote(&mut self.buf, key);
self.buf.push(':');
}
pub fn str(&mut self, key: &str, value: &str) -> &mut Obj {
self.key(key);
let mut v = String::new();
quote(&mut v, value);
self.buf.push_str(&v);
self
}
pub fn str_opt(&mut self, key: &str, value: &str) -> &mut Obj {
if value.is_empty() {
return self;
}
self.str(key, value)
}
pub fn num(&mut self, key: &str, value: i64) -> &mut Obj {
self.key(key);
self.buf.push_str(&value.to_string());
self
}
pub fn bool(&mut self, key: &str, value: bool) -> &mut Obj {
self.key(key);
self.buf.push_str(if value { "true" } else { "false" });
self
}
pub fn strs<'a>(&mut self, key: &str, values: impl Iterator<Item = &'a str>) -> &mut Obj {
self.key(key);
self.buf.push('[');
for (i, v) in values.enumerate() {
if i > 0 {
self.buf.push(',');
}
let mut q = String::new();
quote(&mut q, v);
self.buf.push_str(&q);
}
self.buf.push(']');
self
}
pub fn nums(&mut self, key: &str, values: impl Iterator<Item = i64>) -> &mut Obj {
self.key(key);
self.buf.push('[');
for (i, v) in values.enumerate() {
if i > 0 {
self.buf.push(',');
}
self.buf.push_str(&v.to_string());
}
self.buf.push(']');
self
}
pub fn obj(&mut self, key: &str, value: Obj) -> &mut Obj {
self.key(key);
self.buf.push_str(&value.finish());
self
}
pub fn raw(&mut self, key: &str, json: &str) -> &mut Obj {
self.key(key);
self.buf.push_str(json);
self
}
pub fn finish(self) -> String {
let mut s = self.buf;
s.push('}');
s
}
}
#[cfg(test)]
mod tests {
use super::*;
fn q(s: &str) -> String {
let mut out = String::new();
quote(&mut out, s);
out
}
#[test]
fn quoting_escapes_what_json_requires() {
assert_eq!(q("plain"), r#""plain""#);
assert_eq!(q(r#"say "hi""#), r#""say \"hi\"""#);
assert_eq!(q(r"back\slash"), r#""back\\slash""#);
assert_eq!(q("two\nlines"), r#""two\nlines""#);
assert_eq!(q("tab\there"), r#""tab\there""#);
}
#[test]
fn control_characters_become_unicode_escapes() {
assert_eq!(q("\u{1f}"), "\"\\u001f\"");
assert_eq!(q("\u{1e}"), "\"\\u001e\"");
assert_eq!(q("\u{00}"), "\"\\u0000\"");
}
#[test]
fn non_ascii_is_passed_through_not_escaped() {
assert_eq!(q("Přílíš žluťoučký kůň"), "\"Přílíš žluťoučký kůň\"");
}
#[test]
fn objects_place_their_own_commas() {
let mut o = Obj::new();
o.str("a", "1").num("b", 2).bool("c", true);
assert_eq!(o.finish(), r#"{"a":"1","b":2,"c":true}"#);
}
#[test]
fn an_empty_object_is_still_valid() {
assert_eq!(Obj::new().finish(), "{}");
}
#[test]
fn arrays_and_nesting() {
let mut inner = Obj::new();
inner.num("col", 0);
let mut o = Obj::new();
o.strs("parents", ["aa", "bb"].into_iter())
.nums("counts", [1i64, 2].into_iter())
.obj("graph", inner);
assert_eq!(
o.finish(),
r#"{"parents":["aa","bb"],"counts":[1,2],"graph":{"col":0}}"#
);
}
#[test]
fn empty_arrays_are_emitted_as_empty_not_omitted() {
let mut o = Obj::new();
o.strs("refs", std::iter::empty());
assert_eq!(o.finish(), r#"{"refs":[]}"#);
}
#[test]
fn default_produces_the_same_valid_object_as_new() {
let mut o = Obj::default();
o.num("a", 1);
assert_eq!(o.finish(), r#"{"a":1}"#);
assert_eq!(Obj::default().finish(), "{}");
}
#[test]
fn str_opt_omits_empty_values() {
let mut o = Obj::new();
o.str_opt("a", "").str_opt("b", "x");
assert_eq!(o.finish(), r#"{"b":"x"}"#);
}
}