jsonx-lib 0.5.2

Strict RFC 8259 JSON: a borrowing parser, a pull reader, and a deterministic writer, with budgets checked before allocation and no recursion. No dependencies, no_std.
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
//! The incremental reader: a document fed in chunks as they arrive.

use alloc::string::String;

use crate::{
    DecodeError, DuplicateKeys, FromJson, Kind, Limits, Parser, Value,
    error::{Error, ErrorKind},
    machine::Machine,
    reader::Event,
};

/// The answer of a [`StreamReader`] call: ready, or waiting for more input.
///
/// `NeedInput` is not an error: the input so far is a valid beginning, and
/// the call can be made again after [`feed`](StreamReader::feed) or
/// [`end_input`](StreamReader::end_input).
///
/// # Examples
///
/// ```
/// use jsonx_lib::{Event, Step, StreamReader};
///
/// let mut r = StreamReader::new();
/// assert_eq!(r.next_event()?, Step::NeedInput);
/// r.feed(b"[tr")?;
/// assert_eq!(r.next_event()?, Step::Ready(Some(Event::StartArray)));
/// assert_eq!(r.next_event()?, Step::NeedInput); // `tr` is not a value yet
/// r.feed(b"ue]")?;
/// assert_eq!(r.next_event()?.ready(), Some(Some(Event::Bool(true))));
/// # Ok::<(), jsonx_lib::Error>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[must_use]
pub enum Step<T> {
    /// The call completed with this result.
    Ready(T),
    /// The input so far ends inside what the call needs: feed more, or end
    /// the input, and call again.
    NeedInput,
}

impl<T> Step<T> {
    /// The result, if ready.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Step;
    ///
    /// assert_eq!(Step::Ready(3).ready(), Some(3));
    /// assert_eq!(Step::<u8>::NeedInput.ready(), None);
    /// ```
    #[inline]
    pub fn ready(self) -> Option<T> {
        match self {
            Self::Ready(value) => Some(value),
            Self::NeedInput => None,
        }
    }

    /// Whether the call completed.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(jsonx_lib::Step::Ready(()).is_ready());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_ready(&self) -> bool {
        matches!(self, Self::Ready(_))
    }

    /// Applies `f` to a ready result.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Step;
    ///
    /// assert_eq!(Step::Ready(2).map(|n| n * 10), Step::Ready(20));
    /// ```
    #[inline]
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Step<U> {
        match self {
            Self::Ready(value) => Step::Ready(f(value)),
            Self::NeedInput => Step::NeedInput,
        }
    }
}

/// A raw value being skipped across calls.
#[derive(Clone, Copy, Debug)]
struct RawProgress {
    /// The depth the value started at; it is complete when the reader is back.
    depth: usize,
    /// The value's first byte (absolute), once its first event was read.
    start: Option<usize>,
}

/// How much consumed text the buffer may keep before it is compacted.
const COMPACT_AT: usize = 4 * 1024;

/// A pull reader over input that arrives in pieces: bytes go in with
/// [`feed`](Self::feed) as they arrive, events come out as soon as they are
/// complete.
///
/// It is the same reader as [`Reader`](crate::Reader), over a buffer: the
/// same grammar, the same budgets, and the same errors at the same offsets
/// (counted from the first byte ever fed), whatever the input's chunking.
/// When a call needs bytes that have not arrived it returns
/// [`Step::NeedInput`] and changes nothing a later call would see
/// differently; after [`end_input`](Self::end_input), running out is the
/// [`ErrorKind::UnexpectedEnd`] that [`Reader`](crate::Reader) reports.
///
/// Events borrow from the reader's buffer, so each one must be dropped
/// before the next call. In particular, feed more input after the borrow
/// ends: in an `else` after `if let Step::Ready(..) = reader.next_event()?`
/// (Rust 2024 drops the `if let` temporaries before the `else`), or after
/// the loop that drains the ready events, as below; a `match` keeps the
/// event borrowed in every arm. Consumed input is dropped from the buffer as more
/// is fed, so a long document read with [`next_event`](Self::next_event) as
/// it arrives needs memory for one token and one chunk, not for the
/// document. The whole-value calls ([`read_raw`](Self::read_raw),
/// [`read_value`](Self::read_value), [`decode`](Self::decode)) are
/// different: each keeps its value's text in the buffer until the value
/// ends, bounded by [`Limits::max_value_bytes`]. A token cut by a chunk
/// boundary is continued where it stopped, never scanned again from its
/// start: a string fed one byte at a time costs linear time.
///
/// The input must be UTF-8, checked as it arrives (a character may be split
/// across chunks). The first invalid byte is reported as
/// [`ErrorKind::InvalidUtf8`] when the reader reaches it: a syntax error
/// earlier in the document is reported first. (A complete document given to
/// [`parse_bytes`](crate::parse_bytes) checks the encoding before the
/// syntax, so the two can name different errors for a document that has
/// both.)
///
/// [`Limits::max_input_bytes`] bounds the total fed (in
/// [`documents`](Self::documents) mode, what is fed for each document), and
/// [`Limits::max_value_bytes`] what a whole-value call may hold; the other
/// budgets apply exactly as for a complete document. After an error the
/// reader is finished: every later call returns the same error.
///
/// # Examples
///
/// ```
/// use jsonx_lib::{Event, Step, StreamReader};
///
/// let mut reader = StreamReader::new();
/// let mut keys = Vec::new();
/// for chunk in [&b"{\"jsonr"[..], b"pc\": \"2.0\", \"i", b"d\": 12", b"}"] {
///     reader.feed(chunk)?;
///     while let Step::Ready(Some(event)) = reader.next_event()? {
///         if let Event::Key(key) = event {
///             keys.push(key.into_owned());
///         }
///     }
/// }
/// reader.end_input();
/// assert_eq!(reader.next_event()?, Step::Ready(None)); // the document is complete
/// assert_eq!(keys, ["jsonrpc", "id"]);
/// # Ok::<(), jsonx_lib::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct StreamReader {
    /// The input not yet dropped: valid UTF-8, starting at absolute offset
    /// `base`.
    buf: String,
    base: usize,
    /// An incomplete UTF-8 sequence at the end of the input so far.
    tail: [u8; 4],
    tail_len: usize,
    /// The absolute offset of the first byte that is not UTF-8. Nothing
    /// from it on is kept.
    utf8_error: Option<usize>,
    /// Bytes fed in total.
    fed: usize,
    ended: bool,
    machine: Machine,
    failed: Option<Error>,
    /// The absolute offset where the most recent event's token began.
    last: usize,
    raw: Option<RawProgress>,
}

impl Default for StreamReader {
    fn default() -> Self {
        Self::new()
    }
}

impl StreamReader {
    /// A reader with the default [`Limits`], refusing duplicate keys in what
    /// [`read_value`](Self::read_value) builds. For others, use
    /// [`Parser::stream_reader`].
    ///
    /// # Examples
    ///
    /// ```
    /// let r = jsonx_lib::StreamReader::new();
    /// assert_eq!(r.offset(), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::with_config(Limits::new(), DuplicateKeys::Error)
    }

    /// A reader with the given budgets and duplicate-key policy.
    pub(crate) fn with_config(limits: Limits, duplicates: DuplicateKeys) -> Self {
        Self {
            buf: String::new(),
            base: 0,
            tail: [0; 4],
            tail_len: 0,
            utf8_error: None,
            fed: 0,
            ended: false,
            machine: {
                let mut machine = Machine::new(limits, duplicates, false);
                // Keys outlive the front of the buffer, which is dropped.
                machine.copy_keys = true;
                machine
            },
            failed: None,
            last: 0,
            raw: None,
        }
    }

    /// Reads a sequence of documents instead of one, as
    /// [`Reader::documents`](crate::Reader::documents) does: NDJSON, JSON
    /// Lines, or concatenated JSON, fed as it arrives. Whole-value reads
    /// return one document each, and `Ready(None)` once the input has ended
    /// after the last.
    ///
    /// [`Limits::max_input_bytes`] then applies to each document, not to the
    /// stream: input is counted from where the current document began (or,
    /// between documents, from the end of the last one), so a connection
    /// that carries documents for as long as it stays open is never refused
    /// for its total. A [`Reader`](crate::Reader), which has its whole input
    /// already, applies the budget to all of it.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{Step, StreamReader};
    ///
    /// let mut r = StreamReader::new().documents();
    /// let mut seen = Vec::new();
    /// for chunk in [&b"{\"id\": 1}\n{\"i"[..], b"d\": 2}\n"] {
    ///     r.feed(chunk)?;
    ///     while let Step::Ready(Some(doc)) = r.read_value()? {
    ///         seen.push(doc["id"].as_i64());
    ///     }
    /// }
    /// r.end_input();
    /// assert_eq!(r.read_value()?, Step::Ready(None));
    /// assert_eq!(seen, [Some(1), Some(2)]);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn documents(mut self) -> Self {
        self.machine.documents = true;
        self
    }

    /// Adds the next piece of input. A chunk may end anywhere, even inside a
    /// token or a UTF-8 character.
    ///
    /// # Errors
    ///
    /// [`ErrorKind::InputTooLarge`] when the input in total (in documents
    /// mode, of the current document) grows past [`Limits::max_input_bytes`],
    /// or when the value a pending whole-value call is reading grows past
    /// [`Limits::max_value_bytes`], at the offset of the first byte over the
    /// budget (the reader is then finished);
    /// [`ErrorKind::InputAfterEnd`] after [`end_input`](Self::end_input);
    /// any error the reader already stopped at.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{ErrorKind, Limits, Parser};
    ///
    /// let mut r = Parser::new().limits(Limits::new().with_max_input_bytes(4)).stream_reader();
    /// assert!(r.feed(b"[1,").is_ok());
    /// assert_eq!(r.feed(b"22]").unwrap_err().kind(), ErrorKind::InputTooLarge);
    /// ```
    pub fn feed(&mut self, bytes: &[u8]) -> Result<(), Error> {
        if let Some(e) = self.failed {
            return Err(e);
        }
        if self.ended {
            return Err(Error::new(ErrorKind::InputAfterEnd, self.fed));
        }
        // The input budget, from where the current document began (the
        // start of the input outside documents mode).
        let start = self.machine.document_start();
        let max = self.machine.limits.max_input_bytes;
        if bytes.len() > max.saturating_sub(self.fed.saturating_sub(start)) {
            let e = Error::new(ErrorKind::InputTooLarge, start.saturating_add(max));
            return Err(*self.failed.insert(e));
        }
        // The value a whole-value call is waiting on stays in the buffer.
        if let Some(progress) = self.raw {
            let start = progress
                .start
                .unwrap_or(self.base + self.machine.needed_from());
            let max = self.machine.limits.max_value_bytes;
            if bytes.len() > max.saturating_sub(self.fed.saturating_sub(start)) {
                let e = Error::new(ErrorKind::InputTooLarge, start.saturating_add(max));
                return Err(*self.failed.insert(e));
            }
        }
        self.fed += bytes.len();
        self.compact();
        if self.utf8_error.is_none() {
            self.append(bytes);
        }
        Ok(())
    }

    /// Says that the input has ended: nothing more will be fed. From now on,
    /// running out of input is an error, as for a complete document, and a
    /// number or whitespace at the very end is final.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{Event, Step, StreamReader};
    ///
    /// let mut r = StreamReader::new();
    /// r.feed(b"12")?;
    /// assert_eq!(r.next_event()?, Step::NeedInput); // `123` may follow
    /// r.end_input();
    /// assert_eq!(r.next_event()?, Step::Ready(Some(Event::Number(12.into()))));
    /// assert_eq!(r.next_event()?, Step::Ready(None));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    pub fn end_input(&mut self) {
        if self.ended {
            return;
        }
        self.ended = true;
        if self.tail_len > 0 && self.utf8_error.is_none() {
            // A character cut off by the end of the input.
            self.utf8_error = Some(self.base + self.buf.len());
        }
        self.machine.complete = true;
    }

    /// Reads up to 8 KiB from `source` and feeds it, or calls
    /// [`end_input`](Self::end_input) when `source` is at its end. Returns
    /// the number of bytes read (`0` at the end). Interrupted reads are
    /// retried.
    ///
    /// A budget error from [`feed`](Self::feed) is not an I/O error: it is
    /// kept, and returned by the next reading call.
    ///
    /// # Errors
    ///
    /// Any error from `source` other than [`std::io::ErrorKind::Interrupted`].
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{Step, StreamReader};
    ///
    /// let mut source: &[u8] = br#"{"big": [1, 2, 3]}"#;
    /// let mut r = StreamReader::new();
    /// let mut events = 0;
    /// loop {
    ///     if let Step::Ready(event) = r.next_event()? {
    ///         match event {
    ///             Some(_) => events += 1,
    ///             None => break,
    ///         }
    ///     } else {
    ///         r.read_from(&mut source)?;
    ///     }
    /// }
    /// assert_eq!(events, 8); // {, "big", [, 1, 2, 3, ], }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn read_from(&mut self, source: &mut dyn std::io::Read) -> std::io::Result<usize> {
        let mut chunk = [0u8; 8 * 1024];
        loop {
            match source.read(&mut chunk) {
                Ok(0) => {
                    self.end_input();
                    return Ok(0);
                }
                Ok(n) => {
                    // A refused feed is kept in `failed` and reported by the
                    // next reading call.
                    let _kept = self.feed(chunk.get(..n).unwrap_or_default());
                    return Ok(n);
                }
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
    }

    /// Reads the next event: `Ready(Some(event))`, `Ready(None)` once the
    /// document is complete and the input has ended with nothing but
    /// whitespace after it, or `NeedInput`.
    ///
    /// # Errors
    ///
    /// The first syntax error, exceeded budget, or invalid UTF-8, at its
    /// byte offset. Once an error is returned, every later call returns it.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{ErrorKind, Event, Step, StreamReader};
    ///
    /// let mut r = StreamReader::new();
    /// r.feed(b"[1,")?;
    /// assert_eq!(r.next_event()?, Step::Ready(Some(Event::StartArray)));
    /// assert!(r.next_event()?.is_ready()); // 1
    /// r.feed(b"]")?;
    /// let err = r.next_event().unwrap_err();
    /// assert_eq!((err.kind(), err.offset()), (ErrorKind::TrailingComma, 3));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    pub fn next_event(&mut self) -> Result<Step<Option<Event<'_>>>, Error> {
        if let Some(e) = self.failed {
            return Err(e);
        }
        let Self {
            buf,
            machine,
            base,
            last,
            failed,
            utf8_error,
            ..
        } = self;
        match machine.step(buf) {
            Ok(Some(event)) => {
                *last = *base + machine.last;
                Ok(Step::Ready(Some(event)))
            }
            Ok(None) => match utf8_error {
                // The valid text holds a whole document, then bad bytes.
                Some(at) => Err(*failed.insert(Error::new(ErrorKind::InvalidUtf8, *at))),
                None => Ok(Step::Ready(None)),
            },
            Err(e) => halt(failed, machine, buf.len(), *base, *utf8_error, e),
        }
    }

    /// Reads the next value whole and returns its exact source text, without
    /// decoding or allocating anything, as [`Reader::read_raw`](crate::Reader::read_raw)
    /// does, with the same positioning rules: `Ready(None)` when no value
    /// comes next.
    ///
    /// The value must be in the buffer whole before it can be returned, so
    /// a large value costs memory for all of it, whitespace included, up to
    /// [`Limits::max_value_bytes`] (past it, [`feed`](Self::feed) refuses
    /// more). `NeedInput` keeps the progress: the next call continues the
    /// same value.
    ///
    /// After a single document's value, a call answers as
    /// [`next_event`](Self::next_event) does there: `NeedInput` while only
    /// whitespace has followed and the input has not ended, `Ready(None)`
    /// once it has, and [`ErrorKind::TrailingCharacters`] for anything but
    /// whitespace. [`finish`](Self::finish) makes the same check in one call.
    ///
    /// # Errors
    ///
    /// As [`next_event`](Self::next_event), for any error inside the value,
    /// and [`ErrorKind::TrailingCharacters`] after the document.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{Event, Step, StreamReader};
    ///
    /// let mut r = StreamReader::new();
    /// r.feed(br#"{"id": 1, "params": {"line""#)?;
    /// assert!(r.next_event()?.is_ready()); // {
    /// assert!(r.next_event()?.is_ready()); // "id"
    /// assert_eq!(r.read_raw()?, Step::Ready(Some("1")));
    /// assert!(r.next_event()?.is_ready()); // "params"
    /// assert_eq!(r.read_raw()?, Step::NeedInput);
    /// r.feed(br#": 3}}"#)?;
    /// assert_eq!(r.read_raw()?, Step::Ready(Some(r#"{"line": 3}"#)));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    pub fn read_raw(&mut self) -> Result<Step<Option<&str>>, Error> {
        Ok(self.raw_span()?.map(|span| {
            span.and_then(|(start, end)| self.buf.get(start - self.base..end - self.base))
        }))
    }

    /// Reads the next value whole and builds it as a [`Value`], applying the
    /// reader's [`DuplicateKeys`] policy; positioning as for
    /// [`read_raw`](Self::read_raw). The value borrows from the buffer:
    /// call [`Value::into_owned`] to keep it.
    ///
    /// # Errors
    ///
    /// As [`read_raw`](Self::read_raw), plus [`ErrorKind::DuplicateKey`]
    /// under [`DuplicateKeys::Error`].
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{Step, StreamReader};
    ///
    /// let mut r = StreamReader::new();
    /// r.feed(br#"{"a": [1, "#)?;
    /// assert_eq!(r.read_value()?, Step::NeedInput);
    /// r.feed(br#"2]}"#)?;
    /// let value = r.read_value()?.ready().flatten().unwrap_or_default();
    /// assert_eq!(value["a"][1], 2);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    pub fn read_value(&mut self) -> Result<Step<Option<Value<'_>>>, Error> {
        if let Some(e) = self.failed {
            return Err(e);
        }
        let Step::Ready(span) = self.raw_span()? else {
            return Ok(Step::NeedInput);
        };
        let Some((start, end)) = span else {
            return Ok(Step::Ready(None));
        };
        let text = self
            .buf
            .get(start - self.base..end - self.base)
            .unwrap_or("");
        // The budgets, and duplicates under `DuplicateKeys::Error`, were
        // checked while the value was skipped; the memory budget, and
        // `First` and `Last`, remain to apply to the tree.
        let limits = Limits::unlimited().with_max_memory(self.machine.limits.max_memory);
        let parser = Parser::new()
            .limits(limits)
            .duplicate_keys(self.machine.duplicates);
        match parser.parse(text) {
            Ok(value) => Ok(Step::Ready(Some(value))),
            Err(e) => {
                let e = Error::new(e.kind(), e.offset() + start);
                self.failed = Some(e);
                Err(e)
            }
        }
    }

    /// Reads the next value whole as a `T` ([`FromJson`]); positioning as
    /// for [`read_raw`](Self::read_raw). The value borrows from the buffer,
    /// as `T` allows.
    ///
    /// The value is first skipped (validated, with every budget) as it
    /// arrives, then read as `T` once it is all there. Byte offsets in an
    /// error count from the first byte fed.
    ///
    /// # Errors
    ///
    /// The [`DecodeError`] of `T`, or the reader's error.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{Step, StreamReader};
    ///
    /// let mut r = StreamReader::new().documents();
    /// r.feed(b"[1, 2]\n[3")?;
    /// assert_eq!(r.decode::<Vec<u8>>()?, Step::Ready(Some(vec![1, 2])));
    /// assert_eq!(r.decode::<Vec<u8>>()?, Step::NeedInput);
    /// r.feed(b"]\n")?;
    /// r.end_input();
    /// assert_eq!(r.decode::<Vec<u8>>()?, Step::Ready(Some(vec![3])));
    /// assert_eq!(r.decode::<Vec<u8>>()?, Step::Ready(None));
    /// # Ok::<(), jsonx_lib::DecodeError>(())
    /// ```
    pub fn decode<'s, T: FromJson<'s>>(&'s mut self) -> Result<Step<Option<T>>, DecodeError> {
        let Step::Ready(span) = self.raw_span()? else {
            return Ok(Step::NeedInput);
        };
        let Some((start, end)) = span else {
            return Ok(Step::Ready(None));
        };
        let text = self
            .buf
            .get(start - self.base..end - self.base)
            .unwrap_or("");
        // The budgets, and duplicates under `DuplicateKeys::Error`, were
        // checked while the value was skipped. The depth budget stays, to
        // bound a recursive `T`, and the memory budget, for what `T` holds.
        let limits = Limits::unlimited()
            .with_max_depth(self.machine.limits.max_depth)
            .with_max_memory(self.machine.limits.max_memory);
        let parser = Parser::new()
            .limits(limits)
            .duplicate_keys(self.machine.duplicates)
            .numbers(self.machine.numbers);
        parser
            .decode(text)
            .map(|value| Step::Ready(Some(value)))
            .map_err(|e| e.shifted(start))
    }

    /// Reads to the end of the input, checking that the rest of the
    /// document (in documents mode, of every document) is valid and that
    /// nothing but whitespace follows: `Ready(())` once the input has ended
    /// and all of it was read, `NeedInput` before that. As
    /// [`Reader::finish`](crate::Reader::finish), for input that arrives in
    /// pieces.
    ///
    /// The whole-value calls stop at the end of the value they read, and a
    /// value nested in the document says nothing of the rest of it. Call
    /// this after the last of them to know that the input held exactly one
    /// valid document (or a sequence of valid ones).
    ///
    /// # Errors
    ///
    /// The first error in the rest of the input, as
    /// [`next_event`](Self::next_event) reports it: a syntax error, an
    /// exceeded budget, invalid UTF-8, or [`ErrorKind::TrailingCharacters`].
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{ErrorKind, Step, StreamReader};
    ///
    /// let mut r = StreamReader::new();
    /// r.feed(br#"{"id": 1} "#)?;
    /// assert!(r.read_value()?.is_ready());
    /// assert_eq!(r.finish()?, Step::NeedInput); // more may follow
    /// r.end_input();
    /// assert_eq!(r.finish()?, Step::Ready(()));
    ///
    /// let mut r = StreamReader::new();
    /// r.feed(br#"{"id": 1}}"#)?;
    /// r.end_input();
    /// assert!(r.read_value()?.is_ready());
    /// let err = r.finish().unwrap_err();
    /// assert_eq!((err.kind(), err.offset()), (ErrorKind::TrailingCharacters, 9));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    pub fn finish(&mut self) -> Result<Step<()>, Error> {
        // A whole-value call left waiting is given up: its value is read
        // as events, like the rest.
        self.raw = None;
        loop {
            match self.next_event()? {
                Step::Ready(Some(_)) => {}
                Step::Ready(None) => return Ok(Step::Ready(())),
                Step::NeedInput => return Ok(Step::NeedInput),
            }
        }
    }

    /// The kind of the next value, without consuming anything: `Ready(None)`
    /// when no value comes next, or when the next byte cannot start one (the
    /// next [`next_event`](Self::next_event) reports why).
    ///
    /// # Errors
    ///
    /// Any error the reader already stopped at.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{Kind, Step, StreamReader};
    ///
    /// let mut r = StreamReader::new();
    /// r.feed(b"[ ")?;
    /// assert!(r.next_event()?.is_ready());
    /// assert_eq!(r.peek_kind()?, Step::NeedInput);
    /// r.feed(b"\"x\"]")?;
    /// assert_eq!(r.peek_kind()?, Step::Ready(Some(Kind::String)));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    pub fn peek_kind(&mut self) -> Result<Step<Option<Kind>>, Error> {
        if let Some(e) = self.failed {
            return Err(e);
        }
        match self.machine.at_value(&self.buf) {
            Ok(false) => Ok(Step::Ready(None)),
            Ok(true) => match self.machine.peek_kind(&self.buf) {
                Some(kind) => Ok(Step::Ready(Some(kind))),
                // The value's first byte has not arrived.
                None if self.machine.needed_from() == self.buf.len() && !self.machine.complete => {
                    self.halt(Error::new(ErrorKind::UnexpectedEnd, self.buf.len()))
                }
                None => Ok(Step::Ready(None)),
            },
            Err(e) => self.halt(e),
        }
    }

    /// The number of arrays and objects open.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut r = jsonx_lib::StreamReader::new();
    /// r.feed(b"[[")?;
    /// let _ = r.next_event()?;
    /// let _ = r.next_event()?;
    /// assert_eq!(r.depth(), 2);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn depth(&self) -> usize {
        self.machine.depth()
    }

    /// The byte offset, from the first byte fed, just past the input
    /// consumed so far.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut r = jsonx_lib::StreamReader::new();
    /// r.feed(b"[10, 20]")?;
    /// let _ = r.next_event()?;
    /// let _ = r.next_event()?;
    /// assert_eq!(r.offset(), 3);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn offset(&self) -> usize {
        self.base + self.machine.pos
    }

    /// The byte offset, from the first byte fed, where the most recent
    /// event's token began (see [`Reader::event_offset`](crate::Reader::event_offset)).
    ///
    /// # Examples
    ///
    /// ```
    /// let mut r = jsonx_lib::StreamReader::new();
    /// r.feed(b"[ 7]")?;
    /// let _ = r.next_event()?;
    /// let _ = r.next_event()?;
    /// assert_eq!(r.event_offset(), 2);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn event_offset(&self) -> usize {
        self.last
    }

    /// The bytes of input the reader holds: what has been fed and not yet
    /// dropped. Consumed input is dropped as more is fed.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut r = jsonx_lib::StreamReader::new();
    /// r.feed(b"[1, 2")?;
    /// assert_eq!(r.buffered(), 5);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn buffered(&self) -> usize {
        self.buf.len() + self.tail_len
    }

    // ---- internals -----------------------------------------------------------

    /// [`halt`] for `self`.
    fn halt<T>(&mut self, e: Error) -> Result<Step<T>, Error> {
        halt(
            &mut self.failed,
            &self.machine,
            self.buf.len(),
            self.base,
            self.utf8_error,
            e,
        )
    }

    /// Skips the next value (continuing one already started) and returns
    /// its absolute span, or `None` when no value comes next.
    fn raw_span(&mut self) -> Result<Step<Option<(usize, usize)>>, Error> {
        if let Some(e) = self.failed {
            return Err(e);
        }
        let mut progress = match self.raw {
            Some(progress) => progress,
            None => match self.machine.at_value(&self.buf) {
                Ok(false) => {
                    return match self.machine.check_trailing(&self.buf) {
                        Ok(()) => Ok(Step::Ready(None)),
                        Err(e) => self.halt(e),
                    };
                }
                Ok(true) => RawProgress {
                    depth: self.machine.depth(),
                    start: None,
                },
                Err(e) => return self.halt(e),
            },
        };
        self.machine.skipping = true;
        let outcome = loop {
            match self.machine.step(&self.buf) {
                Ok(Some(_)) => {
                    self.last = self.base + self.machine.last;
                    let start = *progress.start.get_or_insert(self.last);
                    if self.machine.depth() == progress.depth {
                        break Ok(Some((start, self.base + self.machine.pos)));
                    }
                }
                // `at_value` saw a value, so the document cannot end here.
                Ok(None) => break Err(Error::new(ErrorKind::UnexpectedEnd, self.buf.len())),
                Err(e) => break Err(e),
            }
        };
        self.machine.skipping = false;
        match outcome {
            Ok(span) => {
                self.raw = None;
                Ok(Step::Ready(span))
            }
            Err(e) => {
                self.raw = Some(progress);
                self.halt(e)
            }
        }
    }

    /// Drops consumed input from the front of the buffer once there is
    /// enough of it to be worth the copy (amortized constant per byte).
    fn compact(&mut self) {
        let mut keep_from = self.machine.needed_from();
        if let Some(RawProgress {
            start: Some(start), ..
        }) = self.raw
        {
            keep_from = keep_from.min(start - self.base);
        }
        if keep_from < COMPACT_AT
            || keep_from * 2 < self.buf.len()
            || !self.buf.is_char_boundary(keep_from)
        {
            return;
        }
        let _dropped = self.buf.drain(..keep_from);
        self.base += keep_from;
        self.machine.rebase(keep_from);
    }

    /// Records that the input stops being UTF-8 at the end of the buffer.
    /// No valid byte can follow, so the text so far is all there will be.
    fn bad_byte(&mut self) {
        self.utf8_error = Some(self.base + self.buf.len());
        self.machine.complete = true;
    }

    /// Appends `bytes` to the buffer, keeping only valid UTF-8 and holding
    /// back a character cut off at the end.
    fn append(&mut self, bytes: &[u8]) {
        let mut rest = bytes;
        if self.tail_len > 0 {
            // Complete the character the last chunk cut off.
            let take = (4 - self.tail_len).min(rest.len());
            let (head, after) = rest.split_at(take);
            if let Some(slot) = self.tail.get_mut(self.tail_len..self.tail_len + take) {
                slot.copy_from_slice(head);
            }
            let have = self.tail_len + take;
            let pending = self.tail.get(..have).unwrap_or_default();
            match core::str::from_utf8(pending) {
                Ok(text) => {
                    self.buf.push_str(text);
                    self.tail_len = 0;
                    rest = after;
                }
                Err(e) => {
                    let used = e.valid_up_to();
                    if used > 0 {
                        // The cut character completed; the bytes after it
                        // in `pending` are new input to read normally.
                        let done = pending.get(..used).unwrap_or_default();
                        self.buf.push_str(core::str::from_utf8(done).unwrap_or(""));
                        let extra = used - self.tail_len;
                        self.tail_len = 0;
                        rest = bytes.get(extra..).unwrap_or_default();
                    } else if e.error_len().is_none() && after.is_empty() {
                        // Still incomplete, and this chunk is used up.
                        self.tail_len = have;
                        return;
                    } else {
                        self.bad_byte();
                        return;
                    }
                }
            }
        }
        match core::str::from_utf8(rest) {
            Ok(text) => self.buf.push_str(text),
            Err(e) => {
                let (valid, invalid) = rest.split_at(e.valid_up_to());
                self.buf.push_str(core::str::from_utf8(valid).unwrap_or(""));
                if e.error_len().is_none() {
                    // A character cut off by the end of this chunk.
                    if let Some(slot) = self.tail.get_mut(..invalid.len()) {
                        slot.copy_from_slice(invalid);
                    }
                    self.tail_len = invalid.len();
                } else {
                    self.bad_byte();
                }
            }
        }
    }
}

/// Turns a machine error into a call's answer: `NeedInput` when the buffer
/// (of `len` bytes, starting at absolute offset `base`) merely ran out,
/// otherwise the error, made absolute and kept in `failed`.
fn halt<T>(
    failed: &mut Option<Error>,
    machine: &Machine,
    len: usize,
    base: usize,
    utf8_error: Option<usize>,
    e: Error,
) -> Result<Step<T>, Error> {
    let ran_out = e.kind() == ErrorKind::UnexpectedEnd && e.offset() == len;
    let e = match (ran_out, utf8_error) {
        (true, _) if !machine.complete => return Ok(Step::NeedInput),
        // The valid text ends where the input stops being UTF-8.
        (true, Some(at)) => Error::new(ErrorKind::InvalidUtf8, at),
        // Wrapping: a repeated key's quote can lie in the dropped front of
        // the buffer, where its text offset wrapped below zero (see
        // `Machine::check_object`); adding `base` back gives its exact
        // offset in the input.
        _ => Error::new(e.kind(), e.offset().wrapping_add(base)),
    };
    *failed = Some(e);
    Err(e)
}

impl Parser {
    /// A [`StreamReader`] with this parser's budgets and duplicate-key
    /// policy (which [`StreamReader::read_value`] applies).
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{ErrorKind, Limits, Parser};
    ///
    /// let mut r = Parser::new().limits(Limits::new().with_max_depth(1)).stream_reader();
    /// r.feed(b"[[]]")?;
    /// assert!(r.next_event().is_ok());
    /// assert_eq!(r.next_event().unwrap_err().kind(), ErrorKind::DepthLimitExceeded);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn stream_reader(&self) -> StreamReader {
        let mut reader = StreamReader::with_config(self.get_limits(), self.get_duplicate_keys());
        reader.machine.numbers = self.get_numbers();
        reader
    }
}

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

    #[test]
    fn test_utf8_split_at_every_byte_of_a_character() {
        let text = "[\"a\u{e9}\u{20ac}\u{1f600}\"]";
        for cut in 0..=text.len() {
            let (a, b) = text.as_bytes().split_at(cut);
            let mut r = StreamReader::new();
            assert!(r.feed(a).is_ok() && r.feed(b).is_ok());
            r.end_input();
            let _start = r.next_event();
            let got = r.next_event().ok().and_then(Step::ready).flatten();
            assert_eq!(
                got,
                Some(Event::String("a\u{e9}\u{20ac}\u{1f600}".into())),
                "cut {cut}"
            );
        }
        // One byte at a time.
        let mut r = StreamReader::new();
        for &byte in text.as_bytes() {
            assert!(r.feed(&[byte]).is_ok());
        }
        assert_eq!(r.buffered(), text.len());
    }

    #[test]
    fn test_invalid_utf8_is_reported_where_the_reader_reaches_it() {
        let mut r = StreamReader::new();
        assert!(r.feed(b"[1, \"a\xC3").is_ok());
        assert!(r.feed(b"(\"]").is_ok()); // 0xC3 0x28 is not UTF-8
        let _start = r.next_event();
        let _one = r.next_event();
        let err = r.next_event().err();
        assert_eq!(
            err.map(|e| (e.kind(), e.offset())),
            Some((ErrorKind::InvalidUtf8, 6))
        );
        // A character cut off by the end of the input.
        let mut r = StreamReader::new();
        assert!(r.feed(b"\"\xE2\x82").is_ok());
        assert_eq!(r.next_event().ok(), Some(Step::NeedInput));
        r.end_input();
        let err = r.next_event().err();
        assert_eq!(
            err.map(|e| (e.kind(), e.offset())),
            Some((ErrorKind::InvalidUtf8, 1))
        );
        // A syntax error before the bad byte comes first.
        let mut r = StreamReader::new();
        assert!(r.feed(b"[1 2, \xFF]").is_ok());
        let _start = r.next_event();
        let _one = r.next_event();
        let err = r.next_event().err();
        assert_eq!(
            err.map(|e| (e.kind(), e.offset())),
            Some((ErrorKind::ExpectedCommaOrBracket, 3))
        );
        // An invalid continuation completing a cut character.
        let mut r = StreamReader::new();
        assert!(r.feed(b"\"\xE2").is_ok());
        assert!(r.feed(b"\x41\"").is_ok());
        let err = r.next_event().err();
        assert_eq!(
            err.map(|e| (e.kind(), e.offset())),
            Some((ErrorKind::InvalidUtf8, 1))
        );
        // A cut character completed, with more input after it in the chunk.
        let mut r = StreamReader::new();
        assert!(r.feed(b"\"\xE2\x82").is_ok());
        assert!(r.feed(b"\xACabc\"").is_ok());
        assert_eq!(
            r.next_event().ok().and_then(Step::ready).flatten(),
            Some(Event::String("\u{20ac}abc".into()))
        );
    }

    #[test]
    fn test_feed_after_end_and_errors_latch() {
        let mut r = StreamReader::new();
        assert!(r.feed(b"[").is_ok());
        r.end_input();
        r.end_input();
        assert_eq!(
            r.feed(b"]").err().map(|e| e.kind()),
            Some(ErrorKind::InputAfterEnd)
        );
        let _start = r.next_event();
        let first = r.next_event().err();
        assert_eq!(first.map(|e| e.kind()), Some(ErrorKind::UnexpectedEnd));
        assert_eq!(r.next_event().err(), first);
        assert_eq!(r.read_raw().err(), first);
        assert_eq!(r.read_value().err(), first);
        assert_eq!(r.peek_kind().err(), first);
        assert_eq!(r.feed(b"x").err(), first);
    }

    #[test]
    fn test_compaction_keeps_memory_to_a_chunk_and_offsets_absolute() {
        let mut r = StreamReader::new();
        let item = b"12345, ";
        let mut total = 1;
        assert!(r.feed(b"[").is_ok());
        let mut max_buffered = 0;
        for _ in 0..20_000 {
            assert!(r.feed(item).is_ok());
            total += item.len();
            while let Ok(Step::Ready(Some(_))) = r.next_event() {}
            max_buffered = max_buffered.max(r.buffered());
        }
        assert!(max_buffered < 3 * COMPACT_AT, "{max_buffered}");
        assert!(r.feed(b"]").is_ok());
        let err = r.next_event().err();
        assert_eq!(
            err.map(|e| (e.kind(), e.offset())),
            Some((ErrorKind::TrailingComma, total))
        );
    }

    #[test]
    fn test_raw_value_spanning_many_chunks_survives_compaction() {
        let mut r = StreamReader::new();
        assert!(r.feed(b"[0, ").is_ok());
        let _start = r.next_event();
        assert_eq!(
            r.read_raw().ok().map(|s| s.map(|o| o.map(str::len))),
            Some(Step::Ready(Some(1)))
        );
        assert!(r.feed(b"{\"k\": [").is_ok());
        assert_eq!(r.read_raw().ok(), Some(Step::NeedInput));
        let mut expected = String::from("{\"k\": [");
        for i in 0..5_000 {
            let piece = alloc::format!("{i}, ");
            expected.push_str(&piece);
            assert!(r.feed(piece.as_bytes()).is_ok());
            assert_eq!(r.read_raw().ok(), Some(Step::NeedInput));
        }
        assert!(r.feed(b"0]}]").is_ok());
        expected.push_str("0]}");
        let raw = r
            .read_raw()
            .ok()
            .and_then(Step::ready)
            .flatten()
            .map(String::from);
        assert_eq!(raw.as_deref(), Some(expected.as_str()));
        assert_eq!(r.event_offset(), 4 + expected.len() - 1);
    }
}