use std::fmt::Write as _;
use crate::escape::{hex, push_json_string};
pub struct Object<'a> {
out: &'a mut String,
empty: bool,
}
impl<'a> Object<'a> {
pub fn new(out: &'a mut String) -> Self {
out.push('{');
Self { out, empty: true }
}
fn key(&mut self, key: &str) {
if !self.empty {
self.out.push(',');
}
self.empty = false;
push_json_string(self.out, key);
self.out.push(':');
}
pub fn str(&mut self, key: &str, value: &str) {
self.key(key);
push_json_string(self.out, value);
}
pub fn u64(&mut self, key: &str, value: u64) {
self.key(key);
let _ = write!(self.out, "{value}");
}
pub fn i64(&mut self, key: &str, value: i64) {
self.key(key);
let _ = write!(self.out, "{value}");
}
pub fn bool(&mut self, key: &str, value: bool) {
self.key(key);
self.out.push_str(if value { "true" } else { "false" });
}
pub fn raw(&mut self, key: &str, value: &str) {
self.key(key);
self.out.push_str(value);
}
pub fn bytes(&mut self, key: &str, value: &[u8]) {
let shown = String::from_utf8_lossy(value);
self.str(key, &shown);
if shown.as_bytes() != value {
self.str(&format!("{key}_hex"), &hex(value));
}
}
pub fn strings(&mut self, key: &str, values: &[&str]) {
self.key(key);
self.out.push('[');
for (i, v) in values.iter().enumerate() {
if i > 0 {
self.out.push(',');
}
push_json_string(self.out, v);
}
self.out.push(']');
}
pub fn u64s(&mut self, key: &str, values: &[u64]) {
self.key(key);
self.out.push('[');
for (i, v) in values.iter().enumerate() {
if i > 0 {
self.out.push(',');
}
self.out.push_str(&v.to_string());
}
self.out.push(']');
}
pub fn obj(&mut self, key: &str) -> Object<'_> {
self.key(key);
Object::new(self.out)
}
pub fn arr(&mut self, key: &str) -> Array<'_> {
self.key(key);
Array::new(self.out)
}
pub fn end(self) {
self.out.push('}');
}
}
pub struct Array<'a> {
out: &'a mut String,
empty: bool,
}
impl<'a> Array<'a> {
pub fn new(out: &'a mut String) -> Self {
out.push('[');
Self { out, empty: true }
}
pub fn obj(&mut self) -> Object<'_> {
if !self.empty {
self.out.push(',');
}
self.empty = false;
Object::new(self.out)
}
pub fn end(self) {
self.out.push(']');
}
}
#[cfg(test)]
mod tests {
use super::{Array, Object};
#[test]
fn an_object_carries_the_value_kinds_a_document_holds() {
let mut out = String::new();
let mut o = Object::new(&mut out);
o.u64("blocks", 16384);
o.i64("created", -1);
o.bool("clean", true);
o.str("uuid", "f0e1");
o.strings("features", &["extent", "64bit"]);
o.raw("scan", "{\"clean\":true}");
o.end();
assert_eq!(
out,
r#"{"blocks":16384,"created":-1,"clean":true,"uuid":"f0e1","features":["extent","64bit"],"scan":{"clean":true}}"#
);
}
#[test]
fn every_string_a_document_carries_goes_through_the_escaper() {
let mut out = String::new();
let mut o = Object::new(&mut out);
o.str("label\u{1b}", "photo\u{202e}gnp.exe");
o.strings("features", &["a\u{9b}[31m"]);
o.end();
assert_eq!(
out,
r#"{"label\u001b":"photo\u202egnp.exe","features":["a\u009b[31m"]}"#
);
}
#[test]
fn a_name_that_is_not_text_carries_its_bytes_as_well() {
let mut out = String::new();
let mut o = Object::new(&mut out);
o.bytes("name", b"/etc/hostname");
o.end();
assert_eq!(
out, r#"{"name":"/etc/hostname"}"#,
"a name that is text says so once"
);
let mut out = String::new();
let mut o = Object::new(&mut out);
o.bytes("name", b"/od\xffd");
o.end();
assert_eq!(
out,
r#"{"name":"/od\u{fffd}d","name_hex":"2f6f64ff64"}"#.replace("\\u{fffd}", "\u{fffd}")
);
}
#[test]
fn nested_objects_and_arrays() {
let mut out = String::new();
let mut o = Object::new(&mut out);
let mut inner = o.obj("features");
inner.u64("unknown", 0);
inner.end();
let mut groups = o.arr("groups");
let mut g = groups.obj();
g.u64("group", 0);
g.end();
let mut g = groups.obj();
g.u64("group", 1);
g.end();
groups.end();
o.end();
assert_eq!(
out,
r#"{"features":{"unknown":0},"groups":[{"group":0},{"group":1}]}"#
);
}
#[test]
fn an_empty_object_and_an_empty_array_are_still_well_formed() {
let mut out = String::new();
Object::new(&mut out).end();
assert_eq!(out, "{}");
let mut out = String::new();
Array::new(&mut out).end();
assert_eq!(out, "[]");
}
}