jsonx_lib/format.rs
1//! Output options: layout, escaping, and float text.
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).
20///
21/// Two options change the text of floats written from Rust values
22/// ([`ValueWriter::f64`](crate::ValueWriter::f64) and
23/// [`f32`](crate::ValueWriter::f32)), for output that must match another
24/// writer's byte for byte: [`exponent_plus`](Self::exponent_plus) writes
25/// `1e+16` for `1e16`, and [`even_ties`](Self::even_ties) changes which of
26/// two equally close shortest texts is written. A [`Number`](crate::Number)
27/// keeps its own text in every format. Every format writes
28/// valid JSON that reads back as the same value (for objects without
29/// repeated keys: the writers do not check for them; see
30/// [`ObjectWriter`](crate::ObjectWriter)); the formats differ only in
31/// bytes.
32///
33/// The struct is `#[non_exhaustive]`: build it from [`Format::compact`] or
34/// [`Format::pretty`] and the `with_*` methods.
35///
36/// # Examples
37///
38/// ```
39/// use jsonx_lib::{json, to_string_with, Format};
40///
41/// let v = json!({ "html": "</script>", "word": "caf\u{e9}" });
42/// let safe = to_string_with(&v, Format::compact().html_safe(true).ascii(true));
43/// assert!(!safe.contains('<') && safe.is_ascii());
44/// assert_eq!(jsonx_lib::parse(&safe)?, v);
45///
46/// let wide = to_string_with(&json!([1]), Format::pretty().with_indent(4));
47/// assert_eq!(wide, "[\n 1\n]");
48/// # Ok::<(), jsonx_lib::Error>(())
49/// ```
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
51#[non_exhaustive]
52pub struct Format {
53 pub(crate) pretty: bool,
54 pub(crate) indent: u8,
55 pub(crate) ascii: bool,
56 pub(crate) html: bool,
57 pub(crate) exponent_plus: bool,
58 pub(crate) even_ties: bool,
59}
60
61impl Format {
62 /// Compact JSON: no whitespace at all. The default.
63 ///
64 /// # Examples
65 ///
66 /// ```
67 /// use jsonx_lib::{json, to_string_with, Format};
68 ///
69 /// assert_eq!(to_string_with(&json!({ "a": [1, 2] }), Format::compact()), r#"{"a":[1,2]}"#);
70 /// ```
71 #[must_use]
72 pub const fn compact() -> Self {
73 Self {
74 pretty: false,
75 indent: 2,
76 ascii: false,
77 html: false,
78 exponent_plus: false,
79 even_ties: false,
80 }
81 }
82
83 /// The indented layout of [`to_string_pretty`](crate::to_string_pretty):
84 /// one member or item per line, two spaces per level, `": "` after keys,
85 /// empty containers as `[]` and `{}`, no trailing newline.
86 ///
87 /// # Examples
88 ///
89 /// ```
90 /// use jsonx_lib::{json, to_string_with, Format};
91 ///
92 /// assert_eq!(to_string_with(&json!([1]), Format::pretty()), "[\n 1\n]");
93 /// ```
94 #[must_use]
95 pub const fn pretty() -> Self {
96 Self {
97 pretty: true,
98 ..Self::compact()
99 }
100 }
101
102 /// The indented layout with `spaces` spaces per level (`0` puts each
103 /// member on its own line without indenting it).
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// use jsonx_lib::{json, to_string_with, Format};
109 ///
110 /// assert_eq!(to_string_with(&json!({ "a": 1 }), Format::compact().with_indent(1)), "{\n \"a\": 1\n}");
111 /// ```
112 #[must_use]
113 pub const fn with_indent(mut self, spaces: u8) -> Self {
114 self.pretty = true;
115 self.indent = spaces;
116 self
117 }
118
119 /// Whether to also escape `<`, `>`, and `&` (as `\u003c`, `\u003e`,
120 /// `\u0026`), so the output is safe inside HTML.
121 ///
122 /// # Examples
123 ///
124 /// ```
125 /// use jsonx_lib::{to_string_with, Format};
126 ///
127 /// let text = to_string_with("</script>", Format::compact().html_safe(true));
128 /// assert_eq!(text, "\"\\u003c/script\\u003e\"");
129 /// ```
130 #[must_use]
131 pub const fn html_safe(mut self, on: bool) -> Self {
132 self.html = on;
133 self
134 }
135
136 /// Whether to escape every non-ASCII character, so the output is pure
137 /// ASCII.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// use jsonx_lib::{to_string_with, Format};
143 ///
144 /// assert_eq!(to_string_with("\u{e9}\u{1f600}", Format::compact().ascii(true)), "\"\\u00e9\\ud83d\\ude00\"");
145 /// ```
146 #[must_use]
147 pub const fn ascii(mut self, on: bool) -> Self {
148 self.ascii = on;
149 self
150 }
151
152 /// Whether to write the `+` of a positive exponent in float text:
153 /// `1e+16` rather than `1e16`, as `serde_json` (1.0.147 and later),
154 /// JavaScript and Python write it. Negative exponents always have their
155 /// `-`; floats from 1e-5 up to below 1e16 are written as decimals and
156 /// have no exponent.
157 ///
158 /// # Examples
159 ///
160 /// ```
161 /// use jsonx_lib::{to_string_with, Format};
162 ///
163 /// let plus = Format::compact().exponent_plus(true);
164 /// assert_eq!(to_string_with(&[1e16, 2.5e-7, 0.5], plus), "[1e+16,2.5e-7,0.5]");
165 /// assert_eq!(to_string_with(&1e16, Format::compact()), "1e16");
166 /// ```
167 #[must_use]
168 pub const fn exponent_plus(mut self, on: bool) -> Self {
169 self.exponent_plus = on;
170 self
171 }
172
173 /// Whether an exact tie in float text goes to the even digit.
174 ///
175 /// A float is written as the shortest decimal that reads back as it, and
176 /// of those the closest. Rarely two are equally close (the float lies
177 /// exactly halfway between them; it takes 16 or 17 significant digits
178 /// for an `f64`). Both read back as the same float. By default the higher
179 /// one is written, as Rust's own formatting (`{}`, `{:e}`) picks it; with
180 /// this option, the one whose last digit is even, as `serde_json`, Java,
181 /// JavaScript and Python pick it.
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// use jsonx_lib::{to_string_with, Format};
187 ///
188 /// // 164696460098373.625 lies exactly between ...373.62 and ...373.63.
189 /// let x = 164_696_460_098_373.625_f64;
190 /// assert_eq!(to_string_with(&x, Format::compact()), "164696460098373.63");
191 /// assert_eq!(to_string_with(&x, Format::compact().even_ties(true)), "164696460098373.62");
192 /// assert_eq!(format!("{x}"), "164696460098373.63");
193 /// ```
194 #[must_use]
195 pub const fn even_ties(mut self, on: bool) -> Self {
196 self.even_ties = on;
197 self
198 }
199
200 /// Whether this is an indented layout.
201 ///
202 /// # Examples
203 ///
204 /// ```
205 /// assert!(jsonx_lib::Format::pretty().is_pretty());
206 /// assert!(!jsonx_lib::Format::default().is_pretty());
207 /// ```
208 #[must_use]
209 pub const fn is_pretty(&self) -> bool {
210 self.pretty
211 }
212
213 /// How an exact tie in float text is broken.
214 #[inline]
215 pub(crate) const fn ties(&self) -> crate::float::Ties {
216 if self.even_ties {
217 crate::float::Ties::Even
218 } else {
219 crate::float::Ties::Up
220 }
221 }
222
223 /// Whether strings need more than the minimal escaping.
224 #[inline]
225 pub(crate) const fn strict(&self) -> bool {
226 self.ascii || self.html
227 }
228}
229
230impl Default for Format {
231 /// [`Format::compact`].
232 #[inline]
233 fn default() -> Self {
234 Self::compact()
235 }
236}