jsony 0.1.10

An experimental fast compiling serialization and deserialization library for JSON like formats.
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! JSON prettifier: re-formats a JSON document with newlines and indentation.
//!
//! The implementation walks the input with the existing [`crate::parser`]
//! primitives and copies tokens verbatim from the source. It is intentionally
//! non-generic and avoids closures to keep the codegen footprint small.

use crate::json::DecodeError;
use crate::parser::{InnerParser, Parser, Peek};
use crate::{JsonError, JsonParserConfig};

/// Configuration for [`prettify`].
///
/// `indent` is the string emitted per nesting level (typically `"  "` or
/// `"\t"`). `parser` controls the same leniency knobs as the rest of the
/// crate (trailing commas, comments, trailing data).
///
/// `max_line_width` enables single-line rendering of small containers. A
/// container is kept on one line when its compact form fits the width
/// remaining at its nesting depth (`max_line_width - depth * indent.len()`).
/// The in-line key prefix is not counted, so a long key may overshoot the
/// width. `0` (the default) always expands every container.
///
/// `max_inline_depth` caps how many container levels may stack on one inlined
/// line: the outermost inlined container is level 1, a container nested inside
/// it is level 2, and so on. A container is expanded if inlining it would
/// exceed this. This bounds the work of a single inline attempt and doubles as
/// a sizing knob. The default imposes no limit.
///
/// `max_inline_object_entries` and `max_inline_array_entries` bound inlining by
/// container size: an object with more keys (or an array with more elements)
/// than its cap is always expanded, even when its compact form fits the width.
/// `0` keeps only the corresponding empty container inline. Both default to no
/// limit.
///
/// `inline_bracket_padding` inserts a space just inside the brackets of an
/// inlined container, rendering `{ "a": 1 }` and `[ 1, 2 ]` instead of
/// `{"a": 1}` and `[1, 2]`. Empty containers stay tight and expanded output is
/// unaffected. The default is `false`.
///
/// Comments (when allowed) are dropped from the output. Unquoted field keys
/// are not supported by the prettifier and will return an error even if
/// `allow_unquoted_field_keys` is set on the parser config.
#[derive(Clone, Copy)]
pub struct PrettifyConfig<'a> {
    /// Indent string emitted once per nesting level.
    pub indent: &'a str,
    /// Approximate target line width in bytes. `0` disables inlining.
    pub max_line_width: usize,
    /// Maximum container nesting permitted on a single inlined line.
    pub max_inline_depth: usize,
    /// Maximum object key count permitted on a single inlined line. `0` keeps
    /// only empty objects inline.
    pub max_inline_object_entries: usize,
    /// Maximum array element count permitted on a single inlined line. `0` keeps
    /// only empty arrays inline.
    pub max_inline_array_entries: usize,
    /// Pad the insides of inlined container brackets with a space. Empty
    /// containers are unaffected.
    pub inline_bracket_padding: bool,
    /// Parser configuration controlling leniency and recursion limits.
    pub parser: JsonParserConfig,
}

impl<'a> PrettifyConfig<'a> {
    pub const SMART: PrettifyConfig<'static> = PrettifyConfig {
        indent: "  ",
        max_line_width: 90,
        max_inline_depth: 2,
        max_inline_object_entries: 1,
        max_inline_array_entries: 8,
        inline_bracket_padding: false,
        parser: JsonParserConfig {
            recursion_limit: 128,
            allow_trailing_commas: false,
            allow_comments: false,
            allow_unquoted_field_keys: false,
            allow_trailing_data: false,
        },
    };
}

impl Default for PrettifyConfig<'_> {
    fn default() -> Self {
        Self {
            indent: "  ",
            max_line_width: 0,
            max_inline_depth: usize::MAX,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: false,
            parser: JsonParserConfig::default(),
        }
    }
}

static TRAILING_CHARACTERS: DecodeError = DecodeError {
    message: "Trailing characters",
};

/// Re-formats a JSON document with newlines and indentation.
///
/// Numbers and strings are copied verbatim from the input rather than being
/// decoded and re-encoded. Comments (when allowed via the parser config) are
/// stripped from the output.
///
/// # Errors
///
/// Returns a [`JsonError`] if the input is not valid JSON under the given
/// parser configuration.
///
/// # Example
///
/// ```
/// let input = r#"{"a":[1,2,3]}"#;
/// let out = jsony::prettify(input, &Default::default()).unwrap();
/// assert_eq!(out, "{\n  \"a\": [\n    1,\n    2,\n    3\n  ]\n}");
/// ```
pub fn prettify(json: &str, config: &PrettifyConfig<'_>) -> Result<String, JsonError> {
    let mut parser = Parser::new(json, config.parser);
    let mut out = String::with_capacity(json.len() + json.len() / 8);
    match walk(&mut parser, json, &mut out, config) {
        Ok(()) => {
            if config.parser.allow_trailing_data || parser.at.eat_whitespace().is_none() {
                Ok(out)
            } else {
                Err(JsonError::new(&TRAILING_CHARACTERS, None))
            }
        }
        Err(err) => Err(JsonError::extract(err, &mut parser)),
    }
}

fn write_newline_indent(out: &mut String, indent: &str, depth: usize) {
    out.push('\n');
    for _ in 0..depth {
        out.push_str(indent);
    }
}

/// Snapshots the parser index, advances past one scalar value (including
/// strings, where the parser walks escapes for us), then copies the consumed
/// source slice verbatim. Caller must ensure the parser is not at `{` or `[`.
fn copy_scalar_verbatim(
    p: &mut InnerParser<'_>,
    json: &str,
    out: &mut String,
) -> Result<(), &'static DecodeError> {
    let start = p.index;
    match p.skip_value() {
        Ok(()) => {}
        Err(e) => return Err(e),
    }
    out.push_str(&json[start..p.index]);
    Ok(())
}

fn emit_key(
    p: &mut InnerParser<'_>,
    json: &str,
    out: &mut String,
) -> Result<(), &'static DecodeError> {
    match copy_scalar_verbatim(p, json, out) {
        Ok(()) => {}
        Err(e) => return Err(e),
    }
    match p.discard_colon() {
        Ok(()) => {}
        Err(e) => return Err(e),
    }
    out.push_str(": ");
    Ok(())
}

/// Copies a scalar (or object key) verbatim while honoring the inline budget.
///
/// Unlike [`copy_scalar_verbatim`] the source span is measured before being
/// appended, so an oversized scalar aborts the inline attempt without first
/// copying its bytes into `out`. Returns `false` on overflow or parse error.
fn flat_scalar(p: &mut InnerParser<'_>, json: &str, out: &mut String, limit: usize) -> bool {
    let start = p.index;
    if p.skip_value().is_err() {
        return false;
    }
    let end = p.index;
    if out.len() + (end - start) > limit {
        return false;
    }
    out.push_str(&json[start..end]);
    true
}

/// Emits the compact, single-line rendering of the value at the cursor.
///
/// Separators are `", "` between elements and `": "` after keys, with no
/// newlines or indentation. Returns `false` the moment the output would exceed
/// `limit` (the maximum permitted `out.len()`), the container nesting would
/// exceed `depth` levels, a container exceeds its `max_inline_*_entries` cap, or
/// the input is malformed. On `false` the caller must truncate `out` and restore
/// the parser. `depth` is the number of container levels still permitted (the
/// current container consumes one); it also caps recursion, bounding the work of
/// a single inline attempt.
fn flat_value(
    p: &mut InnerParser<'_>,
    json: &str,
    out: &mut String,
    limit: usize,
    depth: usize,
    config: &PrettifyConfig<'_>,
    peek: Peek,
) -> bool {
    let max_obj = config.max_inline_object_entries;
    let max_arr = config.max_inline_array_entries;
    let pad = if config.inline_bracket_padding {
        " "
    } else {
        ""
    };
    match peek {
        Peek::Array => {
            if depth == 0 {
                return false;
            }
            out.push('[');
            match p.enter_seen_array() {
                Ok(Some(mut elem)) => {
                    if max_arr == 0 {
                        return false;
                    }
                    out.push_str(pad);
                    let mut elems = 1;
                    loop {
                        if !flat_value(p, json, out, limit, depth - 1, config, elem) {
                            return false;
                        }
                        match p.array_step() {
                            Ok(Some(next)) => {
                                elems += 1;
                                if elems > max_arr {
                                    return false;
                                }
                                out.push_str(", ");
                                if out.len() > limit {
                                    return false;
                                }
                                elem = next;
                            }
                            Ok(None) => {
                                out.push_str(pad);
                                out.push(']');
                                return out.len() <= limit;
                            }
                            Err(_) => return false,
                        }
                    }
                }
                Ok(None) => {
                    out.push(']');
                    out.len() <= limit
                }
                Err(_) => false,
            }
        }
        Peek::Object => {
            if depth == 0 {
                return false;
            }
            out.push('{');
            match p.enter_seen_object_at_first_key() {
                Ok(Some(())) => {
                    if max_obj == 0 {
                        return false;
                    }
                    out.push_str(pad);
                    let mut keys = 1;
                    loop {
                        if !flat_scalar(p, json, out, limit) {
                            return false;
                        }
                        if p.discard_colon().is_err() {
                            return false;
                        }
                        out.push_str(": ");
                        if out.len() > limit {
                            return false;
                        }
                        let value = match p.peek() {
                            Ok(value) => value,
                            Err(_) => return false,
                        };
                        if !flat_value(p, json, out, limit, depth - 1, config, value) {
                            return false;
                        }
                        match p.object_step_at_key() {
                            Ok(Some(())) => {
                                keys += 1;
                                if keys > max_obj {
                                    return false;
                                }
                                out.push_str(", ");
                                if out.len() > limit {
                                    return false;
                                }
                            }
                            Ok(None) => {
                                out.push_str(pad);
                                out.push('}');
                                return out.len() <= limit;
                            }
                            Err(_) => return false,
                        }
                    }
                }
                Ok(None) => {
                    out.push('}');
                    out.len() <= limit
                }
                Err(_) => false,
            }
        }
        _ => flat_scalar(p, json, out, limit),
    }
}

/// One entry per open container. The vector length is the current nesting
/// depth used for indentation. Growth is bounded by the parser's
/// `recursion_limit`: every push is paired with a `recursion_limit` decrement
/// inside `enter_seen_*`, and every pop with an increment inside the `*_step`
/// close, so the walk stays iterative and cannot overflow the native stack.
#[derive(Clone, Copy)]
enum Frame {
    Array,
    Object,
}

fn walk(
    parser: &mut Parser<'_>,
    json: &str,
    out: &mut String,
    config: &PrettifyConfig<'_>,
) -> Result<(), &'static DecodeError> {
    let indent = config.indent;
    let max_line_width = config.max_line_width;
    let max_inline_depth = config.max_inline_depth;
    let mut stack: Vec<Frame> = Vec::with_capacity(16);

    let mut peek = match parser.at.peek() {
        Ok(p) => p,
        Err(e) => return Err(e),
    };

    'outer: loop {
        // Try to keep the container on a single line when its compact form fits
        // the width remaining at this depth. On overflow or parse error the
        // partial output is truncated and the parser rewound, then the expanded
        // path below runs (re-surfacing any genuine error).
        let budget = max_line_width.saturating_sub(stack.len() * indent.len());
        let inlined =
            if budget > 0 && max_inline_depth > 0 && matches!(peek, Peek::Array | Peek::Object) {
                let start = out.len();
                let snap_index = parser.at.index;
                let snap_limit = parser.at.config.recursion_limit;
                if flat_value(
                    &mut parser.at,
                    json,
                    out,
                    start + budget,
                    max_inline_depth,
                    config,
                    peek,
                ) {
                    true
                } else {
                    out.truncate(start);
                    parser.at.index = snap_index;
                    parser.at.config.recursion_limit = snap_limit;
                    false
                }
            } else {
                false
            };

        if !inlined {
            match peek {
                Peek::Array => {
                    out.push('[');
                    match parser.at.enter_seen_array() {
                        Ok(Some(p)) => {
                            stack.push(Frame::Array);
                            write_newline_indent(out, indent, stack.len());
                            peek = p;
                            continue 'outer;
                        }
                        Ok(None) => {
                            out.push(']');
                        }
                        Err(e) => return Err(e),
                    }
                }
                Peek::Object => {
                    out.push('{');
                    match parser.at.enter_seen_object_at_first_key() {
                        Ok(Some(())) => {
                            stack.push(Frame::Object);
                            write_newline_indent(out, indent, stack.len());
                            match emit_key(&mut parser.at, json, out) {
                                Ok(()) => {}
                                Err(e) => return Err(e),
                            }
                            peek = match parser.at.peek() {
                                Ok(p) => p,
                                Err(e) => return Err(e),
                            };
                            continue 'outer;
                        }
                        Ok(None) => {
                            out.push('}');
                        }
                        Err(e) => return Err(e),
                    }
                }
                _ => match copy_scalar_verbatim(&mut parser.at, json, out) {
                    Ok(()) => {}
                    Err(e) => return Err(e),
                },
            }
        }

        loop {
            let top = match stack.last() {
                Some(&t) => t,
                None => return Ok(()),
            };
            match top {
                Frame::Object => match parser.at.object_step_at_key() {
                    Ok(Some(())) => {
                        out.push(',');
                        write_newline_indent(out, indent, stack.len());
                        match emit_key(&mut parser.at, json, out) {
                            Ok(()) => {}
                            Err(e) => return Err(e),
                        }
                        peek = match parser.at.peek() {
                            Ok(p) => p,
                            Err(e) => return Err(e),
                        };
                        continue 'outer;
                    }
                    Ok(None) => {
                        stack.pop();
                        write_newline_indent(out, indent, stack.len());
                        out.push('}');
                    }
                    Err(e) => return Err(e),
                },
                Frame::Array => match parser.at.array_step() {
                    Ok(Some(p)) => {
                        out.push(',');
                        write_newline_indent(out, indent, stack.len());
                        peek = p;
                        continue 'outer;
                    }
                    Ok(None) => {
                        stack.pop();
                        write_newline_indent(out, indent, stack.len());
                        out.push(']');
                    }
                    Err(e) => return Err(e),
                },
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pretty(json: &str) -> String {
        prettify(json, &PrettifyConfig::default()).unwrap()
    }

    #[test]
    fn empty_containers() {
        assert_eq!(pretty("[]"), "[]");
        assert_eq!(pretty("{}"), "{}");
        assert_eq!(pretty("  []  "), "[]");
    }

    #[test]
    fn scalars() {
        assert_eq!(pretty("null"), "null");
        assert_eq!(pretty("true"), "true");
        assert_eq!(pretty("false"), "false");
        assert_eq!(pretty("42"), "42");
        assert_eq!(pretty("-3.14e2"), "-3.14e2");
        assert_eq!(pretty(r#""hello""#), r#""hello""#);
    }

    #[test]
    fn nested_mixed() {
        let input = r#"{"a":[1,2,{"b":null}],"c":"x\n"}"#;
        let expected = "{\n  \"a\": [\n    1,\n    2,\n    {\n      \"b\": null\n    }\n  ],\n  \"c\": \"x\\n\"\n}";
        assert_eq!(pretty(input), expected);
    }

    #[test]
    fn strings_preserve_escapes_verbatim() {
        // Escape sequences and UTF-8 bytes are copied byte-for-byte.
        let input = r#"["a\nb","ÿ","\\","\""]"#;
        let expected = "[\n  \"a\\nb\",\n  \"ÿ\",\n  \"\\\\\",\n  \"\\\"\"\n]";
        assert_eq!(pretty(input), expected);

        // \u escapes also pass through unchanged (not decoded to UTF-8 bytes).
        let input_u = "[\"\\u00ff\"]";
        let expected_u = "[\n  \"\\u00ff\"\n]";
        assert_eq!(pretty(input_u), expected_u);
    }

    #[test]
    fn numbers_verbatim() {
        let input = r#"[0,1,-1,1.5,1e10,1.5e-3,1E+2]"#;
        let expected = "[\n  0,\n  1,\n  -1,\n  1.5,\n  1e10,\n  1.5e-3,\n  1E+2\n]";
        assert_eq!(pretty(input), expected);
    }

    #[test]
    fn custom_indent() {
        let cfg = PrettifyConfig {
            indent: "\t",
            max_line_width: 0,
            max_inline_depth: usize::MAX,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: false,
            parser: JsonParserConfig::default(),
        };
        let out = prettify(r#"{"a":1}"#, &cfg).unwrap();
        assert_eq!(out, "{\n\t\"a\": 1\n}");
    }

    #[test]
    fn nested_empty_containers_inline() {
        assert_eq!(pretty(r#"[[],{}]"#), "[\n  [],\n  {}\n]");
    }

    #[test]
    fn malformed_returns_error() {
        assert!(prettify("{", &PrettifyConfig::default()).is_err());
        assert!(prettify("[1,]", &PrettifyConfig::default()).is_err());
        assert!(prettify("not json", &PrettifyConfig::default()).is_err());
    }

    #[test]
    fn trailing_data_rejected_by_default() {
        assert!(prettify("1 2", &PrettifyConfig::default()).is_err());
    }

    #[test]
    fn trailing_data_allowed_with_flag() {
        let cfg = PrettifyConfig {
            indent: "  ",
            max_line_width: 0,
            max_inline_depth: usize::MAX,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: false,
            parser: JsonParserConfig {
                allow_trailing_data: true,
                ..JsonParserConfig::default()
            },
        };
        assert_eq!(prettify("1 garbage", &cfg).unwrap(), "1");
    }

    #[test]
    fn trailing_commas_lenient() {
        let cfg = PrettifyConfig {
            indent: "  ",
            max_line_width: 0,
            max_inline_depth: usize::MAX,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: false,
            parser: JsonParserConfig {
                allow_trailing_commas: true,
                ..JsonParserConfig::default()
            },
        };
        assert_eq!(prettify("[1,2,]", &cfg).unwrap(), "[\n  1,\n  2\n]");
    }

    #[test]
    fn deep_nesting_is_iterative() {
        // A naive recursive prettifier would overflow the native stack here.
        // The iterative walk must surface the parser's recursion_limit error
        // instead of crashing.
        let deep = format!("{}1{}", "[".repeat(100_000), "]".repeat(100_000));
        assert!(prettify(&deep, &PrettifyConfig::default()).is_err());

        // Nesting within the default recursion_limit round-trips.
        let shallow = format!("{}1{}", "[".repeat(100), "]".repeat(100));
        assert!(prettify(&shallow, &PrettifyConfig::default()).is_ok());
    }

    #[test]
    fn unquoted_keys_unsupported() {
        let cfg = PrettifyConfig {
            indent: "  ",
            max_line_width: 0,
            max_inline_depth: usize::MAX,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: false,
            parser: JsonParserConfig {
                allow_unquoted_field_keys: true,
                ..JsonParserConfig::default()
            },
        };
        assert!(prettify("{a:1}", &cfg).is_err());
    }

    fn pretty_width(json: &str, max_line_width: usize) -> String {
        pretty_full(json, max_line_width, usize::MAX)
    }

    fn pretty_caps(
        json: &str,
        max_inline_object_entries: usize,
        max_inline_array_entries: usize,
    ) -> String {
        let cfg = PrettifyConfig {
            indent: "  ",
            max_line_width: 80,
            max_inline_depth: usize::MAX,
            max_inline_object_entries,
            max_inline_array_entries,
            inline_bracket_padding: false,
            parser: JsonParserConfig::default(),
        };
        prettify(json, &cfg).unwrap()
    }

    fn pretty_pad(json: &str) -> String {
        let cfg = PrettifyConfig {
            indent: "  ",
            max_line_width: 80,
            max_inline_depth: usize::MAX,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: true,
            parser: JsonParserConfig::default(),
        };
        prettify(json, &cfg).unwrap()
    }

    fn pretty_obj(json: &str, max_inline_object_entries: usize) -> String {
        pretty_caps(json, max_inline_object_entries, usize::MAX)
    }

    fn pretty_arr(json: &str, max_inline_array_entries: usize) -> String {
        pretty_caps(json, usize::MAX, max_inline_array_entries)
    }

    #[test]
    fn inline_object_entries_cap() {
        // A two-key object inlines only when the cap admits both keys.
        let input = r#"{"a":1,"b":2}"#;
        assert_eq!(pretty_obj(input, 2), r#"{"a": 1, "b": 2}"#);
        assert_eq!(pretty_obj(input, 1), "{\n  \"a\": 1,\n  \"b\": 2\n}");

        // Zero keeps only empty objects inline.
        assert_eq!(pretty_obj(r#"{"a":1}"#, 0), "{\n  \"a\": 1\n}");
        assert_eq!(pretty_obj("{}", 0), "{}");
    }

    #[test]
    fn inline_object_entries_cap_propagates() {
        // An oversized object blocks its enclosing array from inlining, while a
        // sibling within the key budget still collapses on its own line.
        let input = r#"[{"a":1,"b":2},{"c":3}]"#;
        assert_eq!(
            pretty_obj(input, 1),
            "[\n  {\n    \"a\": 1,\n    \"b\": 2\n  },\n  {\"c\": 3}\n]"
        );
    }

    #[test]
    fn inline_array_entries_cap() {
        // A three-element array inlines only when the cap admits all elements.
        let input = r#"[1,2,3]"#;
        assert_eq!(pretty_arr(input, 3), "[1, 2, 3]");
        assert_eq!(pretty_arr(input, 2), "[\n  1,\n  2,\n  3\n]");

        // Zero keeps only empty arrays inline.
        assert_eq!(pretty_arr(r#"[1]"#, 0), "[\n  1\n]");
        assert_eq!(pretty_arr("[]", 0), "[]");
    }

    #[test]
    fn inline_array_entries_cap_propagates() {
        // An oversized array blocks its enclosing object from inlining, while a
        // sibling within the element budget still collapses on its own line.
        let input = r#"{"a":[1,2,3],"b":[9]}"#;
        assert_eq!(
            pretty_arr(input, 2),
            "{\n  \"a\": [\n    1,\n    2,\n    3\n  ],\n  \"b\": [9]\n}"
        );
    }

    #[test]
    fn inline_caps_are_independent() {
        // Capping objects to 0 still lets a nested array inline.
        assert_eq!(
            pretty_caps(r#"{"a":[1,2,3]}"#, 0, usize::MAX),
            "{\n  \"a\": [1, 2, 3]\n}"
        );
        // Capping arrays to 0 still lets nested objects inline.
        assert_eq!(
            pretty_caps(r#"[{"a":1},{"b":2}]"#, usize::MAX, 0),
            "[\n  {\"a\": 1},\n  {\"b\": 2}\n]"
        );
    }

    #[test]
    fn inline_bracket_padding_pads_non_empty() {
        // Every inlined bracket gains an inner space.
        assert_eq!(pretty_pad(r#"{"a":[1,2]}"#), r#"{ "a": [ 1, 2 ] }"#);
    }

    #[test]
    fn inline_bracket_padding_skips_empty() {
        // Empty containers stay tight even with padding enabled.
        assert_eq!(pretty_pad(r#"[{},[]]"#), "[ {}, [] ]");
        assert_eq!(pretty_pad("{}"), "{}");
        assert_eq!(pretty_pad("[]"), "[]");
    }

    fn pretty_full(json: &str, max_line_width: usize, max_inline_depth: usize) -> String {
        let cfg = PrettifyConfig {
            indent: "  ",
            max_line_width,
            max_inline_depth,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: false,
            parser: JsonParserConfig::default(),
        };
        prettify(json, &cfg).unwrap()
    }

    #[test]
    fn inline_small_array() {
        // The object (flat 23 > 20) expands, its array value (flat 16 <= 18)
        // inlines, and the inner arrays inline within it.
        assert_eq!(
            pretty_width(r#"{"a":[[0,1],[1,0]]}"#, 20),
            "{\n  \"a\": [[0, 1], [1, 0]]\n}"
        );
    }

    #[test]
    fn inline_whole_document() {
        // A width wide enough for the whole compact form collapses everything.
        assert_eq!(
            pretty_width(r#"{"a":[[0,1],[1,0]]}"#, 80),
            "{\"a\": [[0, 1], [1, 0]]}"
        );
    }

    #[test]
    fn width_zero_is_always_expand() {
        // Width 0 reproduces the always-expand behavior exactly.
        let input = r#"{"a":[1,2,3]}"#;
        assert_eq!(pretty_width(input, 0), pretty(input));
    }

    #[test]
    fn depth_tightens_budget() {
        // `[1, 2]` is 6 bytes. At depth 1 the budget is 8 - 2 = 6 so it inlines;
        // one level deeper the budget is 8 - 4 = 4 so the same array expands.
        // The filler siblings keep each ancestor too wide to collapse.
        let shallow = pretty_width(r#"[[1,2],0,0,0,0,0]"#, 8);
        assert!(shallow.contains("[1, 2]"), "{shallow}");

        let deep = pretty_width(r#"[[[1,2],0,0,0,0,0]]"#, 8);
        assert!(!deep.contains("[1, 2]"), "{deep}");
    }

    #[test]
    fn width_boundary() {
        // Top-level array `[1, 2, 3]` is exactly 9 bytes.
        assert_eq!(pretty_width(r#"[1,2,3]"#, 9), "[1, 2, 3]");
        assert_eq!(pretty_width(r#"[1,2,3]"#, 8), "[\n  1,\n  2,\n  3\n]");
    }

    #[test]
    fn inline_mixed_object() {
        // The short value inlines, the long one expands.
        assert_eq!(
            pretty_width(r#"{"a":[1,2],"b":[100,200,300,400]}"#, 14),
            "{\n  \"a\": [1, 2],\n  \"b\": [\n    100,\n    200,\n    300,\n    400\n  ]\n}"
        );
    }

    #[test]
    fn inline_depth_caps_nesting() {
        // Width is generous, so only the depth cap matters. The levels are:
        // object (1), the array value (2), the inner arrays (3).
        let input = r#"{"a":[[0,1],[1,0]]}"#;

        // Depth 1: only scalar-only containers inline, so just the inner arrays.
        assert_eq!(
            pretty_full(input, 80, 1),
            "{\n  \"a\": [\n    [0, 1],\n    [1, 0]\n  ]\n}"
        );
        // Depth 2: the array value inlines (its inner arrays are level 2 within
        // it), but the object still expands.
        assert_eq!(pretty_full(input, 80, 2), "{\n  \"a\": [[0, 1], [1, 0]]\n}");
        // Depth 3: the whole document collapses.
        assert_eq!(pretty_full(input, 80, 3), "{\"a\": [[0, 1], [1, 0]]}");
    }

    #[test]
    fn inline_preserves_errors() {
        let cfg = PrettifyConfig {
            indent: "  ",
            max_line_width: 80,
            max_inline_depth: usize::MAX,
            max_inline_object_entries: usize::MAX,
            max_inline_array_entries: usize::MAX,
            inline_bracket_padding: false,
            parser: JsonParserConfig::default(),
        };
        assert!(prettify("[1,2,]", &cfg).is_err());
        assert!(prettify("{\"a\":}", &cfg).is_err());
        assert!(prettify("[1,2", &cfg).is_err());
    }
}