Skip to main content

zero_client/json/
stringify.rs

1use super::value::RECURSION_DEPTH;
2use super::{Value, number};
3use crate::map;
4
5/// Encodes a value as `JSON.stringify` does: the same string escaping and
6/// number formatting, with non-finite numbers written as `null`.
7///
8/// Object keys are written in the object's order, which is JS property order,
9/// so the output is what `JSON.stringify` writes for the same object.
10pub fn stringify(value: &Value) -> String {
11    let mut out = String::new();
12    write(value, &mut out);
13    out
14}
15
16/// Appends `value` as JSON text.
17pub fn write(value: &Value, out: &mut String) {
18    write_within(value, out, RECURSION_DEPTH);
19}
20
21/// [`write`], recursing `depth` levels deep.
22fn write_within(value: &Value, out: &mut String, depth: usize) {
23    match value {
24        Value::Array(a) if depth > 0 => {
25            out.push('[');
26            for (i, e) in a.iter().enumerate() {
27                if i > 0 {
28                    out.push(',');
29                }
30                write_within(e, out, depth - 1);
31            }
32            out.push(']');
33        }
34        Value::Object(o) if depth > 0 => {
35            out.push('{');
36            for (i, (k, v)) in o.iter().enumerate() {
37                if i > 0 {
38                    out.push(',');
39                }
40                write_string(k, out);
41                out.push(':');
42                write_within(v, out, depth - 1);
43            }
44            out.push('}');
45        }
46        Value::Array(_) | Value::Object(_) => write_iteratively(value, out),
47        scalar => write_scalar(scalar, out),
48    }
49}
50
51fn write_iteratively(value: &Value, out: &mut String) {
52    enum Open<'a> {
53        Array(std::slice::Iter<'a, Value>),
54        Object(map::Iter<'a, Value>),
55    }
56    // The arrays and objects being written, each with whether it has
57    // written an element yet.
58    let mut stack: Vec<(Open, bool)> = Vec::new();
59    let mut next = Some(value);
60    loop {
61        match next.take() {
62            Some(Value::Array(a)) => {
63                out.push('[');
64                stack.push((Open::Array(a.iter()), false));
65            }
66            Some(Value::Object(o)) => {
67                out.push('{');
68                stack.push((Open::Object(o.iter()), false));
69            }
70            Some(scalar) => write_scalar(scalar, out),
71            None => {}
72        }
73        let Some((open, started)) = stack.last_mut() else {
74            return;
75        };
76        let element = match open {
77            Open::Array(rest) => rest.next().map(|v| (None, v)),
78            Open::Object(rest) => rest.next().map(|(k, v)| (Some(k), v)),
79        };
80        match element {
81            Some((key, v)) => {
82                if *started {
83                    out.push(',');
84                }
85                *started = true;
86                if let Some(key) = key {
87                    write_string(key, out);
88                    out.push(':');
89                }
90                next = Some(v);
91            }
92            None => {
93                out.push(if matches!(open, Open::Array(_)) {
94                    ']'
95                } else {
96                    '}'
97                });
98                stack.pop();
99            }
100        }
101    }
102}
103
104fn write_scalar(value: &Value, out: &mut String) {
105    match value {
106        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
107        Value::Number(n) if n.is_finite() => out.push_str(&number::format(*n)),
108        Value::String(s) => write_string(s, out),
109        // Null, the non-finite numbers, and (never passed here) containers.
110        _ => out.push_str("null"),
111    }
112}
113
114/// Appends `s` as a JSON string literal.
115pub fn write_string(s: &str, out: &mut String) {
116    const HEX: &[u8; 16] = b"0123456789abcdef";
117    out.push('"');
118    if !s.bytes().any(|b| b < 0x20 || b == b'"' || b == b'\\') {
119        out.push_str(s);
120        out.push('"');
121        return;
122    }
123    for c in s.chars() {
124        match c {
125            '"' => out.push_str("\\\""),
126            '\\' => out.push_str("\\\\"),
127            '\u{8}' => out.push_str("\\b"),
128            '\u{c}' => out.push_str("\\f"),
129            '\n' => out.push_str("\\n"),
130            '\r' => out.push_str("\\r"),
131            '\t' => out.push_str("\\t"),
132            '\0'..='\u{1f}' => {
133                out.push_str("\\u00");
134                out.push(HEX[c as usize >> 4] as char);
135                out.push(HEX[c as usize & 0xF] as char);
136            }
137            _ => out.push(c),
138        }
139    }
140    out.push('"');
141}