Skip to main content

jsonx_lib/
reader.rs

1//! The pull reader: a document as a stream of events, without building a tree.
2
3use alloc::borrow::Cow;
4use core::iter::FusedIterator;
5
6use crate::{
7    DuplicateKeys, Kind, Limits, Number, Value,
8    error::{Error, ErrorKind},
9    machine::Machine,
10    parser,
11};
12
13/// One step through a document, from [`Reader::next_event`].
14///
15/// A document is one value. A scalar value is one event; an array is
16/// [`StartArray`](Self::StartArray), its items, then [`EndArray`](Self::EndArray);
17/// an object is [`StartObject`](Self::StartObject), then for each member a
18/// [`Key`](Self::Key) followed by the member's value, then
19/// [`EndObject`](Self::EndObject).
20///
21/// # Examples
22///
23/// ```
24/// use jsonx_lib::{Event, Reader};
25///
26/// let events: Vec<Event> = Reader::new(r#"{"a": [true]}"#).collect::<Result<_, _>>()?;
27/// assert_eq!(events, [
28///     Event::StartObject,
29///     Event::Key("a".into()),
30///     Event::StartArray,
31///     Event::Bool(true),
32///     Event::EndArray,
33///     Event::EndObject,
34/// ]);
35/// # Ok::<(), jsonx_lib::Error>(())
36/// ```
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum Event<'a> {
39    /// `{`: an object begins.
40    StartObject,
41    /// `}`: the innermost open object ends.
42    EndObject,
43    /// `[`: an array begins.
44    StartArray,
45    /// `]`: the innermost open array ends.
46    EndArray,
47    /// A member's key (the `:` after it has been read too). Borrowed unless it
48    /// had escapes.
49    Key(Cow<'a, str>),
50    /// A string value. Borrowed unless it had escapes.
51    String(Cow<'a, str>),
52    /// A number value, as its exact text.
53    Number(Number<'a>),
54    /// `true` or `false`.
55    Bool(bool),
56    /// `null`.
57    Null,
58}
59
60/// A pull parser: reads a document one [`Event`] at a time, building nothing.
61///
62/// The reader is the layer every parse in this crate goes through: it checks
63/// the full RFC 8259 grammar and every budget in [`Limits`] as it goes, with
64/// the same errors and byte offsets as [`parse`](crate::parse). Use it to pick
65/// a few fields out of a large document, to stream a document's contents
66/// somewhere without holding a tree, or to keep part of a message as raw text
67/// to be read later ([`read_raw`](Self::read_raw)).
68///
69/// The reader works over a complete document held in memory, and borrows
70/// strings and numbers from it exactly as [`parse`](crate::parse) does.
71/// Reading is iterative: depth costs one bit of reader state per level, never
72/// stack. The reader's own state for the first 64 levels, 8 open objects, and
73/// 16 of their keys is kept inline, so reading a message of ordinary shape
74/// allocates nothing but the strings it decodes.
75///
76/// **Duplicate keys.** Under [`DuplicateKeys::Error`], the default, the
77/// reader refuses an object that repeats a key, whichever way it is read:
78/// event by event, through [`read_raw`](Self::read_raw), or through
79/// [`read_value`](Self::read_value). The check happens when the object
80/// closes, so the `}` of an object with a repeated key is never returned as
81/// [`Event::EndObject`]: the reader returns [`ErrorKind::DuplicateKey`] at
82/// the repeat's opening quote instead. A loop that collects members and acts
83/// only after the object ended (as below) can therefore never act on a
84/// smuggled second value. To check, the reader keeps, for each key of the
85/// objects still open, its offset and a one-word fingerprint of its decoded
86/// text; an object whose fingerprints may match, or with more than 16 keys,
87/// has its keys read again from the input (and decoded where escaped) when
88/// it closes, and compared as text. (A [`StreamReader`](crate::StreamReader),
89/// whose input's front is dropped as it is read, keeps a decoded copy of
90/// each key instead.) Under the other policies the reader passes every
91/// member through as written; [`read_value`](Self::read_value) applies
92/// `First` and `Last` to the values it builds.
93///
94/// After an error the reader is finished: every later call returns the same
95/// error.
96///
97/// # Examples
98///
99/// Read a JSON-RPC envelope, keeping `params` as raw text for later:
100///
101/// ```
102/// use jsonx_lib::{Event, Reader};
103///
104/// let message = r#"{"jsonrpc": "2.0", "id": 4, "method": "hover", "params": {"line": 3}}"#;
105/// let mut reader = Reader::new(message);
106/// let (mut method, mut params) = (None, None);
107/// assert_eq!(reader.next_event()?, Some(Event::StartObject));
108/// while let Some(Event::Key(key)) = reader.next_event()? {
109///     match &*key {
110///         "method" => method = reader.read_value()?,
111///         "params" => params = reader.read_raw()?,
112///         _ => { let _skipped = reader.read_raw()?; }
113///     }
114/// }
115/// reader.finish()?; // the rest of the document must be valid too
116/// assert_eq!(method.as_ref().and_then(|m| m.as_str()), Some("hover"));
117/// assert_eq!(params, Some(r#"{"line": 3}"#));
118/// # Ok::<(), jsonx_lib::Error>(())
119/// ```
120#[derive(Clone, Debug)]
121pub struct Reader<'a> {
122    src: &'a str,
123    machine: Machine,
124    failed: Option<Error>,
125    /// Heap held by what the current top-level read has built (a tree, or
126    /// a typed value and everything inside it), against
127    /// [`Limits::max_memory`].
128    held: usize,
129    /// How many reads ([`read_value`](Self::read_value),
130    /// [`decode`](Self::decode)) are running, nested: the outermost one
131    /// starts `held` afresh, the ones inside it share its count.
132    reading: u32,
133}
134
135impl<'a> Reader<'a> {
136    /// A reader over `text` with the default [`Limits`].
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// use jsonx_lib::{Event, Reader};
142    ///
143    /// let mut r = Reader::new("  42 ");
144    /// assert_eq!(r.next_event()?.map(|e| e == Event::Number(42.into())), Some(true));
145    /// assert_eq!(r.next_event()?, None);
146    /// # Ok::<(), jsonx_lib::Error>(())
147    /// ```
148    #[must_use]
149    pub fn new(text: &'a str) -> Self {
150        Self::with_config(text, Limits::new(), DuplicateKeys::Error)
151    }
152
153    /// A reader with the given budgets and duplicate-key policy; see
154    /// [`Parser::reader`](crate::Parser::reader).
155    pub(crate) fn with_config(text: &'a str, limits: Limits, duplicates: DuplicateKeys) -> Self {
156        let failed = (text.len() > limits.max_input_bytes)
157            .then(|| Error::new(ErrorKind::InputTooLarge, limits.max_input_bytes));
158        Self {
159            src: text,
160            machine: Machine::new(limits, duplicates, true),
161            failed,
162            held: 0,
163            reading: 0,
164        }
165    }
166
167    /// Reads a sequence of documents instead of one: after a document's
168    /// value, another may follow, separated by any whitespace (or by
169    /// nothing, where the grammar allows: `[1][2]`). This reads
170    /// newline-delimited JSON (NDJSON, JSON Lines) and concatenated JSON.
171    /// Each document has its own [`Limits::max_elements`]; the input size
172    /// budget covers them all. Events run on from one document into the
173    /// next; [`read_value`](Self::read_value) and the other whole-value
174    /// reads return one document each, and `Ok(None)` after the last.
175    ///
176    /// # Examples
177    ///
178    /// ```
179    /// use jsonx_lib::Reader;
180    ///
181    /// let lines = "{\"n\": 1}\n{\"n\": 2}\n";
182    /// let mut r = Reader::new(lines).documents();
183    /// let mut total = 0;
184    /// while let Some(doc) = r.read_value()? {
185    ///     total += doc["n"].as_i64().unwrap_or(0);
186    /// }
187    /// assert_eq!(total, 3);
188    /// # Ok::<(), jsonx_lib::Error>(())
189    /// ```
190    #[must_use]
191    pub fn documents(mut self) -> Self {
192        self.machine.documents = true;
193        self
194    }
195
196    /// Reads the next event, or `Ok(None)` once the document's value is
197    /// complete and nothing but whitespace follows it.
198    ///
199    /// # Errors
200    ///
201    /// The first syntax error or exceeded budget, at its byte offset (see
202    /// [`Error`]). Once an error is returned, every later call returns it too.
203    ///
204    /// # Examples
205    ///
206    /// ```
207    /// use jsonx_lib::{ErrorKind, Event, Reader};
208    ///
209    /// let mut r = Reader::new("[1,]");
210    /// assert_eq!(r.next_event()?, Some(Event::StartArray));
211    /// assert!(r.next_event()?.is_some()); // 1
212    /// let err = r.next_event().unwrap_err();
213    /// assert_eq!((err.kind(), err.offset()), (ErrorKind::TrailingComma, 3));
214    /// # Ok::<(), jsonx_lib::Error>(())
215    /// ```
216    pub fn next_event(&mut self) -> Result<Option<Event<'a>>, Error> {
217        if let Some(e) = self.failed {
218            return Err(e);
219        }
220        self.machine
221            .step(self.src)
222            .inspect_err(|&e| self.failed = Some(e))
223    }
224
225    /// Reads the next value whole and returns its exact source text, without
226    /// decoding or copying it.
227    ///
228    /// Call it where a value comes next: at the start, after a [`Key`](Event::Key),
229    /// or between array items. The value is fully validated. If no value comes
230    /// next (the current array or object ends, or the document already ended),
231    /// returns `Ok(None)` and consumes nothing, so the next
232    /// [`next_event`](Self::next_event) returns the end event as usual. Calling
233    /// it where a key comes next also returns `Ok(None)`.
234    ///
235    /// The text is a slice of the input: it can be stored, compared, or parsed
236    /// later, as `serde_json`'s `RawValue` is used. Nothing of the value is
237    /// allocated; the reader's own state grows with the value's nesting (a
238    /// bit per level) and, under [`DuplicateKeys::Error`], with the keys of
239    /// its open objects, on the heap only past what it keeps inline (see
240    /// [`Reader`]).
241    ///
242    /// # Errors
243    ///
244    /// As [`next_event`](Self::next_event), for any error inside the value,
245    /// including a repeated key under [`DuplicateKeys::Error`].
246    ///
247    /// # Examples
248    ///
249    /// ```
250    /// use jsonx_lib::{Event, Reader};
251    ///
252    /// let mut r = Reader::new(r#"[{"deep": [1, 2]}, "x"]"#);
253    /// assert_eq!(r.next_event()?, Some(Event::StartArray));
254    /// assert_eq!(r.read_raw()?, Some(r#"{"deep": [1, 2]}"#));
255    /// assert_eq!(r.read_raw()?, Some(r#""x""#));
256    /// assert_eq!(r.read_raw()?, None); // the array ends here
257    /// assert_eq!(r.next_event()?, Some(Event::EndArray));
258    /// # Ok::<(), jsonx_lib::Error>(())
259    /// ```
260    pub fn read_raw(&mut self) -> Result<Option<&'a str>, Error> {
261        if let Some(e) = self.failed {
262            return Err(e);
263        }
264        if !self.machine.at_value(self.src)? {
265            return Ok(None);
266        }
267        self.machine.skipping = true;
268        let result = self.skip_value();
269        self.machine.skipping = false;
270        result.map(Some)
271    }
272
273    /// Reads the next value whole and builds it as a [`Value`], applying the
274    /// reader's [`DuplicateKeys`] policy.
275    ///
276    /// Positioning is as for [`read_raw`](Self::read_raw): `Ok(None)`, with
277    /// nothing consumed, when no value comes next.
278    ///
279    /// Each call has its own [`Limits::max_memory`] count: the tree it builds
280    /// is bounded, and what earlier calls returned is not counted, so a large
281    /// array read item by item is limited per item, not in total.
282    ///
283    /// # Errors
284    ///
285    /// As [`next_event`](Self::next_event), plus [`ErrorKind::DuplicateKey`]
286    /// under [`DuplicateKeys::Error`].
287    ///
288    /// # Examples
289    ///
290    /// ```
291    /// use jsonx_lib::{Event, Reader};
292    ///
293    /// let mut r = Reader::new(r#"{"skip": [0], "keep": {"a": 1}}"#);
294    /// r.next_event()?; // {
295    /// r.next_event()?; // "skip"
296    /// r.read_raw()?;
297    /// assert_eq!(r.next_event()?, Some(Event::Key("keep".into())));
298    /// let keep = r.read_value()?.unwrap_or_default();
299    /// assert_eq!(keep["a"], 1);
300    /// # Ok::<(), jsonx_lib::Error>(())
301    /// ```
302    pub fn read_value(&mut self) -> Result<Option<Value<'a>>, Error> {
303        if let Some(e) = self.failed {
304            return Err(e);
305        }
306        if !self.machine.at_value(self.src)? {
307            return Ok(None);
308        }
309        let duplicates = self.machine.duplicates;
310        self.begin_read();
311        let built = parser::build(self, duplicates);
312        self.end_read();
313        built.inspect_err(|&e| self.failed = Some(e)).map(Some)
314    }
315
316    /// The kind of the next value, without consuming anything: `None` when
317    /// no value comes next (positioning as for [`read_raw`](Self::read_raw)),
318    /// or when the next byte cannot start one (the next
319    /// [`next_event`](Self::next_event) reports why). Decided by the value's
320    /// first byte alone, so `tru` peeks as [`Kind::Bool`].
321    ///
322    /// Useful for a value that may be one of several shapes, such as LSP's
323    /// `string | number` ids.
324    ///
325    /// # Errors
326    ///
327    /// Any error the reader already stopped at.
328    ///
329    /// # Examples
330    ///
331    /// ```
332    /// use jsonx_lib::{Kind, Reader};
333    ///
334    /// let mut r = Reader::new(r#"[7, "seven"]"#);
335    /// r.next_event()?;
336    /// assert_eq!(r.peek_kind()?, Some(Kind::Number));
337    /// r.read_raw()?;
338    /// assert_eq!(r.peek_kind()?, Some(Kind::String));
339    /// r.read_raw()?;
340    /// assert_eq!(r.peek_kind()?, None); // the array ends
341    /// # Ok::<(), jsonx_lib::Error>(())
342    /// ```
343    pub fn peek_kind(&mut self) -> Result<Option<Kind>, Error> {
344        if let Some(e) = self.failed {
345            return Err(e);
346        }
347        Ok(if self.machine.at_value(self.src)? {
348            self.machine.peek_kind(self.src)
349        } else {
350            None
351        })
352    }
353
354    /// Finds the value at an [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)
355    /// JSON Pointer in the value that comes next, without building anything,
356    /// and returns its exact source text: what
357    /// [`Value::pointer`](crate::Value::pointer) would find, without the
358    /// tree. Everything before the target is read and validated; members and
359    /// items that are not on the way are skipped with
360    /// [`read_raw`](Self::read_raw).
361    ///
362    /// **Duplicate keys.** Under [`DuplicateKeys::Error`], the default, the
363    /// answer is given only for a value with no repeated key anywhere in it:
364    /// the reader reads the rest of the value it started on before
365    /// returning (and, started at the top of a document, the rest of the
366    /// document, as [`finish`](Self::finish) does), so
367    /// `{"method": "a", "method": "b"}` is refused, as by
368    /// [`parse`](crate::parse), rather than answered with either member. The
369    /// reader then stands past that value. Under the other policies it stops
370    /// just past the target, without reading the rest, and in an object the
371    /// first member with the key is the one taken.
372    ///
373    /// `Ok(None)` when the pointer is malformed or names nothing (as
374    /// `Value::pointer`'s `None`).
375    ///
376    /// # Errors
377    ///
378    /// Any error of the reader on the way to the target, or inside it, and
379    /// under `DuplicateKeys::Error` in the rest of the value (a repeated key
380    /// included).
381    ///
382    /// # Examples
383    ///
384    /// ```
385    /// use jsonx_lib::Reader;
386    ///
387    /// let message = r#"{"jsonrpc": "2.0", "id": 9, "params": {"items": [{"label": "a"}, {"label": "b"}]}}"#;
388    /// assert_eq!(Reader::new(message).find_pointer("/params/items/1/label")?, Some(r#""b""#));
389    /// assert_eq!(Reader::new(message).find_pointer("/id")?, Some("9"));
390    /// assert_eq!(Reader::new(message).find_pointer("/params/missing")?, None);
391    ///
392    /// // A repeated key anywhere is refused, as `parse` refuses it.
393    /// let smuggled = r#"{"method": "initialize", "method": "shutdown"}"#;
394    /// assert!(Reader::new(smuggled).find_pointer("/method").is_err());
395    /// # Ok::<(), jsonx_lib::Error>(())
396    /// ```
397    pub fn find_pointer(&mut self, pointer: &str) -> Result<Option<&'a str>, Error> {
398        let depth = self.depth();
399        let found = self.find_in(pointer)?;
400        if self.machine.duplicates == DuplicateKeys::Error {
401            // The rest of the value, so that every object in it is checked.
402            while self.depth() > depth {
403                if self.next_event()?.is_none() {
404                    break;
405                }
406            }
407            if depth == 0 && !self.machine.documents {
408                self.read_to_end()?;
409            }
410        }
411        Ok(found)
412    }
413
414    /// [`find_pointer`](Self::find_pointer) up to the target.
415    fn find_in(&mut self, pointer: &str) -> Result<Option<&'a str>, Error> {
416        if pointer.is_empty() {
417            return self.read_raw();
418        }
419        let Some(rest) = pointer.strip_prefix('/') else {
420            return Ok(None);
421        };
422        for token in rest.split('/') {
423            let Some(token) = crate::value::unescape_pointer_token(token) else {
424                return Ok(None);
425            };
426            match self.peek_kind()? {
427                Some(Kind::Object) => {
428                    let _start = self.next_event()?;
429                    loop {
430                        match self.next_event()? {
431                            Some(Event::Key(key)) if key == token => break,
432                            Some(Event::Key(_)) => {
433                                let _skipped = self.read_raw()?;
434                            }
435                            _ => return Ok(None),
436                        }
437                    }
438                }
439                Some(Kind::Array) => {
440                    let Some(index) = crate::value::array_index(&token) else {
441                        return Ok(None);
442                    };
443                    let _start = self.next_event()?;
444                    for _ in 0..index {
445                        if self.read_raw()?.is_none() {
446                            return Ok(None);
447                        }
448                    }
449                    if self.peek_kind()?.is_none() {
450                        return Ok(None);
451                    }
452                }
453                _ => return Ok(None),
454            }
455        }
456        self.read_raw()
457    }
458
459    /// Reads to the end of the document, checking that the rest of it is
460    /// valid and that nothing but whitespace follows its value.
461    ///
462    /// # Errors
463    ///
464    /// The first error in the rest of the document.
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// use jsonx_lib::{ErrorKind, Event, Reader};
470    ///
471    /// let mut r = Reader::new(r#"{"id": 1, "x": [} "#);
472    /// assert_eq!(r.next_event()?, Some(Event::StartObject));
473    /// let err = r.finish().unwrap_err();
474    /// assert_eq!((err.kind(), err.offset()), (ErrorKind::ExpectedValue, 16));
475    /// # Ok::<(), jsonx_lib::Error>(())
476    /// ```
477    pub fn finish(mut self) -> Result<(), Error> {
478        self.read_to_end()
479    }
480
481    /// [`finish`](Self::finish) in place, for the crate's own one-call
482    /// functions: the reader is not moved (it is several hundred bytes).
483    #[inline]
484    pub(crate) fn read_to_end(&mut self) -> Result<(), Error> {
485        while self.next_event()?.is_some() {}
486        Ok(())
487    }
488
489    /// The number of arrays and objects open at this point.
490    ///
491    /// # Examples
492    ///
493    /// ```
494    /// let mut r = jsonx_lib::Reader::new("[[]]");
495    /// r.next_event()?;
496    /// r.next_event()?;
497    /// assert_eq!(r.depth(), 2);
498    /// # Ok::<(), jsonx_lib::Error>(())
499    /// ```
500    #[inline]
501    #[must_use]
502    pub fn depth(&self) -> usize {
503        self.machine.depth()
504    }
505
506    /// The byte offset just past the input consumed so far.
507    ///
508    /// # Examples
509    ///
510    /// ```
511    /// let mut r = jsonx_lib::Reader::new("[10, 20]");
512    /// r.next_event()?;
513    /// r.next_event()?;
514    /// assert_eq!(r.offset(), 3);
515    /// # Ok::<(), jsonx_lib::Error>(())
516    /// ```
517    #[inline]
518    #[must_use]
519    pub fn offset(&self) -> usize {
520        self.machine.pos
521    }
522
523    /// The byte offset where the most recent event's token began: the quote of
524    /// a key or string, the first byte of a number or literal, the bracket or
525    /// brace of a start or end event. Useful for pointing a diagnostic of your
526    /// own at the value it is about.
527    ///
528    /// # Examples
529    ///
530    /// ```
531    /// let mut r = jsonx_lib::Reader::new(r#"{ "a" : 1 }"#);
532    /// r.next_event()?;
533    /// r.next_event()?;
534    /// assert_eq!(r.event_offset(), 2); // the key's opening quote
535    /// r.next_event()?;
536    /// assert_eq!(r.event_offset(), 8); // the number
537    /// # Ok::<(), jsonx_lib::Error>(())
538    /// ```
539    #[inline]
540    #[must_use]
541    pub fn event_offset(&self) -> usize {
542        self.machine.last
543    }
544
545    // ---- internals -----------------------------------------------------------
546
547    /// Sets how typed reads take integers.
548    pub(crate) const fn with_numbers(mut self, numbers: crate::Numbers) -> Self {
549        self.machine.numbers = numbers;
550        self
551    }
552
553    /// How typed reads take integers.
554    #[inline]
555    pub(crate) const fn number_policy(&self) -> crate::Numbers {
556        self.machine.numbers
557    }
558
559    /// Whether a value comes next (consuming a separating `,`).
560    #[inline]
561    pub(crate) fn at_a_value(&mut self) -> Result<bool, Error> {
562        if let Some(e) = self.failed {
563            return Err(e);
564        }
565        self.machine.at_value(self.src)
566    }
567
568    /// Enters the object (`object`) or array that comes next, if one does:
569    /// see [`Machine::enter`].
570    #[inline]
571    pub(crate) fn enter(&mut self, object: bool) -> Result<bool, Error> {
572        if let Some(e) = self.failed {
573            return Err(e);
574        }
575        self.machine
576            .enter(self.src, object)
577            .inspect_err(|&e| self.failed = Some(e))
578    }
579
580    /// The decoded text of the key whose opening quote is at `quote` (for an
581    /// error's path: the key is read again).
582    pub(crate) fn key_at(&self, quote: usize) -> alloc::string::String {
583        crate::machine::key_text(self.src, quote).into_owned()
584    }
585
586    /// [`at_a_value`](Self::at_a_value) inside an array, with the common
587    /// case (a `,` and an item, or a first item) inline.
588    #[inline]
589    pub(crate) fn at_item(&mut self) -> Result<bool, Error> {
590        if let Some(e) = self.failed {
591            return Err(e);
592        }
593        match self.machine.at_item(self.src) {
594            Some(more) => Ok(more),
595            None => self.machine.at_value(self.src),
596        }
597    }
598
599    /// Enters a read that builds something (a tree or a typed value). The
600    /// outermost one starts the memory count afresh: what an earlier call
601    /// built has been handed to the caller, who may have dropped it, so only
602    /// what one call builds is bounded. Reads nested inside it (a `Value`
603    /// field of a typed decode, a `decode` called from a `FromJson` impl)
604    /// share its count. Pair with [`end_read`](Self::end_read).
605    #[inline]
606    pub(crate) fn begin_read(&mut self) {
607        if self.reading == 0 {
608            self.held = 0;
609        }
610        self.reading += 1;
611    }
612
613    /// Leaves a read entered with [`begin_read`](Self::begin_read).
614    #[inline]
615    pub(crate) fn end_read(&mut self) {
616        self.reading = self.reading.saturating_sub(1);
617    }
618
619    /// What the current top-level read holds, in bytes.
620    #[inline]
621    pub(crate) const fn held(&self) -> usize {
622        self.held
623    }
624
625    /// Records `held` bytes held in all by the current top-level read.
626    #[inline]
627    pub(crate) fn set_held(&mut self, held: usize) {
628        self.held = held;
629    }
630
631    /// The memory budget, [`Limits::max_memory`].
632    #[inline]
633    pub(crate) const fn max_memory(&self) -> usize {
634        self.machine.limits.max_memory
635    }
636
637    /// Charges `bytes` more to the current top-level read, refusing them, as
638    /// [`ErrorKind::MemoryLimitExceeded`] at `at`, past
639    /// [`Limits::max_memory`].
640    #[inline]
641    pub(crate) fn charge(&mut self, bytes: usize, at: usize) -> Result<(), Error> {
642        let held = self.held.saturating_add(bytes);
643        if held > self.max_memory() {
644            return Err(Error::new(ErrorKind::MemoryLimitExceeded, at));
645        }
646        self.held = held;
647        Ok(())
648    }
649
650    /// The reader's duplicate-key policy.
651    #[inline]
652    pub(crate) fn duplicate_policy(&self) -> DuplicateKeys {
653        self.machine.duplicates
654    }
655
656    /// Consumes one whole value (the reader is positioned at it) and returns
657    /// its text.
658    fn skip_value(&mut self) -> Result<&'a str, Error> {
659        let depth = self.machine.depth();
660        let first = self.next_event()?;
661        let start = self.machine.last;
662        if matches!(first, Some(Event::StartArray | Event::StartObject)) {
663            while self.machine.depth() > depth {
664                if self.next_event()?.is_none() {
665                    return Err(Error::new(ErrorKind::UnexpectedEnd, self.src.len()));
666                }
667            }
668        }
669        Ok(self.src.get(start..self.machine.pos).unwrap_or(""))
670    }
671}
672
673impl<'a> Iterator for Reader<'a> {
674    type Item = Result<Event<'a>, Error>;
675
676    /// The next event; after the end or an error, `None`. An error is yielded
677    /// once.
678    fn next(&mut self) -> Option<Self::Item> {
679        if self.failed.is_some() && self.machine.is_done() {
680            return None;
681        }
682        match self.next_event() {
683            Ok(Some(event)) => Some(Ok(event)),
684            Ok(None) => None,
685            Err(e) => {
686                // Yield the error once, then stop.
687                self.machine.finish_iteration();
688                Some(Err(e))
689            }
690        }
691    }
692}
693
694impl FusedIterator for Reader<'_> {}