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)`. After a single
234    /// document's value, `Ok(None)` is returned only if nothing but
235    /// whitespace follows; anything else is
236    /// [`ErrorKind::TrailingCharacters`], as [`next_event`](Self::next_event)
237    /// and [`finish`](Self::finish) report it.
238    ///
239    /// The text is a slice of the input: it can be stored, compared, or parsed
240    /// later, as `serde_json`'s `RawValue` is used. Nothing of the value is
241    /// allocated; the reader's own state grows with the value's nesting (a
242    /// bit per level) and, under [`DuplicateKeys::Error`], with the keys of
243    /// its open objects, on the heap only past what it keeps inline (see
244    /// [`Reader`]).
245    ///
246    /// # Errors
247    ///
248    /// As [`next_event`](Self::next_event), for any error inside the value,
249    /// including a repeated key under [`DuplicateKeys::Error`], and
250    /// [`ErrorKind::TrailingCharacters`] after the document.
251    ///
252    /// # Examples
253    ///
254    /// ```
255    /// use jsonx_lib::{Event, Reader};
256    ///
257    /// let mut r = Reader::new(r#"[{"deep": [1, 2]}, "x"]"#);
258    /// assert_eq!(r.next_event()?, Some(Event::StartArray));
259    /// assert_eq!(r.read_raw()?, Some(r#"{"deep": [1, 2]}"#));
260    /// assert_eq!(r.read_raw()?, Some(r#""x""#));
261    /// assert_eq!(r.read_raw()?, None); // the array ends here
262    /// assert_eq!(r.next_event()?, Some(Event::EndArray));
263    /// # Ok::<(), jsonx_lib::Error>(())
264    /// ```
265    pub fn read_raw(&mut self) -> Result<Option<&'a str>, Error> {
266        if let Some(e) = self.failed {
267            return Err(e);
268        }
269        if !self.machine.at_value(self.src)? {
270            return self.no_value();
271        }
272        self.machine.skipping = true;
273        let result = self.skip_value();
274        self.machine.skipping = false;
275        result.map(Some)
276    }
277
278    /// Reads the next value whole and builds it as a [`Value`], applying the
279    /// reader's [`DuplicateKeys`] policy.
280    ///
281    /// Positioning is as for [`read_raw`](Self::read_raw): `Ok(None)`, with
282    /// nothing consumed, when no value comes next.
283    ///
284    /// Each call has its own [`Limits::max_memory`] count: the tree it builds
285    /// is bounded, and what earlier calls returned is not counted, so a large
286    /// array read item by item is limited per item, not in total.
287    ///
288    /// # Errors
289    ///
290    /// As [`next_event`](Self::next_event), plus [`ErrorKind::DuplicateKey`]
291    /// under [`DuplicateKeys::Error`].
292    ///
293    /// # Examples
294    ///
295    /// ```
296    /// use jsonx_lib::{Event, Reader};
297    ///
298    /// let mut r = Reader::new(r#"{"skip": [0], "keep": {"a": 1}}"#);
299    /// r.next_event()?; // {
300    /// r.next_event()?; // "skip"
301    /// r.read_raw()?;
302    /// assert_eq!(r.next_event()?, Some(Event::Key("keep".into())));
303    /// let keep = r.read_value()?.unwrap_or_default();
304    /// assert_eq!(keep["a"], 1);
305    /// # Ok::<(), jsonx_lib::Error>(())
306    /// ```
307    pub fn read_value(&mut self) -> Result<Option<Value<'a>>, Error> {
308        if let Some(e) = self.failed {
309            return Err(e);
310        }
311        if !self.machine.at_value(self.src)? {
312            return self.no_value();
313        }
314        let duplicates = self.machine.duplicates;
315        self.begin_read();
316        let built = parser::build(self, duplicates);
317        self.end_read();
318        built.inspect_err(|&e| self.failed = Some(e)).map(Some)
319    }
320
321    /// The kind of the next value, without consuming anything: `None` when
322    /// no value comes next (positioning as for [`read_raw`](Self::read_raw)),
323    /// or when the next byte cannot start one (the next
324    /// [`next_event`](Self::next_event) reports why). Decided by the value's
325    /// first byte alone, so `tru` peeks as [`Kind::Bool`].
326    ///
327    /// Useful for a value that may be one of several shapes, such as LSP's
328    /// `string | number` ids.
329    ///
330    /// # Errors
331    ///
332    /// Any error the reader already stopped at.
333    ///
334    /// # Examples
335    ///
336    /// ```
337    /// use jsonx_lib::{Kind, Reader};
338    ///
339    /// let mut r = Reader::new(r#"[7, "seven"]"#);
340    /// r.next_event()?;
341    /// assert_eq!(r.peek_kind()?, Some(Kind::Number));
342    /// r.read_raw()?;
343    /// assert_eq!(r.peek_kind()?, Some(Kind::String));
344    /// r.read_raw()?;
345    /// assert_eq!(r.peek_kind()?, None); // the array ends
346    /// # Ok::<(), jsonx_lib::Error>(())
347    /// ```
348    pub fn peek_kind(&mut self) -> Result<Option<Kind>, Error> {
349        if let Some(e) = self.failed {
350            return Err(e);
351        }
352        Ok(if self.machine.at_value(self.src)? {
353            self.machine.peek_kind(self.src)
354        } else {
355            None
356        })
357    }
358
359    /// Finds the value at an [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)
360    /// JSON Pointer in the value that comes next, without building anything,
361    /// and returns its exact source text: what
362    /// [`Value::pointer`](crate::Value::pointer) would find, without the
363    /// tree. Everything before the target is read and validated; members and
364    /// items that are not on the way are skipped with
365    /// [`read_raw`](Self::read_raw).
366    ///
367    /// **Duplicate keys.** Under [`DuplicateKeys::Error`], the default, the
368    /// answer is given only for a value with no repeated key anywhere in it:
369    /// the reader reads the rest of the value it started on before
370    /// returning (and, started at the top of a document, the rest of the
371    /// document, as [`finish`](Self::finish) does), so
372    /// `{"method": "a", "method": "b"}` is refused, as by
373    /// [`parse`](crate::parse), rather than answered with either member. The
374    /// reader then stands past that value. Under
375    /// [`DuplicateKeys::Last`] the member taken is the last one with the
376    /// key, as [`parse`](crate::parse) and typed reads under that policy
377    /// keep it: each object on the way is read to its end, and the reader
378    /// stands past the value it started on. Under the other policies it
379    /// stops just past the target, without reading the rest, and in an
380    /// object the first member with the key is the one taken.
381    ///
382    /// `Ok(None)` when the pointer is malformed or names nothing (as
383    /// `Value::pointer`'s `None`).
384    ///
385    /// # Errors
386    ///
387    /// Any error of the reader on the way to the target, or inside it, and
388    /// under `DuplicateKeys::Error` in the rest of the value (a repeated key
389    /// included).
390    ///
391    /// # Examples
392    ///
393    /// ```
394    /// use jsonx_lib::Reader;
395    ///
396    /// let message = r#"{"jsonrpc": "2.0", "id": 9, "params": {"items": [{"label": "a"}, {"label": "b"}]}}"#;
397    /// assert_eq!(Reader::new(message).find_pointer("/params/items/1/label")?, Some(r#""b""#));
398    /// assert_eq!(Reader::new(message).find_pointer("/id")?, Some("9"));
399    /// assert_eq!(Reader::new(message).find_pointer("/params/missing")?, None);
400    ///
401    /// // A repeated key anywhere is refused, as `parse` refuses it.
402    /// let smuggled = r#"{"method": "initialize", "method": "shutdown"}"#;
403    /// assert!(Reader::new(smuggled).find_pointer("/method").is_err());
404    /// # Ok::<(), jsonx_lib::Error>(())
405    /// ```
406    pub fn find_pointer(&mut self, pointer: &str) -> Result<Option<&'a str>, Error> {
407        let depth = self.depth();
408        let found = self.find_in(pointer)?;
409        if self.machine.duplicates == DuplicateKeys::Last {
410            // The rest of the value it started on (each object on the way
411            // was read whole already).
412            while self.depth() > depth {
413                if self.next_event()?.is_none() {
414                    break;
415                }
416            }
417        } else if self.machine.duplicates == DuplicateKeys::Error {
418            // The rest of the value, so that every object in it is checked.
419            while self.depth() > depth {
420                if self.next_event()?.is_none() {
421                    break;
422                }
423            }
424            if depth == 0 && !self.machine.documents {
425                self.read_to_end()?;
426            }
427        }
428        Ok(found)
429    }
430
431    /// [`find_pointer`](Self::find_pointer) up to the target.
432    fn find_in(&mut self, pointer: &str) -> Result<Option<&'a str>, Error> {
433        if pointer.is_empty() {
434            return self.read_raw();
435        }
436        match pointer.strip_prefix('/') {
437            Some(tokens) => self.find_tokens(tokens),
438            None => Ok(None),
439        }
440    }
441
442    /// [`find_in`](Self::find_in) for a pointer without its leading `/`.
443    fn find_tokens(&mut self, mut tokens: &str) -> Result<Option<&'a str>, Error> {
444        loop {
445            let (token, more) = match tokens.split_once('/') {
446                Some((token, more)) => (token, Some(more)),
447                None => (tokens, None),
448            };
449            let Some(token) = crate::value::unescape_pointer_token(token) else {
450                return Ok(None);
451            };
452            match self.peek_kind()? {
453                Some(Kind::Object) if self.machine.duplicates == DuplicateKeys::Last => {
454                    let Some(member) = self.last_member(&token)? else {
455                        return Ok(None);
456                    };
457                    let Some(more) = more else {
458                        return Ok(Some(member));
459                    };
460                    // The rest of the pointer, in the member's text. It was
461                    // read and checked whole, so reading it again cannot
462                    // fail.
463                    let mut inner =
464                        Reader::with_config(member, self.machine.limits, DuplicateKeys::Last);
465                    return inner.find_tokens(more);
466                }
467                Some(Kind::Object) => {
468                    let _start = self.next_event()?;
469                    loop {
470                        match self.next_event()? {
471                            Some(Event::Key(key)) if key == token => break,
472                            Some(Event::Key(_)) => {
473                                let _skipped = self.read_raw()?;
474                            }
475                            _ => return Ok(None),
476                        }
477                    }
478                }
479                Some(Kind::Array) => {
480                    let Some(index) = crate::value::array_index(&token) else {
481                        return Ok(None);
482                    };
483                    let _start = self.next_event()?;
484                    for _ in 0..index {
485                        if self.read_raw()?.is_none() {
486                            return Ok(None);
487                        }
488                    }
489                    if self.peek_kind()?.is_none() {
490                        return Ok(None);
491                    }
492                }
493                _ => return Ok(None),
494            }
495            match more {
496                Some(more) => tokens = more,
497                None => return self.read_raw(),
498            }
499        }
500    }
501
502    /// Reads the object that comes next to its end and returns the text of
503    /// the last member with the key `key`, or `None` if it has none.
504    fn last_member(&mut self, key: &str) -> Result<Option<&'a str>, Error> {
505        let _start = self.next_event()?;
506        let mut found = None;
507        while let Some(Event::Key(name)) = self.next_event()? {
508            let hit = name == key;
509            let value = self.read_raw()?;
510            if hit {
511                found = value;
512            }
513        }
514        Ok(found)
515    }
516
517    /// Reads to the end of the document, checking that the rest of it is
518    /// valid and that nothing but whitespace follows its value.
519    ///
520    /// # Errors
521    ///
522    /// The first error in the rest of the document.
523    ///
524    /// # Examples
525    ///
526    /// ```
527    /// use jsonx_lib::{ErrorKind, Event, Reader};
528    ///
529    /// let mut r = Reader::new(r#"{"id": 1, "x": [} "#);
530    /// assert_eq!(r.next_event()?, Some(Event::StartObject));
531    /// let err = r.finish().unwrap_err();
532    /// assert_eq!((err.kind(), err.offset()), (ErrorKind::ExpectedValue, 16));
533    /// # Ok::<(), jsonx_lib::Error>(())
534    /// ```
535    pub fn finish(mut self) -> Result<(), Error> {
536        self.read_to_end()
537    }
538
539    /// The answer of a whole-value read where no value comes next: `None`,
540    /// unless a single document's value is followed by more than
541    /// whitespace.
542    fn no_value<T>(&mut self) -> Result<Option<T>, Error> {
543        self.machine
544            .check_trailing(self.src)
545            .inspect_err(|&e| self.failed = Some(e))?;
546        Ok(None)
547    }
548
549    /// [`finish`](Self::finish) in place, for the crate's own one-call
550    /// functions: the reader is not moved (it is several hundred bytes).
551    #[inline]
552    pub(crate) fn read_to_end(&mut self) -> Result<(), Error> {
553        while self.next_event()?.is_some() {}
554        Ok(())
555    }
556
557    /// The number of arrays and objects open at this point.
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// let mut r = jsonx_lib::Reader::new("[[]]");
563    /// r.next_event()?;
564    /// r.next_event()?;
565    /// assert_eq!(r.depth(), 2);
566    /// # Ok::<(), jsonx_lib::Error>(())
567    /// ```
568    #[inline]
569    #[must_use]
570    pub fn depth(&self) -> usize {
571        self.machine.depth()
572    }
573
574    /// The byte offset just past the input consumed so far.
575    ///
576    /// # Examples
577    ///
578    /// ```
579    /// let mut r = jsonx_lib::Reader::new("[10, 20]");
580    /// r.next_event()?;
581    /// r.next_event()?;
582    /// assert_eq!(r.offset(), 3);
583    /// # Ok::<(), jsonx_lib::Error>(())
584    /// ```
585    #[inline]
586    #[must_use]
587    pub fn offset(&self) -> usize {
588        self.machine.pos
589    }
590
591    /// The byte offset where the most recent event's token began: the quote of
592    /// a key or string, the first byte of a number or literal, the bracket or
593    /// brace of a start or end event. Useful for pointing a diagnostic of your
594    /// own at the value it is about.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// let mut r = jsonx_lib::Reader::new(r#"{ "a" : 1 }"#);
600    /// r.next_event()?;
601    /// r.next_event()?;
602    /// assert_eq!(r.event_offset(), 2); // the key's opening quote
603    /// r.next_event()?;
604    /// assert_eq!(r.event_offset(), 8); // the number
605    /// # Ok::<(), jsonx_lib::Error>(())
606    /// ```
607    #[inline]
608    #[must_use]
609    pub fn event_offset(&self) -> usize {
610        self.machine.last
611    }
612
613    // ---- internals -----------------------------------------------------------
614
615    /// Sets how typed reads take integers.
616    pub(crate) const fn with_numbers(mut self, numbers: crate::Numbers) -> Self {
617        self.machine.numbers = numbers;
618        self
619    }
620
621    /// How typed reads take integers.
622    #[inline]
623    pub(crate) const fn number_policy(&self) -> crate::Numbers {
624        self.machine.numbers
625    }
626
627    /// Whether a value comes next (consuming a separating `,`).
628    #[inline]
629    pub(crate) fn at_a_value(&mut self) -> Result<bool, Error> {
630        if let Some(e) = self.failed {
631            return Err(e);
632        }
633        self.machine.at_value(self.src)
634    }
635
636    /// Enters the object (`object`) or array that comes next, if one does:
637    /// see [`Machine::enter`].
638    #[inline]
639    pub(crate) fn enter(&mut self, object: bool) -> Result<bool, Error> {
640        if let Some(e) = self.failed {
641            return Err(e);
642        }
643        self.machine
644            .enter(self.src, object)
645            .inspect_err(|&e| self.failed = Some(e))
646    }
647
648    /// The decoded text of the key whose opening quote is at `quote` (for an
649    /// error's path: the key is read again).
650    pub(crate) fn key_at(&self, quote: usize) -> alloc::string::String {
651        crate::machine::key_text(self.src, quote).into_owned()
652    }
653
654    /// [`at_a_value`](Self::at_a_value) inside an array, with the common
655    /// case (a `,` and an item, or a first item) inline.
656    #[inline]
657    pub(crate) fn at_item(&mut self) -> Result<bool, Error> {
658        if let Some(e) = self.failed {
659            return Err(e);
660        }
661        match self.machine.at_item(self.src) {
662            Some(more) => Ok(more),
663            None => self.machine.at_value(self.src),
664        }
665    }
666
667    /// Enters a read that builds something (a tree or a typed value). The
668    /// outermost one starts the memory count afresh: what an earlier call
669    /// built has been handed to the caller, who may have dropped it, so only
670    /// what one call builds is bounded. Reads nested inside it (a `Value`
671    /// field of a typed decode, a `decode` called from a `FromJson` impl)
672    /// share its count. Pair with [`end_read`](Self::end_read).
673    #[inline]
674    pub(crate) fn begin_read(&mut self) {
675        if self.reading == 0 {
676            self.held = 0;
677        }
678        self.reading += 1;
679    }
680
681    /// Leaves a read entered with [`begin_read`](Self::begin_read).
682    #[inline]
683    pub(crate) fn end_read(&mut self) {
684        self.reading = self.reading.saturating_sub(1);
685    }
686
687    /// What the current top-level read holds, in bytes.
688    #[inline]
689    pub(crate) const fn held(&self) -> usize {
690        self.held
691    }
692
693    /// Records `held` bytes held in all by the current top-level read.
694    #[inline]
695    pub(crate) fn set_held(&mut self, held: usize) {
696        self.held = held;
697    }
698
699    /// The memory budget, [`Limits::max_memory`].
700    #[inline]
701    pub(crate) const fn max_memory(&self) -> usize {
702        self.machine.limits.max_memory
703    }
704
705    /// Charges `bytes` more to the current top-level read, refusing them, as
706    /// [`ErrorKind::MemoryLimitExceeded`] at `at`, past
707    /// [`Limits::max_memory`].
708    #[inline]
709    pub(crate) fn charge(&mut self, bytes: usize, at: usize) -> Result<(), Error> {
710        let held = self.held.saturating_add(bytes);
711        if held > self.max_memory() {
712            return Err(Error::new(ErrorKind::MemoryLimitExceeded, at));
713        }
714        self.held = held;
715        Ok(())
716    }
717
718    /// The reader's duplicate-key policy.
719    #[inline]
720    pub(crate) fn duplicate_policy(&self) -> DuplicateKeys {
721        self.machine.duplicates
722    }
723
724    /// Consumes one whole value (the reader is positioned at it) and returns
725    /// its text.
726    fn skip_value(&mut self) -> Result<&'a str, Error> {
727        let depth = self.machine.depth();
728        let first = self.next_event()?;
729        let start = self.machine.last;
730        if matches!(first, Some(Event::StartArray | Event::StartObject)) {
731            while self.machine.depth() > depth {
732                if self.next_event()?.is_none() {
733                    return Err(Error::new(ErrorKind::UnexpectedEnd, self.src.len()));
734                }
735            }
736        }
737        Ok(self.src.get(start..self.machine.pos).unwrap_or(""))
738    }
739}
740
741impl<'a> Iterator for Reader<'a> {
742    type Item = Result<Event<'a>, Error>;
743
744    /// The next event; after the end or an error, `None`. An error is yielded
745    /// once.
746    fn next(&mut self) -> Option<Self::Item> {
747        if self.failed.is_some() && self.machine.is_done() {
748            return None;
749        }
750        match self.next_event() {
751            Ok(Some(event)) => Some(Ok(event)),
752            Ok(None) => None,
753            Err(e) => {
754                // Yield the error once, then stop.
755                self.machine.finish_iteration();
756                Some(Err(e))
757            }
758        }
759    }
760}
761
762impl FusedIterator for Reader<'_> {}