use serde_json::Value;
use std::fmt::Write;
#[derive(Debug, Default, Clone, Copy)]
pub struct EncodeOptions {
pub pretty: bool,
}
pub fn encode(v: &Value) -> String {
let mut out = String::new();
encode_into(v, &mut out, EncodeOptions::default());
out
}
pub fn encode_pretty(v: &Value) -> String {
let mut out = String::new();
encode_into(v, &mut out, EncodeOptions { pretty: true });
out
}
pub fn encode_into(v: &Value, out: &mut String, opts: EncodeOptions) {
write_value(v, out, opts, 0);
}
pub fn encode_string(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'/' => out.push_str("\\/"),
'\x08' => out.push_str("\\b"),
'\x09' => out.push_str("\\t"),
'\x0a' => out.push_str("\\n"),
'\x0c' => out.push_str("\\f"),
'\x0d' => out.push_str("\\r"),
c if (c as u32) < 0x20 => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c if (c as u32) < 0x80 => {
out.push(c);
}
c => {
let cp = c as u32;
if cp <= 0xFFFF {
let _ = write!(out, "\\u{:04x}", cp);
} else {
let v = cp - 0x10000;
let high = 0xD800 + (v >> 10);
let low = 0xDC00 + (v & 0x3FF);
let _ = write!(out, "\\u{:04x}\\u{:04x}", high, low);
}
}
}
}
out.push('"');
}
fn write_value(v: &Value, out: &mut String, opts: EncodeOptions, depth: usize) {
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.to_string());
}
Value::String(s) => encode_string(s, out),
Value::Array(arr) => {
if arr.is_empty() {
out.push_str("[]");
return;
}
out.push('[');
for (i, item) in arr.iter().enumerate() {
if i > 0 {
out.push(',');
}
if opts.pretty {
out.push('\n');
push_indent(out, depth + 1);
}
write_value(item, out, opts, depth + 1);
}
if opts.pretty {
out.push('\n');
push_indent(out, depth);
}
out.push(']');
}
Value::Object(map) => {
if map.is_empty() {
out.push_str("[]");
return;
}
out.push('{');
for (i, (k, val)) in map.iter().enumerate() {
if i > 0 {
out.push(',');
}
if opts.pretty {
out.push('\n');
push_indent(out, depth + 1);
}
encode_string(k, out);
out.push(':');
if opts.pretty {
out.push(' ');
}
write_value(val, out, opts, depth + 1);
}
if opts.pretty {
out.push('\n');
push_indent(out, depth);
}
out.push('}');
}
}
}
fn push_indent(out: &mut String, depth: usize) {
for _ in 0..depth {
out.push_str(" ");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encodes_string_like_php_json_encode() {
let mut out = String::new();
encode_string("hello", &mut out);
assert_eq!(out, "\"hello\"");
let mut out = String::new();
encode_string("https://example.com/x", &mut out);
assert_eq!(out, "\"https:\\/\\/example.com\\/x\"");
let mut out = String::new();
encode_string("ñ", &mut out);
assert_eq!(out, "\"\\u00f1\"");
let mut out = String::new();
encode_string("\"\\\n\t", &mut out);
assert_eq!(out, "\"\\\"\\\\\\n\\t\"");
let mut out = String::new();
encode_string("😀", &mut out);
assert_eq!(out, "\"\\ud83d\\ude00\"");
}
#[test]
fn compact_object_matches_php_default() {
let v = serde_json::json!({ "a": 1, "b": [true, false, null] });
assert_eq!(encode(&v), r#"{"a":1,"b":[true,false,null]}"#);
}
#[test]
fn compact_empty_object_becomes_empty_array() {
let v = serde_json::json!({ "k": {} });
assert_eq!(encode(&v), r#"{"k":[]}"#);
}
#[test]
fn pretty_empty_array() {
assert_eq!(encode_pretty(&serde_json::json!([])), "[]");
}
#[test]
fn pretty_string_array_matches_php() {
let v = serde_json::json!(["Pest\\Plugins\\Cache", "Pest\\Arch\\Plugin"]);
assert_eq!(
encode_pretty(&v),
"[\n \"Pest\\\\Plugins\\\\Cache\",\n \"Pest\\\\Arch\\\\Plugin\"\n]"
);
}
#[test]
fn pretty_slash_and_backslash_escape() {
let v = serde_json::json!(["a/b", "x\\y"]);
assert_eq!(encode_pretty(&v), "[\n \"a\\/b\",\n \"x\\\\y\"\n]");
}
#[test]
fn pretty_object_with_nested_array_matches_php() {
let v = serde_json::json!({ "a": 1, "b": ["x", "y"] });
assert_eq!(
encode_pretty(&v),
"{\n \"a\": 1,\n \"b\": [\n \"x\",\n \"y\"\n ]\n}"
);
}
#[test]
fn pretty_empty_object_becomes_empty_array() {
let v = serde_json::json!({ "k": {} });
assert_eq!(encode_pretty(&v), "{\n \"k\": []\n}");
}
}