Skip to main content

jsonx_lib/
write.rs

1//! The writer: deterministic compact and pretty output with complete escaping.
2
3use alloc::{borrow::Cow, string::String};
4use core::{convert::Infallible, fmt, slice};
5
6use crate::{Value, scan, tree::Member};
7
8/// Spaces for indentation, copied in slices.
9const SPACES: &str = "                                                                ";
10
11/// Indentation width of the pretty layout.
12const INDENT: usize = 2;
13
14/// Appends `text` to `out` as a JSON string literal, quotes included.
15///
16/// The escaping is complete and the same every time:
17///
18/// - `"` and `\` are escaped as `\"` and `\\`;
19/// - the control characters U+0000 to U+001F are escaped, with the short forms
20///   `\b \f \n \r \t` where JSON has one and `\u00XX` (lowercase hex)
21///   otherwise;
22/// - U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped as
23///   `\u2028` and `\u2029`: JSON allows them raw, but JavaScript before ES2019
24///   ends a line at them, so raw ones break JSON embedded in a script;
25/// - everything else, including `/`, DEL, and all other non-ASCII text, is
26///   copied unchanged as UTF-8.
27///
28/// So no string can end the literal early or put a raw line break in it,
29/// whatever it contains: the output is always exactly one JSON string token
30/// that decodes back to `text`. Unescaped stretches are copied in bulk, found
31/// eight bytes at a time.
32///
33/// # Examples
34///
35/// ```
36/// let mut out = String::from("{\"msg\":");
37/// jsonx_lib::write_string(&mut out, "say \"hi\"\n\u{2028}");
38/// out.push('}');
39/// assert_eq!(out, r#"{"msg":"say \"hi\"\n\u2028"}"#);
40/// ```
41pub fn write_string(out: &mut String, text: &str) {
42    out.reserve(text.len() + 2);
43    out.push('"');
44    let bytes = text.as_bytes();
45    let mut from = 0;
46    let mut at = 0;
47    loop {
48        at = scan::find_write_special(bytes, at);
49        let Some(&b) = bytes.get(at) else { break };
50        let escape: &str = match b {
51            b'"' => "\\\"",
52            b'\\' => "\\\\",
53            b'\n' => "\\n",
54            b'\r' => "\\r",
55            b'\t' => "\\t",
56            0x08 => "\\b",
57            0x0C => "\\f",
58            0xE2 => match bytes.get(at + 1..at + 3) {
59                Some([0x80, 0xA8]) => "\\u2028",
60                Some([0x80, 0xA9]) => "\\u2029",
61                // Another character starting with 0xE2: copy it as is.
62                _ => {
63                    at += 1;
64                    continue;
65                }
66            },
67            control => {
68                out.push_str(text.get(from..at).unwrap_or(""));
69                out.push_str("\\u00");
70                out.push(char::from(scan::hex_digit(control >> 4)));
71                out.push(char::from(scan::hex_digit(control)));
72                at += 1;
73                from = at;
74                continue;
75            }
76        };
77        out.push_str(text.get(from..at).unwrap_or(""));
78        out.push_str(escape);
79        // The line separators are three bytes; every other escaped byte, one.
80        at += if b == 0xE2 { 3 } else { 1 };
81        from = at;
82    }
83    out.push_str(text.get(from..).unwrap_or(""));
84    out.push('"');
85}
86
87/// Serializes `value` as compact JSON: no whitespace at all.
88///
89/// The output is deterministic: members in their order, numbers as their exact
90/// text, strings escaped as [`write_string`] describes. Parsing it gives back
91/// a value equal to `value`.
92///
93/// # Examples
94///
95/// ```
96/// use jsonx_lib::{json, to_string};
97///
98/// let v = json!({ "id": 1, "tags": ["a", "b"], "none": null });
99/// assert_eq!(to_string(&v), r#"{"id":1,"tags":["a","b"],"none":null}"#);
100/// ```
101#[must_use]
102pub fn to_string(value: &Value<'_>) -> String {
103    let mut out = String::new();
104    write_value(&mut out, value);
105    out
106}
107
108/// Serializes `value` as indented JSON: two spaces per level, one member or
109/// item per line, `": "` after keys, empty containers as `[]` and `{}`, and
110/// no trailing newline.
111///
112/// # Examples
113///
114/// ```
115/// use jsonx_lib::{json, to_string_pretty};
116///
117/// let v = json!({ "a": [1, 2], "b": {} });
118/// assert_eq!(to_string_pretty(&v), "{\n  \"a\": [\n    1,\n    2\n  ],\n  \"b\": {}\n}");
119/// ```
120#[must_use]
121pub fn to_string_pretty(value: &Value<'_>) -> String {
122    let mut out = String::new();
123    write_value_pretty(&mut out, value);
124    out
125}
126
127/// Appends `value` to `out` as compact JSON (see [`to_string`]). Reusing one
128/// buffer across documents avoids an allocation per document.
129///
130/// # Examples
131///
132/// ```
133/// use jsonx_lib::{json, write_value};
134///
135/// let mut out = String::from("Content: ");
136/// write_value(&mut out, &json!([true]));
137/// assert_eq!(out, "Content: [true]");
138/// ```
139pub fn write_value(out: &mut String, value: &Value<'_>) {
140    let Ok(()) = emit::<Infallible>(out, value, false, usize::MAX, &mut |_| Ok(()));
141}
142
143/// Appends `value` to `out` as indented JSON (see [`to_string_pretty`]).
144///
145/// # Examples
146///
147/// ```
148/// use jsonx_lib::{json, write_value_pretty};
149///
150/// let mut out = String::new();
151/// write_value_pretty(&mut out, &json!([1]));
152/// assert_eq!(out, "[\n  1\n]");
153/// ```
154pub fn write_value_pretty(out: &mut String, value: &Value<'_>) {
155    let Ok(()) = emit::<Infallible>(out, value, true, usize::MAX, &mut |_| Ok(()));
156}
157
158/// Writes `value` as compact JSON to an [`io::Write`](std::io::Write),
159/// through a buffer of a few kilobytes, so a large document is never held as
160/// one string.
161///
162/// # Errors
163///
164/// Any error from `writer`.
165///
166/// # Examples
167///
168/// ```
169/// let mut out = Vec::new();
170/// jsonx_lib::to_writer(&mut out, &jsonx_lib::json!({ "ok": true }))?;
171/// assert_eq!(out, br#"{"ok":true}"#);
172/// # Ok::<(), std::io::Error>(())
173/// ```
174#[cfg(feature = "std")]
175#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
176pub fn to_writer<W: std::io::Write>(writer: W, value: &Value<'_>) -> std::io::Result<()> {
177    write_io(writer, value, false)
178}
179
180/// Writes `value` as indented JSON (see [`to_string_pretty`]) to an
181/// [`io::Write`](std::io::Write), through a buffer of a few kilobytes.
182///
183/// # Errors
184///
185/// Any error from `writer`.
186///
187/// # Examples
188///
189/// ```
190/// let mut out = Vec::new();
191/// jsonx_lib::to_writer_pretty(&mut out, &jsonx_lib::json!([null]))?;
192/// assert_eq!(out, b"[\n  null\n]");
193/// # Ok::<(), std::io::Error>(())
194/// ```
195#[cfg(feature = "std")]
196#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
197pub fn to_writer_pretty<W: std::io::Write>(writer: W, value: &Value<'_>) -> std::io::Result<()> {
198    write_io(writer, value, true)
199}
200
201#[cfg(feature = "std")]
202fn write_io<W: std::io::Write>(
203    mut writer: W,
204    value: &Value<'_>,
205    pretty: bool,
206) -> std::io::Result<()> {
207    const CHUNK: usize = 8 * 1024;
208    let mut buf = String::with_capacity(CHUNK + 256);
209    emit(&mut buf, value, pretty, CHUNK, &mut |chunk: &mut String| {
210        let result = writer.write_all(chunk.as_bytes());
211        chunk.clear();
212        result
213    })?;
214    writer.write_all(buf.as_bytes())
215}
216
217/// Appends a newline and the indentation for `depth` levels.
218fn newline(out: &mut String, depth: usize) {
219    out.push('\n');
220    let mut width = depth.saturating_mul(INDENT);
221    while width > 0 {
222        let chunk = width.min(SPACES.len());
223        out.push_str(SPACES.get(..chunk).unwrap_or(""));
224        width -= chunk;
225    }
226}
227
228/// The children of an open container still to be written.
229enum Open<'r, 'a> {
230    Array(slice::Iter<'r, Value<'a>>),
231    Object(slice::Iter<'r, Member<'a>>),
232}
233
234/// Writes `value` into `out`, handing `out` to `flush` whenever it holds at
235/// least `flush_at` bytes (the flush is expected to empty it).
236///
237/// Iterative: an explicit stack of open containers replaces recursion, so any
238/// depth is safe.
239fn emit<E>(
240    out: &mut String,
241    value: &Value<'_>,
242    pretty: bool,
243    flush_at: usize,
244    flush: &mut dyn FnMut(&mut String) -> Result<(), E>,
245) -> Result<(), E> {
246    let mut stack: alloc::vec::Vec<(Open<'_, '_>, bool)> = alloc::vec::Vec::new();
247    let mut next = Some(value);
248    loop {
249        if let Some(value) = next.take() {
250            match value {
251                Value::Null => out.push_str("null"),
252                Value::Bool(true) => out.push_str("true"),
253                Value::Bool(false) => out.push_str("false"),
254                Value::Number(n) => out.push_str(n.as_str()),
255                Value::String(s) => write_string(out, s),
256                Value::Array(a) if a.is_empty() => out.push_str("[]"),
257                Value::Object(o) if o.is_empty() => out.push_str("{}"),
258                Value::Array(a) => {
259                    out.push('[');
260                    stack.push((Open::Array(a.iter()), true));
261                }
262                Value::Object(o) => {
263                    out.push('{');
264                    stack.push((Open::Object(o.as_slice().iter()), true));
265                }
266            }
267            if out.len() >= flush_at {
268                flush(out)?;
269            }
270        }
271        let depth = stack.len();
272        let Some((open, first)) = stack.last_mut() else {
273            return Ok(());
274        };
275        let (child, key): (Option<&Value<'_>>, Option<&Cow<'_, str>>) = match open {
276            Open::Array(it) => (it.next(), None),
277            Open::Object(it) => match it.next() {
278                Some((k, v)) => (Some(v), Some(k)),
279                None => (None, None),
280            },
281        };
282        let Some(child) = child else {
283            let close = if matches!(open, Open::Array(_)) {
284                ']'
285            } else {
286                '}'
287            };
288            let _closed = stack.pop();
289            if pretty {
290                newline(out, depth - 1);
291            }
292            out.push(close);
293            continue;
294        };
295        if !*first {
296            out.push(',');
297        }
298        *first = false;
299        if pretty {
300            newline(out, depth);
301        }
302        if let Some(key) = key {
303            write_string(out, key);
304            out.push_str(if pretty { ": " } else { ":" });
305        }
306        next = Some(child);
307    }
308}
309
310impl fmt::Display for Value<'_> {
311    /// Writes the value as compact JSON, or as indented JSON with the
312    /// alternate flag (`{:#}`).
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// let v = jsonx_lib::json!({ "a": [1] });
318    /// assert_eq!(format!("{v}"), r#"{"a":[1]}"#);
319    /// assert_eq!(format!("{v:#}"), "{\n  \"a\": [\n    1\n  ]\n}");
320    /// ```
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        const CHUNK: usize = 4 * 1024;
323        let mut buf = String::new();
324        emit(
325            &mut buf,
326            self,
327            f.alternate(),
328            CHUNK,
329            &mut |chunk: &mut String| {
330                let result = f.write_str(chunk);
331                chunk.clear();
332                result
333            },
334        )?;
335        f.write_str(&buf)
336    }
337}
338
339impl fmt::Debug for Value<'_> {
340    /// Writes the value as compact JSON.
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        fmt::Display::fmt(self, f)
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use alloc::string::ToString;
349
350    use super::*;
351
352    fn quoted(text: &str) -> String {
353        let mut out = String::new();
354        write_string(&mut out, text);
355        out
356    }
357
358    #[test]
359    fn test_write_string_escapes_exactly() {
360        assert_eq!(quoted(""), r#""""#);
361        assert_eq!(quoted("plain/text"), r#""plain/text""#);
362        assert_eq!(quoted("\"\\"), r#""\"\\""#);
363        assert_eq!(quoted("\u{8}\u{c}\n\r\t"), r#""\b\f\n\r\t""#);
364        assert_eq!(
365            quoted("\u{0}\u{1}\u{1f}\u{7f}"),
366            "\"\\u0000\\u0001\\u001f\u{7f}\""
367        );
368        assert_eq!(quoted("a\u{2028}b\u{2029}c"), r#""a\u2028b\u2029c""#);
369        // Other characters starting with 0xE2 pass through.
370        assert_eq!(
371            quoted("\u{20ac}\u{2027}\u{202a}"),
372            "\"\u{20ac}\u{2027}\u{202a}\""
373        );
374        assert_eq!(
375            quoted("long run of text then \" quote"),
376            r#""long run of text then \" quote""#
377        );
378    }
379
380    #[test]
381    fn test_pretty_layout_nested_and_empty() {
382        let v = crate::parse(r#"{"a":[],"b":{},"c":[{"d":null}]}"#).unwrap_or_default();
383        assert_eq!(
384            to_string_pretty(&v),
385            "{\n  \"a\": [],\n  \"b\": {},\n  \"c\": [\n    {\n      \"d\": null\n    }\n  ]\n}"
386        );
387        assert_eq!(to_string_pretty(&Value::from(1)), "1");
388    }
389
390    #[test]
391    fn test_display_flushes_in_chunks_identically() {
392        let mut big = String::from("[");
393        for i in 0..5000 {
394            big.push_str(&alloc::format!("{i},"));
395        }
396        big.push_str("0]");
397        let v = crate::parse(&big).unwrap_or_default();
398        assert_eq!(v.to_string(), big);
399    }
400
401    #[test]
402    fn test_deep_indent_beyond_spaces_buffer() {
403        let depth = 40;
404        let text = "[".repeat(depth) + &"]".repeat(depth);
405        let v = crate::parse(&text).unwrap_or_default();
406        let pretty = to_string_pretty(&v);
407        assert!(pretty.contains(&alloc::format!("\n{}[]", " ".repeat((depth - 1) * 2))));
408    }
409}