1use alloc::{borrow::Cow, string::String};
4use core::{fmt, slice};
5
6use crate::{
7 Format, ToJson, Value,
8 encode::{Keep, Out, ValueWriter, Written},
9 scan,
10 tree::Member,
11};
12
13const SPACES: &str = " ";
15
16#[inline(always)]
50pub fn write_string(out: &mut String, text: &str) {
51 let plain = scan::plain_prefix_for_write(text.as_bytes());
52 if plain == text.len() {
53 out.reserve(text.len() + 2);
54 out.push('"');
55 out.push_str(text);
56 out.push('"');
57 } else {
58 write_string_escaped(out, text, plain);
59 }
60}
61
62#[inline(never)]
65fn write_string_escaped(out: &mut String, text: &str, plain: usize) {
66 out.reserve(text.len() + 2);
67 out.push('"');
68 let bytes = text.as_bytes();
69 let mut from = 0;
70 let mut at = plain;
71 loop {
72 at = scan::find_write_special(bytes, at);
73 let Some(&b) = bytes.get(at) else { break };
74 let escape: &str = match b {
75 b'"' => "\\\"",
76 b'\\' => "\\\\",
77 b'\n' => "\\n",
78 b'\r' => "\\r",
79 b'\t' => "\\t",
80 0x08 => "\\b",
81 0x0C => "\\f",
82 0xE2 => match bytes.get(at + 1..at + 3) {
83 Some([0x80, 0xA8]) => "\\u2028",
84 Some([0x80, 0xA9]) => "\\u2029",
85 _ => {
87 at += 1;
88 continue;
89 }
90 },
91 control => {
92 out.push_str(text.get(from..at).unwrap_or(""));
93 out.push_str("\\u00");
94 out.push(char::from(scan::hex_digit(control >> 4)));
95 out.push(char::from(scan::hex_digit(control)));
96 at += 1;
97 from = at;
98 continue;
99 }
100 };
101 out.push_str(text.get(from..at).unwrap_or(""));
102 out.push_str(escape);
103 at += if b == 0xE2 { 3 } else { 1 };
105 from = at;
106 }
107 out.push_str(text.get(from..).unwrap_or(""));
108 out.push('"');
109}
110
111#[inline(always)]
115pub(crate) fn write_str(out: &mut String, text: &str, format: Format) {
116 if format.strict() {
117 write_string_strict(out, text, format);
118 } else {
119 write_string(out, text);
120 }
121}
122
123fn write_string_strict(out: &mut String, text: &str, format: Format) {
126 out.reserve(text.len() + 2);
127 out.push('"');
128 let mut from = 0;
129 for (at, ch) in text.char_indices() {
130 let escape = match ch {
131 '"' | '\\' | '\u{0}'..='\u{1f}' | '\u{2028}' | '\u{2029}' => true,
132 '<' | '>' | '&' => format.html,
133 _ => format.ascii && !ch.is_ascii(),
134 };
135 if !escape {
136 continue;
137 }
138 out.push_str(text.get(from..at).unwrap_or(""));
139 from = at + ch.len_utf8();
140 match ch {
141 '"' => out.push_str("\\\""),
142 '\\' => out.push_str("\\\\"),
143 '\n' => out.push_str("\\n"),
144 '\r' => out.push_str("\\r"),
145 '\t' => out.push_str("\\t"),
146 '\u{8}' => out.push_str("\\b"),
147 '\u{c}' => out.push_str("\\f"),
148 _ => {
149 let mut units = [0u16; 2];
150 for unit in ch.encode_utf16(&mut units) {
151 push_unicode_escape(out, *unit);
152 }
153 }
154 }
155 }
156 out.push_str(text.get(from..).unwrap_or(""));
157 out.push('"');
158}
159
160pub(crate) fn write_raw(out: &mut String, raw: &str, format: Format) {
168 if !format.strict() {
169 out.push_str(raw);
170 return;
171 }
172 out.reserve(raw.len());
173 let mut from = 0;
174 for (at, ch) in raw.char_indices() {
175 let escape = match ch {
176 '\u{2028}' | '\u{2029}' => true,
177 '<' | '>' | '&' => format.html,
178 _ => format.ascii && !ch.is_ascii(),
179 };
180 if !escape {
181 continue;
182 }
183 out.push_str(raw.get(from..at).unwrap_or(""));
184 from = at + ch.len_utf8();
185 let mut units = [0u16; 2];
186 for unit in ch.encode_utf16(&mut units) {
187 push_unicode_escape(out, *unit);
188 }
189 }
190 out.push_str(raw.get(from..).unwrap_or(""));
191}
192
193fn push_unicode_escape(out: &mut String, unit: u16) {
195 out.push('\\');
196 out.push('u');
197 for shift in [12, 8, 4, 0] {
198 out.push(char::from(scan::hex_digit((unit >> shift) as u8)));
200 }
201}
202
203const START: usize = 128;
209
210#[must_use]
228pub fn to_string<T: ToJson + ?Sized>(value: &T) -> String {
229 let mut out = String::with_capacity(START);
230 write_value(&mut out, value);
231 out
232}
233
234#[must_use]
247pub fn to_string_pretty<T: ToJson + ?Sized>(value: &T) -> String {
248 let mut out = String::with_capacity(START);
249 write_value_pretty(&mut out, value);
250 out
251}
252
253pub fn write_value<T: ToJson + ?Sized>(out: &mut String, value: &T) {
266 write_value_with(out, value, Format::compact());
267}
268
269pub fn write_value_pretty<T: ToJson + ?Sized>(out: &mut String, value: &T) {
281 write_value_with(out, value, Format::pretty());
282}
283
284#[must_use]
295pub fn to_string_with<T: ToJson + ?Sized>(value: &T, format: Format) -> String {
296 let mut out = String::with_capacity(START);
297 write_value_with(&mut out, value, format);
298 out
299}
300
301pub fn write_value_with<T: ToJson + ?Sized>(out: &mut String, value: &T, format: Format) {
313 let mut keep = Keep;
314 let writer = ValueWriter::new(Out {
315 buf: out,
316 sink: &mut keep,
317 flush_at: usize::MAX,
318 format,
319 depth: 0,
320 });
321 let Written(()) = value.to_json(writer);
322}
323
324#[cfg(feature = "std")]
341#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
342pub fn to_writer<W: std::io::Write, T: ToJson + ?Sized>(
343 writer: W,
344 value: &T,
345) -> std::io::Result<()> {
346 to_writer_with(writer, value, Format::compact())
347}
348
349#[cfg(feature = "std")]
365#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
366pub fn to_writer_pretty<W: std::io::Write, T: ToJson + ?Sized>(
367 writer: W,
368 value: &T,
369) -> std::io::Result<()> {
370 to_writer_with(writer, value, Format::pretty())
371}
372
373pub(crate) const CHUNK: usize = 8 * 1024;
375
376#[cfg(feature = "std")]
394#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
395pub fn to_writer_with<W: std::io::Write, T: ToJson + ?Sized>(
396 mut writer: W,
397 value: &T,
398 format: Format,
399) -> std::io::Result<()> {
400 let mut buf = String::with_capacity(CHUNK + 256);
401 let mut sink = crate::encode::IoSink {
402 writer: &mut writer,
403 error: None,
404 };
405 let out = Out {
406 buf: &mut buf,
407 sink: &mut sink,
408 flush_at: CHUNK,
409 format,
410 depth: 0,
411 };
412 let Written(()) = value.to_json(ValueWriter::new(out));
413 crate::encode::Flush::flush(&mut sink, &mut buf);
414 sink.error.map_or(Ok(()), Err)
415}
416
417pub(crate) fn newline(out: &mut String, depth: usize, format: Format) {
419 out.push('\n');
420 let mut width = depth.saturating_mul(usize::from(format.indent));
421 while width > 0 {
422 let chunk = width.min(SPACES.len());
423 out.push_str(SPACES.get(..chunk).unwrap_or(""));
424 width -= chunk;
425 }
426}
427
428enum Open<'r, 'a> {
430 Array(slice::Iter<'r, Value<'a>>),
431 Object(slice::Iter<'r, Member<'a>>),
432}
433
434pub(crate) fn emit<E>(
441 out: &mut String,
442 value: &Value<'_>,
443 format: Format,
444 base: usize,
445 flush_at: usize,
446 flush: &mut dyn FnMut(&mut String) -> Result<(), E>,
447) -> Result<(), E> {
448 match (format.pretty, format.strict()) {
451 (false, false) => emit_as::<E, false, false>(out, value, format, base, flush_at, flush),
452 (false, true) => emit_as::<E, false, true>(out, value, format, base, flush_at, flush),
453 (true, false) => emit_as::<E, true, false>(out, value, format, base, flush_at, flush),
454 (true, true) => emit_as::<E, true, true>(out, value, format, base, flush_at, flush),
455 }
456}
457
458fn emit_as<E, const PRETTY: bool, const STRICT: bool>(
461 out: &mut String,
462 value: &Value<'_>,
463 format: Format,
464 base: usize,
465 flush_at: usize,
466 flush: &mut dyn FnMut(&mut String) -> Result<(), E>,
467) -> Result<(), E> {
468 let write_text = |out: &mut String, text: &str| {
469 if STRICT {
470 write_string_strict(out, text, format);
471 } else {
472 write_string(out, text);
473 }
474 };
475 let mut stack: alloc::vec::Vec<(Open<'_, '_>, bool)> = alloc::vec::Vec::new();
476 let mut next = Some(value);
477 loop {
478 if let Some(value) = next.take() {
479 match value {
480 Value::Null => out.push_str("null"),
481 Value::Bool(true) => out.push_str("true"),
482 Value::Bool(false) => out.push_str("false"),
483 Value::Number(n) => out.push_str(n.as_str()),
484 Value::String(s) => write_text(out, s),
485 Value::Array(a) if a.is_empty() => out.push_str("[]"),
486 Value::Object(o) if o.is_empty() => out.push_str("{}"),
487 Value::Array(a) => {
488 out.push('[');
489 stack.push((Open::Array(a.iter()), true));
490 }
491 Value::Object(o) => {
492 out.push('{');
493 stack.push((Open::Object(o.as_slice().iter()), true));
494 }
495 }
496 if out.len() >= flush_at {
497 flush(out)?;
498 }
499 }
500 let depth = stack.len();
501 let Some((open, first)) = stack.last_mut() else {
502 return Ok(());
503 };
504 let (child, key): (Option<&Value<'_>>, Option<&Cow<'_, str>>) = match open {
505 Open::Array(it) => (it.next(), None),
506 Open::Object(it) => match it.next() {
507 Some((k, v)) => (Some(v), Some(k)),
508 None => (None, None),
509 },
510 };
511 let Some(child) = child else {
512 let close = if matches!(open, Open::Array(_)) {
513 ']'
514 } else {
515 '}'
516 };
517 let _closed = stack.pop();
518 if PRETTY {
519 newline(out, base + depth - 1, format);
520 }
521 out.push(close);
522 continue;
523 };
524 if !*first {
525 out.push(',');
526 }
527 *first = false;
528 if PRETTY {
529 newline(out, base + depth, format);
530 }
531 if let Some(key) = key {
532 write_text(out, key);
533 out.push_str(if PRETTY { ": " } else { ":" });
534 }
535 next = Some(child);
536 }
537}
538
539impl fmt::Display for Value<'_> {
540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551 const CHUNK: usize = 4 * 1024;
552 let mut buf = String::new();
553 emit(
554 &mut buf,
555 self,
556 if f.alternate() {
557 Format::pretty()
558 } else {
559 Format::compact()
560 },
561 0,
562 CHUNK,
563 &mut |chunk: &mut String| {
564 let result = f.write_str(chunk);
565 chunk.clear();
566 result
567 },
568 )?;
569 f.write_str(&buf)
570 }
571}
572
573impl fmt::Debug for Value<'_> {
574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
576 fmt::Display::fmt(self, f)
577 }
578}
579
580#[cfg(test)]
581mod tests {
582 use alloc::string::ToString;
583
584 use super::*;
585
586 fn quoted(text: &str) -> String {
587 let mut out = String::new();
588 write_string(&mut out, text);
589 out
590 }
591
592 #[test]
593 fn test_write_string_escapes_exactly() {
594 assert_eq!(quoted(""), r#""""#);
595 assert_eq!(quoted("plain/text"), r#""plain/text""#);
596 assert_eq!(quoted("\"\\"), r#""\"\\""#);
597 assert_eq!(quoted("\u{8}\u{c}\n\r\t"), r#""\b\f\n\r\t""#);
598 assert_eq!(
599 quoted("\u{0}\u{1}\u{1f}\u{7f}"),
600 "\"\\u0000\\u0001\\u001f\u{7f}\""
601 );
602 assert_eq!(quoted("a\u{2028}b\u{2029}c"), r#""a\u2028b\u2029c""#);
603 assert_eq!(
605 quoted("\u{20ac}\u{2027}\u{202a}"),
606 "\"\u{20ac}\u{2027}\u{202a}\""
607 );
608 assert_eq!(
609 quoted("long run of text then \" quote"),
610 r#""long run of text then \" quote""#
611 );
612 }
613
614 #[test]
615 fn test_pretty_layout_nested_and_empty() {
616 let v = crate::parse(r#"{"a":[],"b":{},"c":[{"d":null}]}"#).unwrap_or_default();
617 assert_eq!(
618 to_string_pretty(&v),
619 "{\n \"a\": [],\n \"b\": {},\n \"c\": [\n {\n \"d\": null\n }\n ]\n}"
620 );
621 assert_eq!(to_string_pretty(&Value::from(1)), "1");
622 }
623
624 #[test]
625 fn test_display_flushes_in_chunks_identically() {
626 let mut big = String::from("[");
627 for i in 0..5000 {
628 big.push_str(&alloc::format!("{i},"));
629 }
630 big.push_str("0]");
631 let v = crate::parse(&big).unwrap_or_default();
632 assert_eq!(v.to_string(), big);
633 }
634
635 #[test]
636 fn test_deep_indent_beyond_spaces_buffer() {
637 let depth = 40;
638 let text = "[".repeat(depth) + &"]".repeat(depth);
639 let v = crate::parse(&text).unwrap_or_default();
640 let pretty = to_string_pretty(&v);
641 assert!(pretty.contains(&alloc::format!("\n{}[]", " ".repeat((depth - 1) * 2))));
642 }
643}