Skip to main content

jsonx_lib/
format.rs

1//! Output options: layout and escaping.
2
3/// How the writers lay out and escape their output.
4///
5/// The default is compact JSON (no whitespace) with the escaping described
6/// on [`write_string`](crate::write_string): quotes, backslashes, control
7/// characters, and U+2028/U+2029, and nothing else. [`pretty`](Self::pretty)
8/// is the [`to_string_pretty`](crate::to_string_pretty) layout. Two stricter
9/// escapings are available for output that is embedded somewhere JSON's own
10/// rules are not enough:
11///
12/// - [`html_safe`](Self::html_safe) also escapes `<`, `>`, and `&`, so the
13///   output can sit inside an HTML `<script>` element or attribute without
14///   ending it (`</script>` cannot appear in it);
15/// - [`ascii`](Self::ascii) escapes every non-ASCII character as `\uXXXX`
16///   (a surrogate pair above U+FFFF), for channels that are not 8-bit clean.
17///
18/// Both apply to everything written, [`RawValue`](crate::RawValue) text
19/// included (its strings are escaped the same way). Every format writes
20/// valid JSON that reads back as the same value (for objects without
21/// repeated keys: the writers do not check for them; see
22/// [`ObjectWriter`](crate::ObjectWriter)); the formats differ only in
23/// bytes.
24///
25/// The struct is `#[non_exhaustive]`: build it from [`Format::compact`] or
26/// [`Format::pretty`] and the `with_*` methods.
27///
28/// # Examples
29///
30/// ```
31/// use jsonx_lib::{json, to_string_with, Format};
32///
33/// let v = json!({ "html": "</script>", "word": "caf\u{e9}" });
34/// let safe = to_string_with(&v, Format::compact().html_safe(true).ascii(true));
35/// assert!(!safe.contains('<') && safe.is_ascii());
36/// assert_eq!(jsonx_lib::parse(&safe)?, v);
37///
38/// let wide = to_string_with(&json!([1]), Format::pretty().with_indent(4));
39/// assert_eq!(wide, "[\n    1\n]");
40/// # Ok::<(), jsonx_lib::Error>(())
41/// ```
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43#[non_exhaustive]
44pub struct Format {
45    pub(crate) pretty: bool,
46    pub(crate) indent: u8,
47    pub(crate) ascii: bool,
48    pub(crate) html: bool,
49}
50
51impl Format {
52    /// Compact JSON: no whitespace at all. The default.
53    ///
54    /// # Examples
55    ///
56    /// ```
57    /// use jsonx_lib::{json, to_string_with, Format};
58    ///
59    /// assert_eq!(to_string_with(&json!({ "a": [1, 2] }), Format::compact()), r#"{"a":[1,2]}"#);
60    /// ```
61    #[must_use]
62    pub const fn compact() -> Self {
63        Self {
64            pretty: false,
65            indent: 2,
66            ascii: false,
67            html: false,
68        }
69    }
70
71    /// The indented layout of [`to_string_pretty`](crate::to_string_pretty):
72    /// one member or item per line, two spaces per level, `": "` after keys,
73    /// empty containers as `[]` and `{}`, no trailing newline.
74    ///
75    /// # Examples
76    ///
77    /// ```
78    /// use jsonx_lib::{json, to_string_with, Format};
79    ///
80    /// assert_eq!(to_string_with(&json!([1]), Format::pretty()), "[\n  1\n]");
81    /// ```
82    #[must_use]
83    pub const fn pretty() -> Self {
84        Self {
85            pretty: true,
86            ..Self::compact()
87        }
88    }
89
90    /// The indented layout with `spaces` spaces per level (`0` puts each
91    /// member on its own line without indenting it).
92    ///
93    /// # Examples
94    ///
95    /// ```
96    /// use jsonx_lib::{json, to_string_with, Format};
97    ///
98    /// assert_eq!(to_string_with(&json!({ "a": 1 }), Format::compact().with_indent(1)), "{\n \"a\": 1\n}");
99    /// ```
100    #[must_use]
101    pub const fn with_indent(mut self, spaces: u8) -> Self {
102        self.pretty = true;
103        self.indent = spaces;
104        self
105    }
106
107    /// Whether to also escape `<`, `>`, and `&` (as `\u003c`, `\u003e`,
108    /// `\u0026`), so the output is safe inside HTML.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use jsonx_lib::{to_string_with, Format};
114    ///
115    /// let text = to_string_with("</script>", Format::compact().html_safe(true));
116    /// assert_eq!(text, "\"\\u003c/script\\u003e\"");
117    /// ```
118    #[must_use]
119    pub const fn html_safe(mut self, on: bool) -> Self {
120        self.html = on;
121        self
122    }
123
124    /// Whether to escape every non-ASCII character, so the output is pure
125    /// ASCII.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use jsonx_lib::{to_string_with, Format};
131    ///
132    /// assert_eq!(to_string_with("\u{e9}\u{1f600}", Format::compact().ascii(true)), "\"\\u00e9\\ud83d\\ude00\"");
133    /// ```
134    #[must_use]
135    pub const fn ascii(mut self, on: bool) -> Self {
136        self.ascii = on;
137        self
138    }
139
140    /// Whether this is an indented layout.
141    ///
142    /// # Examples
143    ///
144    /// ```
145    /// assert!(jsonx_lib::Format::pretty().is_pretty());
146    /// assert!(!jsonx_lib::Format::default().is_pretty());
147    /// ```
148    #[must_use]
149    pub const fn is_pretty(&self) -> bool {
150        self.pretty
151    }
152
153    /// Whether strings need more than the minimal escaping.
154    #[inline]
155    pub(crate) const fn strict(&self) -> bool {
156        self.ascii || self.html
157    }
158}
159
160impl Default for Format {
161    /// [`Format::compact`].
162    #[inline]
163    fn default() -> Self {
164        Self::compact()
165    }
166}