nojson 0.3.11

A flexible Rust JSON library with no dependencies, no macros, no unsafe and optional no_std support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use core::fmt::{Display, Write};

use crate::DisplayJson;

/// A formatter for JSON values that controls the layout and formatting of the output.
///
/// [`JsonFormatter`] wraps the [`core::fmt::Formatter`] and provides methods specifically designed
/// for generating well-formed JSON with customizable formatting options like indentation and spacing.
///
/// This formatter is primarily used when implementing the [`DisplayJson`] trait or when using the
/// [`json()`](crate::json) function for in-place JSON generation.
///
/// # Examples
///
/// Basic usage with the [`json()`](crate::json) function:
/// ```
/// // Generate compact JSON
/// let compact = nojson::json(|f| f.value([1, 2, 3]));
/// assert_eq!(compact.to_string(), "[1,2,3]");
///
/// // Generate pretty-printed JSON
/// let pretty = nojson::json(|f| {
///     f.set_indent_size(2);
///     f.set_spacing(true);
///     f.value([1, 2, 3])
/// });
///
/// assert_eq!(
///     format!("\n{}", pretty),
///     r#"
/// [
///   1,
///   2,
///   3
/// ]"#
/// );
/// ```
pub struct JsonFormatter<'a, 'b> {
    inner: &'a mut core::fmt::Formatter<'b>,
    level: usize,
    indent_size: usize,
    spacing: bool,
}

impl<'a, 'b> JsonFormatter<'a, 'b> {
    pub(crate) fn new(inner: &'a mut core::fmt::Formatter<'b>) -> Self {
        Self {
            inner,
            level: 0,
            indent_size: 0,
            spacing: false,
        }
    }

    /// Formats a value that implements the [`DisplayJson`] trait.
    ///
    /// This is the primary method for writing a value to the JSON output.
    ///
    /// # Examples
    ///
    /// ```
    /// let output = nojson::json(|f| f.value([1, 2, 3]));
    /// assert_eq!(output.to_string(), "[1,2,3]");
    /// ```
    pub fn value<T: DisplayJson>(&mut self, value: T) -> core::fmt::Result {
        value.fmt(self)
    }

    /// Formats a value as a JSON string with proper escaping.
    ///
    /// This method handles the necessary escaping of special characters in JSON strings,
    /// including quotes, backslashes, control characters, etc.
    ///
    /// # Examples
    ///
    /// ```
    /// let output = nojson::json(|f| f.string("Hello\nWorld"));
    /// assert_eq!(output.to_string(), r#""Hello\nWorld""#);
    /// ```
    pub fn string<T: Display>(&mut self, content: T) -> core::fmt::Result {
        write!(self.inner, "\"")?;
        {
            let mut fmt = JsonStringContentFormatter { inner: self.inner };
            write!(fmt, "{content}")?;
        }
        write!(self.inner, "\"")?;
        Ok(())
    }

    /// Creates a JSON array with the provided formatting function.
    ///
    /// This method starts a new JSON array and provides a [`JsonArrayFormatter`] to the callback
    /// function for adding elements to the array. It handles proper indentation, spacing, and
    /// brackets placement.
    ///
    /// # Examples
    ///
    /// ```
    /// let output = nojson::json(|f| {
    ///     f.array(|f| {
    ///         f.element(1)?;
    ///         f.element(2)?;
    ///         f.element(3)
    ///     })
    /// });
    /// assert_eq!(output.to_string(), "[1,2,3]");
    ///
    /// // With pretty-printing
    /// let pretty = nojson::json(|f| {
    ///     f.set_indent_size(2);
    ///     f.set_spacing(true);
    ///     f.array(|f| {
    ///         f.element(1)?;
    ///         f.element(2)?;
    ///         f.element(3)
    ///     })
    /// });
    /// ```
    pub fn array<F>(&mut self, f: F) -> core::fmt::Result
    where
        F: FnOnce(&mut JsonArrayFormatter<'a, 'b, '_>) -> core::fmt::Result,
    {
        write!(self.inner, "[")?;

        let indent_size = self.indent_size;
        let spacing = self.spacing;
        self.level += 1;
        let mut array = JsonArrayFormatter {
            fmt: self,
            empty: true,
        };
        f(&mut array)?;
        let empty = array.empty;
        self.level -= 1;
        self.indent_size = indent_size;
        self.spacing = spacing;

        if !empty {
            self.indent()?;
        }
        write!(self.inner, "]")?;

        Ok(())
    }

    /// Creates a JSON object with the provided formatting function.
    ///
    /// This method starts a new JSON object and provides a [`JsonObjectFormatter`] to the callback
    /// function for adding members to the object. It handles proper indentation, spacing, and
    /// braces placement.
    ///
    /// # Examples
    ///
    /// ```
    /// let output = nojson::json(|f| {
    ///     f.object(|f| {
    ///         f.member("name", "Alice")?;
    ///         f.member("age", 30)
    ///     })
    /// });
    /// assert_eq!(output.to_string(), r#"{"name":"Alice","age":30}"#);
    ///
    /// // With pretty-printing
    /// let pretty = nojson::json(|f| {
    ///     f.set_indent_size(2);
    ///     f.set_spacing(true);
    ///     f.object(|f| {
    ///         f.member("name", "Alice")?;
    ///         f.member("age", 30)
    ///     })
    /// });
    /// ```
    pub fn object<F>(&mut self, f: F) -> core::fmt::Result
    where
        F: FnOnce(&mut JsonObjectFormatter<'a, 'b, '_>) -> core::fmt::Result,
    {
        write!(self.inner, "{{")?;

        let indent_size = self.indent_size;
        let spacing = self.spacing;
        self.level += 1;
        let mut object = JsonObjectFormatter {
            fmt: self,
            empty: true,
        };
        f(&mut object)?;
        let empty = object.empty;
        self.level -= 1;
        self.indent_size = indent_size;
        self.spacing = spacing;

        if !empty {
            if self.indent_size > 0 {
                self.indent()?;
            } else if self.spacing {
                write!(self.inner, " ")?;
            }
        }
        write!(self.inner, "}}")?;

        Ok(())
    }

    /// Returns a mutable reference to the inner [`core::fmt::Formatter`].
    ///
    /// This method provides direct access to the wrapped formatter, which can be useful
    /// for implementing custom formatting logic for primitive types.
    ///
    /// # Note
    ///
    /// It is the responsibility of the user to ensure that the content written to the inner formatter is valid JSON.
    pub fn inner_mut(&mut self) -> &mut core::fmt::Formatter<'b> {
        self.inner
    }

    /// Returns the current indentation level.
    ///
    /// The indentation level increases when entering arrays and objects, and
    /// decreases when exiting them.
    pub fn get_level(&self) -> usize {
        self.level
    }

    /// Returns the number of spaces used for each indentation level.
    pub fn get_indent_size(&self) -> usize {
        self.indent_size
    }

    /// Sets the number of spaces used for each indentation level.
    ///
    /// Note that this setting only affects the current and higher indentation levels.
    pub fn set_indent_size(&mut self, size: usize) {
        self.indent_size = size;
    }

    /// Returnes whether inserting a space after ':', ',', and '{'.
    pub fn get_spacing(&self) -> bool {
        self.spacing
    }

    /// Sets whether inserting a space after ':', ',', and '{'.
    ///
    /// Note that this setting only affects the current and higher indentation levels.
    pub fn set_spacing(&mut self, enable: bool) {
        self.spacing = enable;
    }

    fn indent(&mut self) -> core::fmt::Result {
        if self.indent_size > 0 {
            let total = self.indent_size * self.level;
            write!(self.inner, "\n{:total$}", "", total = total)?;
        }
        Ok(())
    }
}

impl core::fmt::Debug for JsonFormatter<'_, '_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("JsonFormatter")
            .field("level", &self.level)
            .field("indent_size", &self.indent_size)
            .field("spacing", &self.spacing)
            .finish_non_exhaustive()
    }
}

struct JsonStringContentFormatter<'a, 'b> {
    inner: &'a mut core::fmt::Formatter<'b>,
}

impl core::fmt::Write for JsonStringContentFormatter<'_, '_> {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        let bytes = s.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            let skip = crate::swar::skip_plain_ascii_bytes(&bytes[i..]);
            if skip > 0 {
                self.inner.write_str(&s[i..i + skip])?;
                i += skip;
                continue;
            }
            // Non-ASCII bytes don't need escaping in JSON; emit the entire
            // contiguous non-ASCII run in one write_str rather than
            // re-decoding char-by-char. Safe because `s` is valid UTF-8 and
            // `skip_non_ascii_bytes` stops at the next ASCII byte, which is
            // also a UTF-8 boundary.
            if bytes[i] >= 0x80 {
                let run = crate::swar::skip_non_ascii_bytes(&bytes[i..]);
                self.inner.write_str(&s[i..i + run])?;
                i += run;
                continue;
            }
            // ASCII byte that needs escaping: ", \, or a control character.
            let b = bytes[i];
            match b {
                b'"' => self.inner.write_str("\\\"")?,
                b'\\' => self.inner.write_str("\\\\")?,
                b'\n' => self.inner.write_str("\\n")?,
                b'\r' => self.inner.write_str("\\r")?,
                b'\t' => self.inner.write_str("\\t")?,
                0x08 => self.inner.write_str("\\b")?,
                0x0C => self.inner.write_str("\\f")?,
                _ => write!(self.inner, "\\u{:04x}", b as u32)?,
            }
            i += 1;
        }
        Ok(())
    }
}

/// A formatter for JSON arrays.
///
/// This struct is created by the [`JsonFormatter::array()`] method and provides
/// methods for adding elements to a JSON array with proper formatting, spacing,
/// and indentation.
///
/// # Examples
///
/// ```
/// let output = nojson::json(|f| {
///     f.array(|f| {
///         f.element(1)?;
///         f.element("test")?;
///         f.element(true)
///     })
/// });
/// assert_eq!(output.to_string(), r#"[1,"test",true]"#);
///
/// // With pretty-printing
/// let pretty = nojson::json(|f| {
///     f.set_indent_size(2);
///     f.set_spacing(true);
///     f.array(|f| {
///         f.elements([1, 2, 3])
///     })
/// });
/// ```
pub struct JsonArrayFormatter<'a, 'b, 'c> {
    fmt: &'c mut JsonFormatter<'a, 'b>,
    empty: bool,
}

impl JsonArrayFormatter<'_, '_, '_> {
    /// Adds a single element to the JSON array.
    ///
    /// This method handles adding the appropriate comma separators between elements
    /// and applies the current formatting rules like indentation and spacing.
    ///
    /// # Examples
    ///
    /// ```
    /// let output = nojson::json(|f| {
    ///     f.array(|f| {
    ///         f.element(1)?;
    ///         f.element("text")?;
    ///         f.element([9.87])
    ///     })
    /// });
    /// ```
    pub fn element<T: DisplayJson>(&mut self, element: T) -> core::fmt::Result {
        if !self.empty {
            write!(self.fmt.inner, ",")?;
            if self.fmt.spacing && self.fmt.indent_size == 0 {
                write!(self.fmt.inner, " ")?;
            }
        }
        self.fmt.indent()?;
        self.fmt.value(element)?;
        self.empty = false;
        Ok(())
    }

    /// Adds multiple elements to the JSON array from an iterator.
    ///
    /// This is a convenience method that iterates over the provided collection and
    /// adds each item as an element using the [`JsonArrayFormatter::element()`] method.
    ///
    /// # Examples
    ///
    /// ```
    /// let values = vec![1, 2, 3];
    /// let output = nojson::json(|f| {
    ///     f.array(|f| f.elements(&values))
    /// });
    /// assert_eq!(output.to_string(), "[1,2,3]");
    ///
    /// // Works with any iterable collection
    /// let output = nojson::json(|f| {
    ///     f.array(|f| f.elements([true, false, true]))
    /// });
    /// ```
    pub fn elements<I>(&mut self, elements: I) -> core::fmt::Result
    where
        I: IntoIterator,
        I::Item: DisplayJson,
    {
        for element in elements {
            self.element(element)?;
        }
        Ok(())
    }
}

/// A formatter for JSON objects.
///
/// This struct is created by the [`JsonFormatter::object()`] method and provides
/// methods for adding name-value pairs (members) to a JSON object with proper
/// formatting, spacing, and indentation.
///
/// # Examples
///
/// ```
/// let output = nojson::json(|f| {
///     f.object(|f| {
///         f.member("name", "Alice")?;
///         f.member("age", 30)
///     })
/// });
/// assert_eq!(output.to_string(), r#"{"name":"Alice","age":30}"#);
///
/// // With pretty-printing
/// let pretty = nojson::json(|f| {
///     f.set_indent_size(2);
///     f.set_spacing(true);
///     f.object(|f| {
///         f.member("name", "Alice")?;
///         f.member("age", 30)
///     })
/// });
/// ```
pub struct JsonObjectFormatter<'a, 'b, 'c> {
    fmt: &'c mut JsonFormatter<'a, 'b>,
    empty: bool,
}

impl JsonObjectFormatter<'_, '_, '_> {
    /// Adds a single name-value pair (member) to the JSON object.
    ///
    /// This method handles adding the appropriate comma separators between members
    /// and applies the current formatting rules like indentation and spacing.
    ///
    /// # Examples
    ///
    /// ```
    /// let output = nojson::json(|f| {
    ///     f.object(|f| {
    ///         f.member("name", "Alice")?;
    ///         f.member("age", 30)?;
    ///         f.member("active", true)
    ///     })
    /// });
    /// ```
    pub fn member<N, V>(&mut self, name: N, value: V) -> core::fmt::Result
    where
        N: Display,
        V: DisplayJson,
    {
        if !self.empty {
            write!(self.fmt.inner, ",")?;
            if self.fmt.spacing && self.fmt.indent_size == 0 {
                write!(self.fmt.inner, " ")?;
            }
        } else if self.fmt.spacing && self.fmt.indent_size == 0 {
            write!(self.fmt.inner, " ")?;
        }

        self.fmt.indent()?;
        self.fmt.string(name)?;
        write!(self.fmt.inner, ":")?;
        if self.fmt.spacing {
            write!(self.fmt.inner, " ")?;
        }
        self.fmt.value(value)?;
        self.empty = false;
        Ok(())
    }

    /// Adds multiple name-value pairs (members) to the JSON object from an iterator.
    ///
    /// This is a convenience method that iterates over the provided collection and
    /// adds each item as a member using the [`JsonObjectFormatter::member()`] method.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::BTreeMap;
    ///
    /// let mut map = BTreeMap::new();
    /// map.insert("name", "Alice");
    /// map.insert("age", "30");
    ///
    /// let output = nojson::json(|f| {
    ///     f.object(|f| f.members(&map))
    /// });
    /// ```
    pub fn members<I, N, V>(&mut self, members: I) -> core::fmt::Result
    where
        I: IntoIterator<Item = (N, V)>,
        N: Display,
        V: DisplayJson,
    {
        for (name, value) in members {
            self.member(name, value)?;
        }
        Ok(())
    }
}