#![deny(unsafe_code)]
#![allow(dead_code)]
use super::value::{Member, Value};
pub fn to_compact(value: &Value) -> String {
let mut out = String::new();
write_compact(value, &mut out);
out
}
enum Frame<'a> {
Arr(std::slice::Iter<'a, Value>),
Obj(std::slice::Iter<'a, Member>),
}
pub fn write_compact(value: &Value, out: &mut String) {
let mut stack: Vec<(Frame<'_>, bool)> = Vec::new();
let mut next = Some(value);
loop {
if let Some(v) = next.take() {
match v {
Value::Array(items) => {
out.push('[');
stack.push((Frame::Arr(items.iter()), false));
}
Value::Object(members) => {
out.push('{');
stack.push((Frame::Obj(members.iter()), false));
}
scalar => write_scalar(scalar, out),
}
}
match stack.last_mut() {
None => return,
Some((frame, seen)) => {
if !advance(frame, seen, out, &mut next) {
stack.pop();
}
}
}
}
}
fn advance<'a>(
frame: &mut Frame<'a>,
seen: &mut bool,
out: &mut String,
next: &mut Option<&'a Value>,
) -> bool {
let value = match frame {
Frame::Arr(it) => match it.next() {
Some(v) => v,
None => {
out.push(']');
return false;
}
},
Frame::Obj(it) => match it.next() {
Some(m) => {
if *seen {
out.push(',');
}
*seen = true;
escape_into(&m.key, out);
out.push(':');
*next = Some(&m.value);
return true;
}
None => {
out.push('}');
return false;
}
},
};
if *seen {
out.push(',');
}
*seen = true;
*next = Some(value);
true
}
fn write_scalar(v: &Value, out: &mut String) {
match v {
Value::Null => out.push_str("null"),
Value::Bool(true) => out.push_str("true"),
Value::Bool(false) => out.push_str("false"),
Value::Number(n) => out.push_str(n.text()),
Value::Str(s) => escape_into(s, out),
Value::Array(_) => out.push_str("[]"),
Value::Object(_) => out.push_str("{}"),
}
}
pub fn escape_into(s: &str, out: &mut String) {
out.push('"');
if !s.bytes().any(needs_escape) {
out.push_str(s);
out.push('"');
return;
}
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => push_hex(c as u32, out),
c => out.push(c),
}
}
out.push('"');
}
pub fn escape(s: &str) -> String {
let mut out = String::new();
escape_into(s, &mut out);
out
}
fn needs_escape(b: u8) -> bool {
b < 0x20 || b == b'"' || b == b'\\'
}
fn push_hex(c: u32, out: &mut String) {
const HEX: [u8; 16] = *b"0123456789abcdef";
out.push_str("\\u00");
out.push(HEX[(c >> 4 & 0xf) as usize] as char);
out.push(HEX[(c & 0xf) as usize] as char);
}
#[cfg(test)]
#[path = "write_tests.rs"]
mod tests;