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