1use alloc::{borrow::Cow, string::String};
4use core::{convert::Infallible, fmt, slice};
5
6use crate::{Value, scan, tree::Member};
7
8const SPACES: &str = " ";
10
11const INDENT: usize = 2;
13
14pub 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 _ => {
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 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#[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#[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
127pub fn write_value(out: &mut String, value: &Value<'_>) {
140 let Ok(()) = emit::<Infallible>(out, value, false, usize::MAX, &mut |_| Ok(()));
141}
142
143pub fn write_value_pretty(out: &mut String, value: &Value<'_>) {
155 let Ok(()) = emit::<Infallible>(out, value, true, usize::MAX, &mut |_| Ok(()));
156}
157
158#[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#[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
217fn 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
228enum Open<'r, 'a> {
230 Array(slice::Iter<'r, Value<'a>>),
231 Object(slice::Iter<'r, Member<'a>>),
232}
233
234fn 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 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 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 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}