tabnas-render 0.2.1

Renderers for the tabnas transducer protocols: incremental CSV and JSON text from streamed tables and events.
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
//! `JsonEvents/1` as JSON text.
//!
//! The renderer writes what it is given, in the order it is given, with
//! nothing held back but the separators: a comma is written when the next
//! item begins, never speculatively, so an aborted document is still a
//! prefix of a valid one. Compact output is the standard profile; a fixed
//! indent is a separate profile for people rather than programs, and the
//! two differ only in whitespace. Strings are escaped as RFC 8259 requires
//! and no more: `"`, `\`, and the control characters, with everything else,
//! non-ASCII included, written as itself, because the output is UTF-8 and
//! an escape would only make it longer.
//!
//! The renderer validates the event sequence as it goes, because a
//! third-party source is as much a source of `JsonEvents/1` as the
//! standard ones are: one root value, keys only where a member begins,
//! balanced containers, one end.

use tabnas_alchemy::shared::{Fail, Flow, JsonEvent, Number, Sink};

use crate::number::{check_number, write_value};
use crate::text::TextOut;

/// The JSON profile, which is one of alchemy's shared types.
pub use tabnas_alchemy::shared::json::JsonOptions;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Frame {
    Object { first: bool, expecting_key: bool },
    Array { first: bool },
}

/// Renders `JsonEvents/1` as JSON text.
///
/// Exactly one root value, then `End`; a second root, an `End` before the
/// root or with a container open, a key outside an object or where a value
/// is due, a value where a key is due, an unbalanced or mismatched close,
/// and any event after `End` are `PROTOCOL_ORDER_ERROR`. Numbers write
/// their lexeme when it is a JSON number (`INVALID_NUMBER` otherwise) and
/// the shortest text that reads back as the value when there is none; NaN
/// and infinity have no JSON form and are `TARGET_VALUE_UNREPRESENTABLE`,
/// whatever lexeme stands beside them. A number is checked before its
/// separator is written, so a rejected value leaves no trace. The output
/// is flushed once, at `End`; a failure found after any text was written
/// says so with `committed_output`.
pub struct JsonRenderer<O: TextOut> {
    out: O,
    options: JsonOptions,
    /// Spaces per level; zero is compact.
    indent: usize,
    stack: Vec<Frame>,
    root_done: bool,
    ended: bool,
    emitted: bool,
    scratch: String,
    /// Spaces, grown to the widest indentation written so far.
    pad: String,
}

impl<O: TextOut> JsonRenderer<O> {
    pub fn new(out: O, options: JsonOptions) -> Self {
        JsonRenderer {
            indent: options.indent.unwrap_or(0),
            out,
            options,
            stack: Vec::new(),
            root_done: false,
            ended: false,
            emitted: false,
            scratch: String::new(),
            pad: String::new(),
        }
    }

    pub fn options(&self) -> &JsonOptions {
        &self.options
    }

    /// Containers currently open.
    pub fn depth(&self) -> usize {
        self.stack.len()
    }

    /// Whether `End` has been rendered.
    pub fn is_done(&self) -> bool {
        self.ended
    }

    pub fn into_inner(self) -> O {
        self.out
    }

    /// Mark a failure as leaving partial output when text this renderer
    /// wrote has reached the destination; text still buffered in the
    /// output has not, and the output knows which.
    fn fail(&self, f: Fail) -> Fail {
        if self.emitted && self.out.has_committed() {
            f.committed()
        } else {
            f
        }
    }

    fn protocol(&self, message: &str) -> Fail {
        self.fail(Fail::protocol(message))
    }

    fn put(&mut self, s: &str) -> Result<(), Fail> {
        self.emitted = true;
        self.out.write_str(s)
    }

    /// The escaped form of `s`, streamed: each run that needs no escaping
    /// is written as it is and each escape as it comes, so the renderer
    /// never holds a copy of a scalar. Building the escaped text first would
    /// keep up to six bytes per byte of the largest string seen for the
    /// renderer's whole life, against the promise that nothing here holds a
    /// document.
    fn put_string(&mut self, s: &str) -> Result<(), Fail> {
        self.put("\"")?;
        let mut rest = s;
        while let Some((i, width, escaped)) = rest
            .char_indices()
            .find_map(|(i, c)| escape(c).map(|e| (i, c.len_utf8(), e)))
        {
            if i > 0 {
                self.put(&rest[..i])?;
            }
            self.put(escaped)?;
            rest = &rest[i + width..];
        }
        if !rest.is_empty() {
            self.put(rest)?;
        }
        self.put("\"")
    }

    /// Write a number that [`check_number`] has passed: the lexeme as it
    /// is, or the value formatted once into the reused scratch buffer.
    fn put_number(&mut self, n: Number<'_>) -> Result<(), Fail> {
        match n.lexeme {
            Some(l) => self.put(l),
            None => {
                self.emitted = true;
                self.out.write_str(write_value(n.value, &mut self.scratch))
            }
        }
    }

    /// A line break and the indentation of `depth` levels; nothing when
    /// compact.
    fn break_line(&mut self, depth: usize) -> Result<(), Fail> {
        if self.indent == 0 {
            return Ok(());
        }
        let width = depth.saturating_mul(self.indent);
        while self.pad.len() < width {
            self.pad.push(' ');
        }
        let pad = std::mem::take(&mut self.pad);
        self.put("\n")?;
        // `pad` is ASCII spaces at least `width` long, so the slice is on a
        // char boundary and within bounds.
        let r = self.put(&pad[..width]);
        self.pad = pad;
        r
    }

    /// The separators before a value, and the check that one may begin.
    fn begin_value(&mut self) -> Result<(), Fail> {
        if self.ended {
            return Err(self.protocol("a value after the end"));
        }
        let depth = self.stack.len();
        match self.stack.last_mut() {
            None if self.root_done => Err(self.protocol("a second root value")),
            None => Ok(()),
            Some(Frame::Object {
                expecting_key: true,
                ..
            }) => Err(self.protocol("a value where a key is due")),
            Some(Frame::Object { .. }) => Ok(()),
            Some(Frame::Array { first }) => {
                let comma = !*first;
                *first = false;
                if comma {
                    self.put(",")?;
                }
                self.break_line(depth)
            }
        }
    }

    /// Bookkeeping after a whole value.
    fn end_value(&mut self) {
        match self.stack.last_mut() {
            None => self.root_done = true,
            Some(Frame::Object { expecting_key, .. }) => *expecting_key = true,
            Some(Frame::Array { .. }) => {}
        }
    }

    fn key(&mut self, k: &str) -> Result<(), Fail> {
        if self.ended {
            return Err(self.protocol("a key after the end"));
        }
        let depth = self.stack.len();
        match self.stack.last_mut() {
            Some(Frame::Object {
                first,
                expecting_key: true,
            }) => {
                let comma = !*first;
                *first = false;
                if comma {
                    self.put(",")?;
                }
                self.break_line(depth)?;
                self.put_string(k)?;
                self.put(if self.indent > 0 { ": " } else { ":" })?;
                // Only after the key is on the wire, so a write failure
                // cannot leave the frame half updated.
                if let Some(Frame::Object { expecting_key, .. }) = self.stack.last_mut() {
                    *expecting_key = false;
                }
                Ok(())
            }
            Some(Frame::Object { .. }) => Err(self.protocol("a key where a value is due")),
            Some(Frame::Array { .. }) => Err(self.protocol("a key inside an array")),
            None => Err(self.protocol("a key outside an object")),
        }
    }

    fn start(&mut self, open: &str, frame: Frame) -> Result<(), Fail> {
        self.begin_value()?;
        self.put(open)?;
        self.stack.push(frame);
        Ok(())
    }

    fn close_object(&mut self) -> Result<(), Fail> {
        if self.ended {
            return Err(self.protocol("an object end after the end"));
        }
        let first = match self.stack.last() {
            Some(Frame::Object {
                expecting_key: false,
                ..
            }) => return Err(self.protocol("an object ended after a key with no value")),
            Some(Frame::Object { first, .. }) => *first,
            Some(Frame::Array { .. }) => return Err(self.protocol("an object end inside an array")),
            None => return Err(self.protocol("an object end with no open object")),
        };
        self.stack.pop();
        if !first {
            self.break_line(self.stack.len())?;
        }
        self.put("}")?;
        self.end_value();
        Ok(())
    }

    fn close_array(&mut self) -> Result<(), Fail> {
        if self.ended {
            return Err(self.protocol("an array end after the end"));
        }
        let first = match self.stack.last() {
            Some(Frame::Array { first }) => *first,
            Some(Frame::Object { .. }) => {
                return Err(self.protocol("an array end inside an object"))
            }
            None => return Err(self.protocol("an array end with no open array")),
        };
        self.stack.pop();
        if !first {
            self.break_line(self.stack.len())?;
        }
        self.put("]")?;
        self.end_value();
        Ok(())
    }

    fn scalar(&mut self, ev: JsonEvent<'_>) -> Result<(), Fail> {
        // Before the separator: a number that will be refused must leave
        // nothing behind, or a caller that carries on after the failure
        // would find `[1,,2]` in the output.
        if let JsonEvent::Number(n) = ev {
            check_number(n.value, n.lexeme).map_err(|f| self.fail(f))?;
        }
        self.begin_value()?;
        match ev {
            JsonEvent::Null => self.put("null")?,
            JsonEvent::Bool(true) => self.put("true")?,
            JsonEvent::Bool(false) => self.put("false")?,
            JsonEvent::Number(n) => self.put_number(n)?,
            JsonEvent::String(s) => self.put_string(s)?,
            // `scalar` is called for the four scalar events only.
            _ => return Err(self.protocol("not a scalar")),
        }
        self.end_value();
        Ok(())
    }

    fn end(&mut self) -> Result<(), Fail> {
        if self.ended {
            return Err(self.protocol("a second end"));
        }
        if !self.stack.is_empty() {
            return Err(self.protocol(&format!(
                "the end with {} open container(s)",
                self.stack.len()
            )));
        }
        if !self.root_done {
            return Err(self.protocol("the end before a root value"));
        }
        if self.options.trailing_newline {
            self.put("\n")?;
        }
        // Ended only once the flush has succeeded: a document whose last
        // bytes never reached the writer is not done, whatever `End` said.
        self.out.flush()?;
        self.ended = true;
        Ok(())
    }
}

/// The `\u00XX` forms of the control characters, the short escapes RFC 8259
/// names among them, indexed by code point.
const CONTROL: [&str; 32] = [
    "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", "\\b",
    "\\t", "\\n", "\\u000b", "\\f", "\\r", "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012",
    "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a",
    "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f",
];

/// The escape RFC 8259 requires for `c`, or `None` when the character is
/// written as itself: `"`, `\` and the control characters, and no more,
/// because the output is UTF-8 and an escape would only make it longer.
fn escape(c: char) -> Option<&'static str> {
    match c {
        '"' => Some("\\\""),
        '\\' => Some("\\\\"),
        // Below 0x20 the index is within the table; `get` says so without
        // a panic path.
        c if (c as u32) < 0x20 => CONTROL.get(c as usize).copied(),
        _ => None,
    }
}

impl<O: TextOut> Sink for JsonRenderer<O> {
    fn event(&mut self, ev: JsonEvent<'_>) -> Result<Flow, Fail> {
        match ev {
            JsonEvent::ObjectStart => self.start(
                "{",
                Frame::Object {
                    first: true,
                    expecting_key: true,
                },
            )?,
            JsonEvent::ArrayStart => self.start("[", Frame::Array { first: true })?,
            JsonEvent::ObjectEnd => self.close_object()?,
            JsonEvent::ArrayEnd => self.close_array()?,
            JsonEvent::Key(k) => self.key(k)?,
            JsonEvent::Null | JsonEvent::Bool(_) | JsonEvent::Number(_) | JsonEvent::String(_) => {
                self.scalar(ev)?
            }
            JsonEvent::End => self.end()?,
        }
        Ok(Flow::Continue)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::text::{StringOut, WriteOut};
    use tabnas_alchemy::shared::Code;
    use JsonEvent::*;

    fn num(lexeme: &str) -> JsonEvent<'_> {
        Number(tabnas_alchemy::shared::Number::with_lexeme(
            lexeme.parse().unwrap_or(0.0),
            lexeme,
        ))
    }

    fn value(v: f64) -> JsonEvent<'static> {
        Number(tabnas_alchemy::shared::Number::new(v))
    }

    fn render(options: JsonOptions, events: &[JsonEvent<'_>]) -> Result<std::string::String, Fail> {
        let mut r = JsonRenderer::new(StringOut::new(), options);
        for ev in events {
            r.event(*ev)?;
        }
        Ok(r.into_inner().into_string())
    }

    fn compact(events: &[JsonEvent<'_>]) -> Result<std::string::String, Fail> {
        render(JsonOptions::default(), events)
    }

    fn indented(n: usize, events: &[JsonEvent<'_>]) -> std::string::String {
        render(
            JsonOptions {
                indent: Some(n),
                trailing_newline: false,
            },
            events,
        )
        .unwrap()
    }

    const DOC: &[JsonEvent<'static>] = &[
        ObjectStart,
        Key("a"),
        ArrayStart,
        Number(tabnas_alchemy::shared::Number {
            value: 1.0,
            lexeme: Some("1"),
        }),
        Number(tabnas_alchemy::shared::Number {
            value: 2.5,
            lexeme: None,
        }),
        String("x"),
        Bool(true),
        Null,
        ArrayEnd,
        Key("b"),
        ObjectStart,
        ObjectEnd,
        Key("c"),
        ArrayStart,
        ArrayEnd,
        Key("d"),
        ObjectStart,
        Key("e"),
        Bool(false),
        ObjectEnd,
        ObjectEnd,
        End,
    ];

    #[test]
    fn compact_output_has_no_whitespace() {
        assert_eq!(
            compact(DOC).unwrap(),
            r#"{"a":[1,2.5,"x",true,null],"b":{},"c":[],"d":{"e":false}}"#
        );
    }

    #[test]
    fn an_indent_writes_fixed_nesting_and_keeps_empty_containers_on_one_line() {
        assert_eq!(
            indented(2, DOC),
            "{\n  \"a\": [\n    1,\n    2.5,\n    \"x\",\n    true,\n    null\n  ],\n  \"b\": {},\n  \"c\": [],\n  \"d\": {\n    \"e\": false\n  }\n}"
        );
        assert_eq!(
            indented(4, &[ArrayStart, ArrayStart, Null, ArrayEnd, ArrayEnd, End]),
            "[\n    [\n        null\n    ]\n]"
        );
    }

    #[test]
    fn an_indent_of_zero_is_compact() {
        assert_eq!(indented(0, DOC), compact(DOC).unwrap());
    }

    #[test]
    fn the_trailing_newline_is_written_at_end_when_asked() {
        let options = JsonOptions {
            indent: None,
            trailing_newline: true,
        };
        assert_eq!(render(options, &[Null, End]).unwrap(), "null\n");
        assert_eq!(compact(&[Null, End]).unwrap(), "null");
    }

    #[test]
    fn a_root_scalar_is_a_document() {
        assert_eq!(compact(&[String("x"), End]).unwrap(), "\"x\"");
        assert_eq!(compact(&[num("-0.5e3"), End]).unwrap(), "-0.5e3");
        assert_eq!(compact(&[Bool(false), End]).unwrap(), "false");
    }

    #[test]
    fn strings_are_escaped_as_rfc_8259_requires_and_no_more() {
        let text =
            "q\" b\\ n\n r\r t\t bs\u{8} ff\u{c} nul\0 c1\u{1} us\u{1f} del\u{7f} é 日本 🚀 /";
        assert_eq!(
            compact(&[String(text), End]).unwrap(),
            "\"q\\\" b\\\\ n\\n r\\r t\\t bs\\b ff\\f nul\\u0000 c1\\u0001 us\\u001f del\u{7f} é 日本 🚀 /\""
        );
        assert_eq!(
            compact(&[ObjectStart, Key("k\"\n"), Null, ObjectEnd, End]).unwrap(),
            "{\"k\\\"\\n\":null}"
        );
    }

    /// A `TextOut` that keeps every fragment apart, so streaming is
    /// observable.
    #[derive(Default)]
    struct Fragments(Vec<std::string::String>);

    impl TextOut for Fragments {
        fn write_str(&mut self, s: &str) -> Result<(), Fail> {
            self.0.push(s.to_owned());
            Ok(())
        }

        fn flush(&mut self) -> Result<(), Fail> {
            Ok(())
        }
    }

    #[test]
    fn strings_escape_exactly_as_transduce_does() {
        let mut every_control = std::string::String::new();
        for c in 0u32..0x20 {
            every_control.push(char::from_u32(c).unwrap_or(' '));
            every_control.push('x');
        }
        for text in [
            "",
            "plain",
            "\"",
            "\\",
            "\"\\\"\\",
            "a\"b\\c\nd",
            every_control.as_str(),
            "é 日本 🚀 \u{7f} \u{80} \u{2028} \u{ffff}",
            "ends with control \u{1}",
            "\u{1} starts with control",
        ] {
            let mut want = std::string::String::new();
            tabnas_alchemy::shared::write_json_string(text, &mut want);
            assert_eq!(compact(&[String(text), End]).unwrap(), want, "{text:?}");
        }
    }

    #[test]
    fn strings_are_streamed_in_runs_and_never_copied_whole() {
        let mut r = JsonRenderer::new(Fragments::default(), JsonOptions::default());
        r.event(String("ab\"cd\n\u{1}ef")).unwrap();
        assert_eq!(
            r.out.0,
            ["\"", "ab", "\\\"", "cd", "\\n", "\\u0001", "ef", "\""]
        );
        // A long string of control characters, six bytes of output each,
        // leaves nothing behind in the renderer.
        let big = "\u{1}".repeat(64 * 1024);
        let mut r = JsonRenderer::new(StringOut::new(), JsonOptions::default());
        r.event(String(&big)).unwrap();
        assert_eq!(r.out.as_str().len(), big.len() * 6 + 2);
        assert_eq!(r.scratch.capacity(), 0, "strings do not touch the scratch");
    }

    #[test]
    fn numbers_keep_their_lexeme_or_take_the_shortest_form() {
        let events = [
            ArrayStart,
            num("1.00"),
            num("123456789012345678901234567890"),
            num("-0"),
            num("1E+2"),
            value(0.0),
            value(1e21),
            value(0.1),
            value(-2.0),
            ArrayEnd,
            End,
        ];
        assert_eq!(
            compact(&events).unwrap(),
            "[1.00,123456789012345678901234567890,-0,1E+2,0,1e21,0.1,-2]"
        );
        assert_eq!(
            compact(&[
                ArrayStart,
                value(1e300),
                value(1e-300),
                value(1.5e17),
                value(1e20),
                ArrayEnd,
                End
            ])
            .unwrap(),
            "[1e300,1e-300,150000000000000000,100000000000000000000]"
        );
    }

    #[test]
    fn a_lexeme_that_is_not_a_json_number_is_invalid_number() {
        for bad in ["1.", "01", "NaN", "+1", "0x1"] {
            let err = compact(&[ArrayStart, num(bad), ArrayEnd, End]).unwrap_err();
            assert_eq!(err.code, Code::InvalidNumber, "{bad:?}");
            assert!(err.committed_output);
        }
        let err = compact(&[num("1."), End]).unwrap_err();
        assert!(!err.committed_output);
    }

    #[test]
    fn nan_and_infinity_are_unrepresentable() {
        for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let err = compact(&[value(v), End]).unwrap_err();
            assert_eq!(err.code, Code::TargetValueUnrepresentable);
        }
    }

    #[test]
    fn an_overflowed_lexeme_is_unrepresentable_too() {
        // "1e999" is a JSON number by grammar, but the value beside it is
        // infinity and a reader of the text would refuse it; the crate's
        // own oracle (serde_json) does. Nothing is written for it.
        let overflowed = Number(tabnas_alchemy::shared::Number::with_lexeme(
            f64::INFINITY,
            "1e999",
        ));
        let mut r = JsonRenderer::new(StringOut::new(), JsonOptions::default());
        r.event(ArrayStart).unwrap();
        r.event(num("1")).unwrap();
        let err = r.event(overflowed).unwrap_err();
        assert_eq!(err.code, Code::TargetValueUnrepresentable);
        assert!(err.committed_output);
        assert_eq!(r.out.as_str(), "[1");
        let err = compact(&[overflowed, End]).unwrap_err();
        assert_eq!(err.code, Code::TargetValueUnrepresentable);
        assert!(!err.committed_output);
    }

    #[test]
    fn a_rejected_number_leaves_no_separator_behind() {
        let mut r = JsonRenderer::new(StringOut::new(), JsonOptions::default());
        for ev in [ArrayStart, num("1")] {
            r.event(ev).unwrap();
        }
        assert_eq!(r.event(num("01")).unwrap_err().code, Code::InvalidNumber);
        assert_eq!(r.out.as_str(), "[1");
        assert_eq!(
            r.event(value(f64::NAN)).unwrap_err().code,
            Code::TargetValueUnrepresentable
        );
        assert_eq!(r.out.as_str(), "[1");
        // A caller that carries on regardless still gets a document.
        for ev in [value(2.0), ArrayEnd, End] {
            r.event(ev).unwrap();
        }
        assert_eq!(r.into_inner().as_str(), "[1,2]");
    }

    fn protocol_error(events: &[JsonEvent<'_>]) -> Fail {
        let err = compact(events).unwrap_err();
        assert_eq!(err.code, Code::ProtocolOrderError, "{events:?}");
        err
    }

    #[test]
    fn a_second_root_is_a_protocol_error() {
        protocol_error(&[Null, Null]);
        protocol_error(&[ObjectStart, ObjectEnd, ArrayStart]);
        protocol_error(&[String("a"), String("b"), End]);
    }

    #[test]
    fn an_end_without_a_complete_root_is_a_protocol_error() {
        assert!(!protocol_error(&[End]).committed_output);
        protocol_error(&[ArrayStart, End]);
        protocol_error(&[ObjectStart, Key("a"), End]);
        protocol_error(&[ObjectStart, Key("a"), Null, End]);
    }

    #[test]
    fn a_key_outside_an_object_or_where_a_value_is_due_is_a_protocol_error() {
        protocol_error(&[Key("a")]);
        protocol_error(&[ArrayStart, Key("a")]);
        protocol_error(&[ObjectStart, Key("a"), Key("b")]);
        protocol_error(&[Null, Key("a")]);
    }

    #[test]
    fn a_value_where_a_key_is_due_is_a_protocol_error() {
        protocol_error(&[ObjectStart, Null]);
        protocol_error(&[ObjectStart, ArrayStart]);
        protocol_error(&[ObjectStart, Key("a"), Null, String("b")]);
    }

    #[test]
    fn an_unbalanced_or_mismatched_close_is_a_protocol_error() {
        protocol_error(&[ObjectEnd]);
        protocol_error(&[ArrayEnd]);
        protocol_error(&[ArrayStart, ObjectEnd]);
        protocol_error(&[ObjectStart, ArrayEnd]);
        protocol_error(&[ObjectStart, Key("a"), ObjectEnd]);
        protocol_error(&[ArrayStart, ArrayEnd, ArrayEnd]);
    }

    #[test]
    fn anything_after_the_end_is_a_protocol_error() {
        for after in [End, Null, Key("a"), ObjectStart, ObjectEnd, ArrayEnd] {
            let err = protocol_error(&[Null, End, after]);
            assert!(err.committed_output);
        }
    }

    #[test]
    fn a_failure_leaves_the_output_a_prefix_of_the_document() {
        let mut r = JsonRenderer::new(StringOut::new(), JsonOptions::default());
        for ev in [ObjectStart, Key("a"), ArrayStart, Null] {
            r.event(ev).unwrap();
        }
        assert_eq!(r.depth(), 2);
        assert_eq!(
            r.event(Key("b")).unwrap_err().code,
            Code::ProtocolOrderError
        );
        assert_eq!(r.into_inner().as_str(), "{\"a\":[null");
    }

    /// A writer that takes every byte and refuses to flush.
    struct NoFlush;

    impl std::io::Write for NoFlush {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other("pipe closed"))
        }
    }

    #[test]
    fn a_failed_flush_at_end_leaves_the_renderer_not_done() {
        let mut r = JsonRenderer::new(WriteOut::new(NoFlush), JsonOptions::default());
        r.event(Null).unwrap();
        let err = r.event(End).unwrap_err();
        assert_eq!(err.code, Code::OutputFailed);
        assert!(!r.is_done());
    }

    #[test]
    fn committed_output_means_bytes_that_reached_the_writer() {
        let mut r = JsonRenderer::new(WriteOut::new(Vec::new()), JsonOptions::default());
        r.event(ArrayStart).unwrap();
        let err = r.event(Key("k")).unwrap_err();
        assert_eq!(err.code, Code::ProtocolOrderError);
        assert!(!err.committed_output, "the bracket is only buffered");
        assert_eq!(r.out.committed(), 0);

        let mut r = JsonRenderer::new(
            WriteOut::new(Vec::new()).with_budget(0),
            JsonOptions::default(),
        );
        r.event(ArrayStart).unwrap();
        let err = r.event(Key("k")).unwrap_err();
        assert!(err.committed_output, "the bracket reached the writer");
    }

    #[test]
    fn end_flushes_the_output_and_nothing_else_does() {
        let mut r = JsonRenderer::new(WriteOut::new(Vec::new()), JsonOptions::default());
        for ev in [ArrayStart, Bool(true), ArrayEnd] {
            assert_eq!(r.event(ev).unwrap(), Flow::Continue);
        }
        assert_eq!(r.out.committed(), 0);
        assert!(!r.is_done());
        r.event(End).unwrap();
        assert!(r.is_done());
        assert_eq!(r.out.committed(), 6);
        assert_eq!(r.into_inner().into_inner(), b"[true]");
    }
}