Skip to main content

jsonx_lib/
decode.rs

1//! Typed input: [`FromJson`], read straight from a [`Reader`].
2//!
3//! A `FromJson` type reads itself from the reader's events: no [`Value`] is
4//! built, strings borrow from the input unless they had escapes, and a
5//! mismatch is a [`DecodeError`] that says what was expected, what was
6//! found, at which byte, and where in the document (a JSON Pointer path).
7
8#[cfg(target_has_atomic = "ptr")]
9use alloc::sync::Arc;
10use alloc::{
11    borrow::Cow,
12    boxed::Box,
13    collections::{BTreeMap, BTreeSet, VecDeque},
14    format,
15    rc::Rc,
16    string::String,
17    vec::Vec,
18};
19use core::fmt;
20
21use crate::{
22    Array, DuplicateKeys, Kind, Limits, Number, Numbers, Object, Parser, Reader, ToJson, Value,
23    ValueWriter, Written,
24    error::{Error, ErrorKind},
25    reader::Event,
26};
27
28// ---- Errors ------------------------------------------------------------------
29
30/// One step of the path to a value: an object member's key, or an array
31/// item's index.
32///
33/// # Examples
34///
35/// ```
36/// use jsonx_lib::PathSegment;
37///
38/// assert_eq!(PathSegment::Key("line".into()).to_string(), "line");
39/// assert_eq!(PathSegment::Index(3).to_string(), "3");
40/// ```
41#[derive(Clone, Debug, PartialEq, Eq, Hash)]
42pub enum PathSegment {
43    /// The member with this key.
44    Key(String),
45    /// The item at this index.
46    Index(usize),
47}
48
49impl fmt::Display for PathSegment {
50    /// The segment as it reads in a path: the key, or the index in decimal.
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::Key(key) => f.write_str(key),
54            Self::Index(index) => write!(f, "{index}"),
55        }
56    }
57}
58
59/// What went wrong reading a typed value; see [`DecodeError`].
60///
61/// The enum is `#[non_exhaustive]`: match with a wildcard arm.
62///
63/// # Examples
64///
65/// ```
66/// use jsonx_lib::{DecodeErrorKind, Kind};
67///
68/// let err = jsonx_lib::from_str::<u8>("\"7\"").unwrap_err();
69/// assert_eq!(err.kind(), &DecodeErrorKind::WrongType { expected: "u8", found: Kind::String });
70/// ```
71#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum DecodeErrorKind {
74    /// The text is not valid JSON, or is over a budget: the [`ErrorKind`] a
75    /// parse of the same text reports.
76    Syntax(ErrorKind),
77    /// The value is of the wrong kind: `found` where `expected` (a type
78    /// name such as `"u32"`, or a description such as `"an object"`)
79    /// belongs.
80    WrongType {
81        /// What the target type accepts.
82        expected: &'static str,
83        /// What the document has.
84        found: Kind,
85    },
86    /// A number that does not fit the target type: out of its range, or not
87    /// an integer for an integer type (`1.5` or `1e3` for a `u32`; integers
88    /// are read from integer text only, as [`Number::as_i64`] does).
89    OutOfRange {
90        /// The target type.
91        expected: &'static str,
92    },
93    /// A string with escape sequences was read into a borrowed `&str`, which
94    /// can only point into the input. Read it into `String` or `Cow<str>`.
95    StringNotBorrowable,
96    /// An array of the wrong length for a fixed-size array or a tuple.
97    WrongLength {
98        /// The length the target needs.
99        expected: usize,
100        /// The length the document has.
101        found: usize,
102    },
103    /// An object lacks a member its type requires. The offset is the
104    /// object's opening brace.
105    MissingField(&'static str),
106    /// An object has a member its type does not know, refused with
107    /// [`ObjectReader::unknown_field`]. The key is the last path segment.
108    UnknownField,
109    /// An object repeats a member, found by [`ObjectReader::field`] or a map
110    /// under [`DuplicateKeys::Error`]. The key is the last path segment.
111    DuplicateField,
112    /// The value has the right kind but not an acceptable value; the text
113    /// says what was expected (`"a single character"`, `"a URI"`).
114    InvalidValue(&'static str),
115    /// An error of the implementation's own, with its message.
116    Custom(Cow<'static, str>),
117}
118
119impl fmt::Display for DecodeErrorKind {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            Self::Syntax(kind) => write!(f, "{kind}"),
123            Self::WrongType { expected, found } => write!(f, "expected {expected}, found {found}"),
124            Self::OutOfRange { expected } => write!(f, "number out of range for {expected}"),
125            Self::StringNotBorrowable => {
126                f.write_str("a string with escapes cannot be borrowed as `&str`")
127            }
128            Self::WrongLength { expected, found } => {
129                write!(f, "expected {expected} items, found {found}")
130            }
131            Self::MissingField(name) => write!(f, "missing field `{name}`"),
132            Self::UnknownField => f.write_str("unknown field"),
133            Self::DuplicateField => f.write_str("duplicate field"),
134            Self::InvalidValue(expected) => write!(f, "invalid value: expected {expected}"),
135            Self::Custom(message) => f.write_str(message),
136        }
137    }
138}
139
140#[derive(Clone, Debug, PartialEq, Eq)]
141struct Inner {
142    kind: DecodeErrorKind,
143    offset: usize,
144    /// Outermost first.
145    path: Vec<PathSegment>,
146}
147
148/// Why a typed value could not be read: what went wrong, at which byte, and
149/// where in the document.
150///
151/// The path is built as the error travels out through the containers it
152/// was found in, so it costs nothing until something fails.
153/// [`pointer`](Self::pointer) gives it as an RFC 6901 JSON Pointer, which is
154/// what [`Display`](fmt::Display) shows after the offset:
155/// `expected u32, found string at byte 31 (at /position/line)`. That is a
156/// ready-made message for a JSON-RPC `-32602 Invalid params` reply.
157///
158/// The error is one pointer wide, so `Result<T, DecodeError>` stays small.
159///
160/// # Examples
161///
162/// ```
163/// use jsonx_lib::{DecodeErrorKind, Kind, PathSegment};
164///
165/// let err = jsonx_lib::from_str::<Vec<Vec<u8>>>("[[1], [2, true]]").unwrap_err();
166/// assert_eq!(err.kind(), &DecodeErrorKind::WrongType { expected: "u8", found: Kind::Bool });
167/// assert_eq!(err.offset(), 10);
168/// assert_eq!(err.path(), [PathSegment::Index(1), PathSegment::Index(1)]);
169/// assert_eq!(err.pointer(), "/1/1");
170/// assert_eq!(err.to_string(), "expected u8, found boolean at byte 10 (at /1/1)");
171/// ```
172#[derive(Clone, Debug, PartialEq, Eq)]
173#[must_use]
174pub struct DecodeError(Box<Inner>);
175
176impl DecodeError {
177    /// An error of `kind` at byte `offset`, with an empty path.
178    ///
179    /// # Examples
180    ///
181    /// ```
182    /// use jsonx_lib::{DecodeError, DecodeErrorKind};
183    ///
184    /// let err = DecodeError::new(DecodeErrorKind::InvalidValue("a port"), 12);
185    /// assert_eq!(err.to_string(), "invalid value: expected a port at byte 12");
186    /// ```
187    #[cold]
188    pub fn new(kind: DecodeErrorKind, offset: usize) -> Self {
189        Self(Box::new(Inner {
190            kind,
191            offset,
192            path: Vec::new(),
193        }))
194    }
195
196    /// A [`DecodeErrorKind::WrongType`] error.
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// use jsonx_lib::{DecodeError, Kind};
202    ///
203    /// let err = DecodeError::wrong_type("a position", Kind::Array, 4);
204    /// assert_eq!(err.to_string(), "expected a position, found array at byte 4");
205    /// ```
206    #[cold]
207    pub fn wrong_type(expected: &'static str, found: Kind, offset: usize) -> Self {
208        Self::new(DecodeErrorKind::WrongType { expected, found }, offset)
209    }
210
211    /// A [`DecodeErrorKind::InvalidValue`] error.
212    ///
213    /// # Examples
214    ///
215    /// ```
216    /// let err = jsonx_lib::DecodeError::invalid_value("a URI", 0);
217    /// assert_eq!(err.to_string(), "invalid value: expected a URI at byte 0");
218    /// ```
219    #[cold]
220    pub fn invalid_value(expected: &'static str, offset: usize) -> Self {
221        Self::new(DecodeErrorKind::InvalidValue(expected), offset)
222    }
223
224    /// A [`DecodeErrorKind::Custom`] error with `message`.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// let err = jsonx_lib::DecodeError::custom("end before start", 9);
230    /// assert_eq!(err.to_string(), "end before start at byte 9");
231    /// ```
232    pub fn custom(message: impl Into<Cow<'static, str>>, offset: usize) -> Self {
233        Self::new(DecodeErrorKind::Custom(message.into()), offset)
234    }
235
236    /// A [`DecodeErrorKind::MissingField`] error.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// let err = jsonx_lib::DecodeError::missing_field("uri", 0);
242    /// assert_eq!(err.to_string(), "missing field `uri` at byte 0");
243    /// ```
244    #[cold]
245    pub fn missing_field(name: &'static str, offset: usize) -> Self {
246        Self::new(DecodeErrorKind::MissingField(name), offset)
247    }
248
249    /// The error as seen from the object that holds it under `key`: the key
250    /// goes in front of the path. The object readers do this for you.
251    ///
252    /// # Examples
253    ///
254    /// ```
255    /// let err = jsonx_lib::DecodeError::invalid_value("a URI", 7).at_key("uri").at_key("textDocument");
256    /// assert_eq!(err.pointer(), "/textDocument/uri");
257    /// ```
258    #[cold]
259    pub fn at_key(mut self, key: impl Into<String>) -> Self {
260        self.0.path.insert(0, PathSegment::Key(key.into()));
261        self
262    }
263
264    /// The error as seen from the array that holds it at `index`.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// let err = jsonx_lib::DecodeError::invalid_value("a URI", 7).at_index(2);
270    /// assert_eq!(err.pointer(), "/2");
271    /// ```
272    #[cold]
273    pub fn at_index(mut self, index: usize) -> Self {
274        self.0.path.insert(0, PathSegment::Index(index));
275        self
276    }
277
278    /// What went wrong.
279    #[must_use]
280    pub fn kind(&self) -> &DecodeErrorKind {
281        &self.0.kind
282    }
283
284    /// The byte offset in the input where it went wrong: the value that did
285    /// not fit, or for a syntax error the byte a parse reports.
286    #[must_use]
287    pub fn offset(&self) -> usize {
288        self.0.offset
289    }
290
291    /// Where in the document, outermost first; empty for the top-level
292    /// value.
293    #[must_use]
294    pub fn path(&self) -> &[PathSegment] {
295        &self.0.path
296    }
297
298    /// The path as an [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)
299    /// JSON Pointer (`/params/items/3`, `""` for the top level), usable with
300    /// [`Value::pointer`].
301    ///
302    /// # Examples
303    ///
304    /// ```
305    /// let err = jsonx_lib::DecodeError::invalid_value("x", 0).at_key("a/b").at_key("~");
306    /// assert_eq!(err.pointer(), "/~0/a~1b");
307    /// ```
308    #[must_use]
309    pub fn pointer(&self) -> String {
310        let mut out = String::new();
311        for segment in &self.0.path {
312            out.push('/');
313            match segment {
314                PathSegment::Key(key) => {
315                    for ch in key.chars() {
316                        match ch {
317                            '~' => out.push_str("~0"),
318                            '/' => out.push_str("~1"),
319                            _ => out.push(ch),
320                        }
321                    }
322                }
323                PathSegment::Index(index) => out.push_str(&format!("{index}")),
324            }
325        }
326        out
327    }
328
329    /// The error's line and column in `input`, from 1, the column in
330    /// characters; see [`Error::line_col`].
331    ///
332    /// # Examples
333    ///
334    /// ```
335    /// let text = "{\n  \"n\": \"seven\"\n}";
336    /// let err = jsonx_lib::from_str::<std::collections::BTreeMap<String, u8>>(text).unwrap_err();
337    /// assert_eq!(err.line_col(text), (2, 8));
338    /// ```
339    #[must_use]
340    pub fn line_col(&self, input: impl AsRef<[u8]>) -> (usize, usize) {
341        let at = crate::error::locate(input.as_ref(), self.0.offset);
342        (at.line + 1, at.chars + 1)
343    }
344
345    /// The error's position in `input` as LSP counts it (from 0, the
346    /// character in UTF-16 units); see [`Error::utf16_position`].
347    ///
348    /// # Examples
349    ///
350    /// ```
351    /// let text = "[1,\n \"x\"]";
352    /// let err = jsonx_lib::from_str::<Vec<u8>>(text).unwrap_err();
353    /// assert_eq!(err.utf16_position(text), (1, 1));
354    /// ```
355    #[must_use]
356    pub fn utf16_position(&self, input: impl AsRef<[u8]>) -> (usize, usize) {
357        let at = crate::error::locate(input.as_ref(), self.0.offset);
358        (at.line, at.utf16)
359    }
360
361    /// The parse error, for a [`DecodeErrorKind::Syntax`] error.
362    ///
363    /// # Examples
364    ///
365    /// ```
366    /// use jsonx_lib::ErrorKind;
367    ///
368    /// let err = jsonx_lib::from_str::<Vec<u8>>("[1,]").unwrap_err();
369    /// assert_eq!(err.syntax_error().map(|e| e.kind()), Some(ErrorKind::TrailingComma));
370    /// ```
371    #[must_use]
372    pub fn syntax_error(&self) -> Option<Error> {
373        match self.0.kind {
374            DecodeErrorKind::Syntax(kind) => Some(Error::new(kind, self.0.offset)),
375            _ => None,
376        }
377    }
378
379    /// The same error `by` bytes further into a larger input.
380    pub(crate) fn shifted(mut self, by: usize) -> Self {
381        self.0.offset += by;
382        self
383    }
384}
385
386impl From<Error> for DecodeError {
387    #[cold]
388    fn from(e: Error) -> Self {
389        Self::new(DecodeErrorKind::Syntax(e.kind()), e.offset())
390    }
391}
392
393impl fmt::Display for DecodeError {
394    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395        write!(f, "{} at byte {}", self.0.kind, self.0.offset)?;
396        if !self.0.path.is_empty() {
397            write!(f, " (at {})", self.pointer())?;
398        }
399        Ok(())
400    }
401}
402
403impl core::error::Error for DecodeError {}
404
405// ---- The traits --------------------------------------------------------------
406
407/// A type that reads itself from JSON, straight from a [`Reader`].
408///
409/// The explicit, hand-written counterpart of [`ToJson`]: no derive and no
410/// reflection, so an implementation says in code which members a type has
411/// and how each is read. Nothing is built in between, and the lifetime
412/// `'de` is the input's, so a type can borrow from it: a `&'de str` or
413/// `Cow<'de, str>` field points into the text when the string had no
414/// escapes.
415///
416/// # Implementing it
417///
418/// `from_json` is called with the reader positioned where a value comes
419/// next, and must read exactly that one value. Read a scalar with
420/// [`reader.decode()`](Reader::decode); an object with
421/// [`read_object`](Reader::read_object), which hands out its members; an
422/// array with [`read_array`](Reader::read_array). For a struct:
423///
424/// ```
425/// use std::borrow::Cow;
426/// use jsonx_lib::{DecodeError, FromJson, Reader};
427///
428/// struct Position { line: u32, character: u32 }
429///
430/// impl<'de> FromJson<'de> for Position {
431///     fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
432///         let (mut line, mut character) = (None, None);
433///         let mut object = reader.read_object()?;
434///         while let Some(key) = object.next_key()? {
435///             match &*key {
436///                 "line" => object.field(&mut line)?,
437///                 "character" => object.field(&mut character)?,
438///                 _ => {} // unknown members are skipped (and still validated)
439///             }
440///         }
441///         Ok(Position {
442///             line: object.required(line, "line")?,
443///             character: object.required(character, "character")?,
444///         })
445///     }
446/// }
447///
448/// struct Location<'a> { uri: Cow<'a, str>, position: Position, label: Option<String> }
449///
450/// impl<'de> FromJson<'de> for Location<'de> {
451///     fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
452///         let (mut uri, mut position, mut label) = (None, None, None);
453///         let mut object = reader.read_object()?;
454///         while let Some(key) = object.next_key()? {
455///             match &*key {
456///                 "uri" => object.field(&mut uri)?,
457///                 "position" => object.field(&mut position)?,
458///                 "label" => object.field(&mut label)?,
459///                 _ => {}
460///             }
461///         }
462///         Ok(Location {
463///             uri: object.required(uri, "uri")?,
464///             position: object.required(position, "position")?,
465///             label: object.required(label, "label")?, // absent reads as None
466///         })
467///     }
468/// }
469///
470/// let text = r#"{"uri": "file:///a.rs", "position": {"line": 3, "character": 14}}"#;
471/// let loc: Location = jsonx_lib::from_str(text)?;
472/// assert!(matches!(loc.uri, Cow::Borrowed("file:///a.rs"))); // no copy
473/// assert_eq!((loc.position.line, loc.position.character), (3, 14));
474/// assert_eq!(loc.label, None);
475///
476/// let err = jsonx_lib::from_str::<Location>(r#"{"uri": "x", "position": {"line": "3"}}"#).err();
477/// assert_eq!(
478///     err.map(|e| e.to_string()).as_deref(),
479///     Some("expected u32, found string at byte 34 (at /position/line)")
480/// );
481/// # Ok::<(), DecodeError>(())
482/// ```
483///
484/// What the object reader does for you:
485///
486/// - **Duplicates are refused.** [`field`](ObjectReader::field) refuses a
487///   second value for a field it already has
488///   ([`DecodeErrorKind::DuplicateField`]), and under the default
489///   [`DuplicateKeys::Error`] the reader refuses any repeated key, known or
490///   not, when the object closes. A second value can never be smuggled
491///   past the first.
492/// - **Unknown members are skipped**, after being validated, which is what
493///   LSP and MCP ask of receivers. To refuse them, return
494///   [`unknown_field`](ObjectReader::unknown_field) for the keys you do not
495///   know.
496/// - **Absent members:** [`required`](ObjectReader::required) turns a field
497///   never seen into [`DecodeErrorKind::MissingField`], except for a type
498///   whose [`absent`](Self::absent) gives a value: `Option<T>` (`None`) and
499///   [`Nullable<T>`] (`Absent`).
500/// - **Paths:** an error inside a member's value gets the member's key in
501///   its path; an error inside an array item gets the index.
502///
503/// An enum whose variants have different shapes looks before it reads,
504/// with [`peek_kind`](Reader::peek_kind):
505///
506/// ```
507/// use jsonx_lib::{DecodeError, FromJson, Kind, Reader};
508///
509/// enum Id { Number(i64), Text(String) }
510///
511/// impl<'de> FromJson<'de> for Id {
512///     fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
513///         match reader.peek_kind()? {
514///             Some(Kind::Number) => Ok(Id::Number(reader.decode()?)),
515///             Some(Kind::String) => Ok(Id::Text(reader.decode()?)),
516///             Some(found) => Err(DecodeError::wrong_type("a number or a string", found, reader.offset())),
517///             None => Err(reader.decode::<()>().unwrap_err()), // let the reader say what is wrong
518///         }
519///     }
520/// }
521///
522/// assert!(matches!(jsonx_lib::from_str::<Id>("7")?, Id::Number(7)));
523/// assert!(matches!(jsonx_lib::from_str::<Id>("\"a\"")?, Id::Text(s) if s == "a"));
524/// assert!(jsonx_lib::from_str::<Id>("true").is_err());
525/// # Ok::<(), DecodeError>(())
526/// ```
527///
528/// # Depth
529///
530/// A type that nests as deep as its data (a tree of its own nodes) recurses
531/// once per level. The reader's [`Limits::max_depth`] (128 by default)
532/// refuses anything deeper before `from_json` is called for it, so the
533/// recursion is bounded by the budget, not by the input.
534///
535/// # Provided implementations
536///
537/// `bool`; every integer type (from integer text in range); `f32`, `f64`
538/// (any finite number); `String`, `Box<str>`, `Cow<'de, str>`, `&'de str`
539/// (only for strings without escapes), `char` (a one-character string);
540/// `()` (`null`); `Option<T>` (`null` or absent is `None`), [`Nullable<T>`];
541/// `Box<T>`, `Rc<T>`, `Arc<T>`; `Vec<T>`, `VecDeque<T>`, `Box<[T]>`,
542/// `[T; N]`, `BTreeSet<T>` and with `std` `HashSet<T, S>` (arrays; a set
543/// keeps one of equal items); tuples of up to eight (arrays of that
544/// length); `BTreeMap<K, V>` and with `std` `HashMap<K, V, S>` (objects,
545/// keys through [`FromJsonKey`], duplicates per the reader's
546/// [`DuplicateKeys`] policy); and this crate's [`Value`], [`Number`],
547/// [`Array`], [`Object`], and [`RawValue`](crate::RawValue).
548pub trait FromJson<'de>: Sized {
549    /// Reads one value from `reader`, which is positioned where a value
550    /// comes next.
551    ///
552    /// # Errors
553    ///
554    /// A [`DecodeError`] for a value that is not of this type's shape, or
555    /// any error of the reader.
556    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError>;
557
558    /// The value for an object member that is absent, if absence is
559    /// allowed: `None` (absence is an error) by default, `Some(None)` for
560    /// `Option<T>`, and `Some(Nullable::Absent)` for [`Nullable<T>`].
561    ///
562    /// # Examples
563    ///
564    /// ```
565    /// use jsonx_lib::FromJson;
566    ///
567    /// assert_eq!(<Option<u8> as FromJson>::absent(), Some(None));
568    /// assert_eq!(<u8 as FromJson>::absent(), None);
569    /// ```
570    #[inline]
571    fn absent() -> Option<Self> {
572        None
573    }
574}
575
576/// A type usable as a JSON object key, for [`FromJson`] on maps.
577///
578/// # Examples
579///
580/// ```
581/// use std::{borrow::Cow, collections::BTreeMap};
582/// use jsonx_lib::{DecodeErrorKind, FromJsonKey};
583///
584/// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
585/// struct Lang(String);
586///
587/// impl<'de> FromJsonKey<'de> for Lang {
588///     fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind> {
589///         if key.len() == 2 { Ok(Lang(key.into_owned())) } else { Err(DecodeErrorKind::InvalidValue("a language code")) }
590///     }
591/// }
592///
593/// let names: BTreeMap<Lang, String> = jsonx_lib::from_str(r#"{"en": "hello"}"#)?;
594/// assert_eq!(names[&Lang("en".into())], "hello");
595/// let err = jsonx_lib::from_str::<BTreeMap<Lang, String>>(r#"{"eng": "x"}"#).unwrap_err();
596/// assert_eq!(err.pointer(), "/eng");
597/// # Ok::<(), jsonx_lib::DecodeError>(())
598/// ```
599pub trait FromJsonKey<'de>: Sized {
600    /// Makes the key from its decoded text.
601    ///
602    /// # Errors
603    ///
604    /// The reason the text is not a valid key; the map reports it at the
605    /// key, with the key in the path.
606    fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind>;
607}
608
609// ---- Reading through the reader ----------------------------------------------
610
611/// Reads one value as `T`, then completes any container `T` left open, so
612/// an implementation that stops early (returning once it has what it
613/// wants) cannot leave the reader in the middle of a value.
614pub(crate) fn decode_value<'de, T: FromJson<'de>>(
615    reader: &mut Reader<'de>,
616) -> Result<T, DecodeError> {
617    let depth = reader.depth();
618    let value = T::from_json(reader)?;
619    while reader.depth() > depth {
620        if reader.next_event()?.is_none() {
621            break;
622        }
623    }
624    Ok(value)
625}
626
627impl<'a> Reader<'a> {
628    /// Reads the next value as a `T` ([`FromJson`]).
629    ///
630    /// # Errors
631    ///
632    /// The [`DecodeError`] of `T`, or of the reader.
633    ///
634    /// # Examples
635    ///
636    /// ```
637    /// use jsonx_lib::{Event, Reader};
638    ///
639    /// let mut r = Reader::new(r#"{"id": 7, "tags": ["a", "b"]}"#);
640    /// r.next_event()?; // {
641    /// r.next_event()?; // "id"
642    /// assert_eq!(r.decode::<u64>()?, 7);
643    /// r.next_event()?; // "tags"
644    /// assert_eq!(r.decode::<Vec<&str>>()?, ["a", "b"]);
645    /// # Ok::<(), jsonx_lib::DecodeError>(())
646    /// ```
647    pub fn decode<T: FromJson<'a>>(&mut self) -> Result<T, DecodeError> {
648        self.begin_read();
649        let value = decode_value(self);
650        self.end_read();
651        value
652    }
653
654    /// Charges `bytes` of heap that a typed read is about to hold to the
655    /// current top-level read's
656    /// [`Limits::max_memory`](crate::Limits::max_memory) count.
657    #[inline]
658    fn hold(&mut self, bytes: usize) -> Result<(), DecodeError> {
659        let at = self.offset();
660        self.charge(bytes, at).map_err(DecodeError::from)
661    }
662
663    /// Starts reading an object whose members are read one by one through
664    /// the returned [`ObjectReader`]. Consumes the `{`.
665    ///
666    /// # Errors
667    ///
668    /// [`DecodeErrorKind::WrongType`] if the next value is not an object
669    /// (nothing is consumed), or an error of the reader.
670    ///
671    /// # Examples
672    ///
673    /// ```
674    /// let mut r = jsonx_lib::Reader::new(r#"{"a": 1, "b": [2]}"#);
675    /// let mut object = r.read_object()?;
676    /// let mut keys = Vec::new();
677    /// while let Some(key) = object.next_key()? {
678    ///     keys.push(key.into_owned()); // values not read are skipped
679    /// }
680    /// assert_eq!(keys, ["a", "b"]);
681    /// # Ok::<(), jsonx_lib::DecodeError>(())
682    /// ```
683    pub fn read_object(&mut self) -> Result<ObjectReader<'_, 'a>, DecodeError> {
684        let start = self.open(Kind::Object, "an object")?;
685        Ok(ObjectReader {
686            reader: self,
687            start,
688            key_offset: start,
689            pending: false,
690            done: false,
691        })
692    }
693
694    /// Starts reading an array whose items are read one by one through the
695    /// returned [`ArrayReader`]. Consumes the `[`.
696    ///
697    /// # Errors
698    ///
699    /// [`DecodeErrorKind::WrongType`] if the next value is not an array, or
700    /// an error of the reader.
701    ///
702    /// # Examples
703    ///
704    /// ```
705    /// let mut r = jsonx_lib::Reader::new("[1, 2, 3]");
706    /// let mut items = r.read_array()?;
707    /// let mut sum = 0u32;
708    /// while let Some(n) = items.next_item::<u32>()? {
709    ///     sum += n;
710    /// }
711    /// assert_eq!(sum, 6);
712    /// # Ok::<(), jsonx_lib::DecodeError>(())
713    /// ```
714    pub fn read_array(&mut self) -> Result<ArrayReader<'_, 'a>, DecodeError> {
715        let start = self.open(Kind::Array, "an array")?;
716        Ok(ArrayReader {
717            reader: self,
718            start,
719            index: 0,
720            done: false,
721        })
722    }
723
724    /// Reads the next value as a [`RawValue`](crate::RawValue): its exact
725    /// source text, validated by this read and not scanned again. As
726    /// [`read_raw`](Self::read_raw), `Ok(None)` when no value comes next.
727    ///
728    /// # Errors
729    ///
730    /// As [`read_raw`](Self::read_raw).
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// let mut r = jsonx_lib::Reader::new(r#"{"params": {"line": 3}}"#);
736    /// r.next_event()?;
737    /// r.next_event()?;
738    /// let params = r.read_raw_value()?.unwrap();
739    /// assert_eq!(params.as_str(), r#"{"line": 3}"#);
740    /// # Ok::<(), jsonx_lib::Error>(())
741    /// ```
742    pub fn read_raw_value(&mut self) -> Result<Option<crate::RawValue<'a>>, Error> {
743        Ok(self.read_raw()?.map(crate::RawValue::trusted))
744    }
745
746    /// Checks that the next value is of `kind` and consumes its first event;
747    /// returns its offset.
748    fn open(&mut self, kind: Kind, expected: &'static str) -> Result<usize, DecodeError> {
749        if self.enter(kind == Kind::Object)? {
750            return Ok(self.event_offset());
751        }
752        // Looked at before it is read: a value of another type is left
753        // unread.
754        match self.peek_kind()? {
755            Some(found) if found == kind => {}
756            Some(found) => return Err(DecodeError::wrong_type(expected, found, self.offset())),
757            None if !self.at_a_value()? => {
758                // A container ends, or the document did: there is no value.
759                return Err(DecodeError::new(
760                    DecodeErrorKind::Syntax(ErrorKind::ExpectedValue),
761                    self.offset(),
762                ));
763            }
764            // A byte that cannot start a value: the step below says why.
765            None => {}
766        }
767        match self.next_event()? {
768            Some(Event::StartObject | Event::StartArray) => Ok(self.event_offset()),
769            Some(other) => Err(DecodeError::wrong_type(
770                expected,
771                event_kind(&other),
772                self.event_offset(),
773            )),
774            None => Err(Error::new(ErrorKind::UnexpectedEnd, self.offset()).into()),
775        }
776    }
777
778    /// Reads a scalar value's event for a target described by `expected`:
779    /// one step of the reader. A container is the wrong type (its first
780    /// event is consumed, which does not matter: the read has failed); no
781    /// value at all is [`ErrorKind::ExpectedValue`] (or the reader's own
782    /// error, such as a trailing comma).
783    #[inline]
784    fn scalar(&mut self, expected: &'static str) -> Result<(Event<'a>, usize), DecodeError> {
785        match self.next_event() {
786            Ok(Some(
787                event @ (Event::String(_) | Event::Number(_) | Event::Bool(_) | Event::Null),
788            )) => Ok((event, self.event_offset())),
789            other => Err(self.not_a_scalar(other, expected)),
790        }
791    }
792
793    /// The error of a [`scalar`](Self::scalar) read that found no scalar.
794    #[cold]
795    #[inline(never)]
796    fn not_a_scalar(
797        &self,
798        read: Result<Option<Event<'a>>, Error>,
799        expected: &'static str,
800    ) -> DecodeError {
801        match read {
802            Err(e) => e.into(),
803            Ok(Some(event @ (Event::StartArray | Event::StartObject))) => {
804                DecodeError::wrong_type(expected, event_kind(&event), self.event_offset())
805            }
806            Ok(Some(_)) => DecodeError::new(
807                DecodeErrorKind::Syntax(ErrorKind::ExpectedValue),
808                self.event_offset(),
809            ),
810            Ok(None) => DecodeError::new(
811                DecodeErrorKind::Syntax(ErrorKind::ExpectedValue),
812                self.offset(),
813            ),
814        }
815    }
816}
817
818/// The kind of value an event starts.
819fn event_kind(event: &Event<'_>) -> Kind {
820    match event {
821        Event::StartObject | Event::EndObject | Event::Key(_) => Kind::Object,
822        Event::StartArray | Event::EndArray => Kind::Array,
823        Event::String(_) => Kind::String,
824        Event::Number(_) => Kind::Number,
825        Event::Bool(_) => Kind::Bool,
826        Event::Null => Kind::Null,
827    }
828}
829
830/// Reads the members of an object one by one; from
831/// [`Reader::read_object`].
832///
833/// Call [`next_key`](Self::next_key) until it returns `None`; after each
834/// key, read its value with [`field`](Self::field), [`value`](Self::value),
835/// [`value_with`](Self::value_with), [`raw`](Self::raw), or
836/// [`skip`](Self::skip), or do nothing and the next `next_key` skips it.
837/// Errors in a value get the member's key in their path. See [`FromJson`]
838/// for the whole pattern.
839pub struct ObjectReader<'r, 'de> {
840    reader: &'r mut Reader<'de>,
841    start: usize,
842    /// The current key's opening quote (its text is read again only for an
843    /// error's path).
844    key_offset: usize,
845    /// A key was read and its value not yet.
846    pending: bool,
847    done: bool,
848}
849
850impl<'de> ObjectReader<'_, 'de> {
851    /// The next member's key (borrowed from the input unless it had
852    /// escapes), or `None` after the last member, when the object's `}` has
853    /// been read. A value left unread is skipped first (and validated).
854    ///
855    /// # Errors
856    ///
857    /// Any error of the reader, including a repeated key under
858    /// [`DuplicateKeys::Error`] (reported when the object closes).
859    ///
860    /// # Examples
861    ///
862    /// ```
863    /// let mut r = jsonx_lib::Reader::new(r#"{"a": [1, 2], "b": 3}"#);
864    /// let mut o = r.read_object()?;
865    /// assert_eq!(o.next_key()?.as_deref(), Some("a"));
866    /// assert_eq!(o.next_key()?.as_deref(), Some("b")); // `[1, 2]` skipped
867    /// assert_eq!(o.value::<u8>()?, 3);
868    /// assert_eq!(o.next_key()?, None);
869    /// # Ok::<(), jsonx_lib::DecodeError>(())
870    /// ```
871    pub fn next_key(&mut self) -> Result<Option<Cow<'de, str>>, DecodeError> {
872        if self.done {
873            return Ok(None);
874        }
875        if self.pending {
876            self.skip()?;
877        }
878        match self.reader.next_event()? {
879            Some(Event::Key(key)) => {
880                self.key_offset = self.reader.event_offset();
881                self.pending = true;
882                Ok(Some(key))
883            }
884            Some(Event::EndObject) => {
885                self.done = true;
886                Ok(None)
887            }
888            _ => Err(DecodeError::new(
889                DecodeErrorKind::Syntax(ErrorKind::ExpectedKey),
890                self.reader.event_offset(),
891            )),
892        }
893    }
894
895    /// Reads the current member's value as a `T`.
896    ///
897    /// # Errors
898    ///
899    /// The [`DecodeError`] of `T`, with this member's key in its path.
900    ///
901    /// # Examples
902    ///
903    /// ```
904    /// let mut r = jsonx_lib::Reader::new(r#"{"n": "x"}"#);
905    /// let mut o = r.read_object()?;
906    /// o.next_key()?;
907    /// assert_eq!(o.value::<u8>().unwrap_err().pointer(), "/n");
908    /// # Ok::<(), jsonx_lib::DecodeError>(())
909    /// ```
910    #[inline]
911    pub fn value<T: FromJson<'de>>(&mut self) -> Result<T, DecodeError> {
912        self.value_with(T::from_json)
913    }
914
915    /// Reads the current member's value with `read`, for a value that needs
916    /// more than a type (a choice of shapes, a value read in place). Errors
917    /// get the key in their path.
918    ///
919    /// # Errors
920    ///
921    /// Whatever `read` returns, with this member's key in its path.
922    ///
923    /// # Examples
924    ///
925    /// ```
926    /// let mut r = jsonx_lib::Reader::new(r#"{"n": [1, 2, 3]}"#);
927    /// let mut o = r.read_object()?;
928    /// o.next_key()?;
929    /// let count = o.value_with(|r| {
930    ///     let mut items = r.read_array()?;
931    ///     let mut count = 0;
932    ///     while items.skip()? {
933    ///         count += 1;
934    ///     }
935    ///     Ok(count)
936    /// })?;
937    /// assert_eq!(count, 3);
938    /// # Ok::<(), jsonx_lib::DecodeError>(())
939    /// ```
940    pub fn value_with<T>(
941        &mut self,
942        read: impl FnOnce(&mut Reader<'de>) -> Result<T, DecodeError>,
943    ) -> Result<T, DecodeError> {
944        self.pending = false;
945        let depth = self.reader.depth();
946        let result = read(self.reader).and_then(|value| {
947            // Finish a container `read` left open.
948            while self.reader.depth() > depth {
949                if self.reader.next_event()?.is_none() {
950                    break;
951                }
952            }
953            Ok(value)
954        });
955        result.map_err(|e| self.in_member(e))
956    }
957
958    /// `e` with the current member's key in its path.
959    #[cold]
960    #[inline(never)]
961    fn in_member(&self, e: DecodeError) -> DecodeError {
962        e.at_key(self.reader.key_at(self.key_offset))
963    }
964
965    /// Reads the current member's value into `slot`, the pattern for a
966    /// struct field: refused as [`DecodeErrorKind::DuplicateField`] (at the
967    /// key) if `slot` already holds a value, so a second value for a field
968    /// cannot override the first. Under [`DuplicateKeys::First`] the second
969    /// value is skipped instead, under `Last` and `KeepAll` it replaces the
970    /// first.
971    ///
972    /// # Errors
973    ///
974    /// [`DecodeErrorKind::DuplicateField`], or the [`DecodeError`] of `T`,
975    /// with this member's key in the path.
976    ///
977    /// # Examples
978    ///
979    /// ```
980    /// use jsonx_lib::DecodeErrorKind;
981    ///
982    /// let mut r = jsonx_lib::Reader::new(r#"{"id": 1, "id": 2}"#);
983    /// let mut o = r.read_object()?;
984    /// let mut id: Option<u8> = None;
985    /// o.next_key()?;
986    /// o.field(&mut id)?;
987    /// o.next_key()?;
988    /// let err = o.field(&mut id).unwrap_err();
989    /// assert_eq!((err.kind(), err.offset(), err.pointer()), (&DecodeErrorKind::DuplicateField, 10, "/id".into()));
990    /// # Ok::<(), jsonx_lib::DecodeError>(())
991    /// ```
992    pub fn field<T: FromJson<'de>>(&mut self, slot: &mut Option<T>) -> Result<(), DecodeError> {
993        if slot.is_some() {
994            match self.reader.duplicate_policy() {
995                DuplicateKeys::First => return self.skip(),
996                DuplicateKeys::Last | DuplicateKeys::KeepAll => {}
997                _ => {
998                    let e = DecodeError::new(DecodeErrorKind::DuplicateField, self.key_offset);
999                    return Err(self.in_member(e));
1000                }
1001            }
1002        }
1003        *slot = Some(self.value()?);
1004        Ok(())
1005    }
1006
1007    /// Skips the current member's value, validating it.
1008    ///
1009    /// # Errors
1010    ///
1011    /// Any error of the reader inside the value.
1012    ///
1013    /// # Examples
1014    ///
1015    /// ```
1016    /// let mut r = jsonx_lib::Reader::new(r#"{"big": [[1], {}], "n": 1}"#);
1017    /// let mut o = r.read_object()?;
1018    /// o.next_key()?;
1019    /// o.skip()?;
1020    /// assert_eq!(o.next_key()?.as_deref(), Some("n"));
1021    /// # Ok::<(), jsonx_lib::DecodeError>(())
1022    /// ```
1023    pub fn skip(&mut self) -> Result<(), DecodeError> {
1024        self.raw().map(|_| ())
1025    }
1026
1027    /// The current member's value as its exact source text, validated.
1028    ///
1029    /// # Errors
1030    ///
1031    /// Any error of the reader inside the value.
1032    ///
1033    /// # Examples
1034    ///
1035    /// ```
1036    /// let mut r = jsonx_lib::Reader::new(r#"{"params": {"line": 3}}"#);
1037    /// let mut o = r.read_object()?;
1038    /// o.next_key()?;
1039    /// assert_eq!(o.raw()?, r#"{"line": 3}"#);
1040    /// # Ok::<(), jsonx_lib::DecodeError>(())
1041    /// ```
1042    pub fn raw(&mut self) -> Result<&'de str, DecodeError> {
1043        self.pending = false;
1044        match self.reader.read_raw() {
1045            Ok(Some(text)) => Ok(text),
1046            Ok(None) => {
1047                let e = DecodeError::new(
1048                    DecodeErrorKind::Syntax(ErrorKind::ExpectedValue),
1049                    self.reader.offset(),
1050                );
1051                Err(self.in_member(e))
1052            }
1053            Err(e) => Err(self.in_member(e.into())),
1054        }
1055    }
1056
1057    /// The error for the current member being one this type does not know:
1058    /// [`DecodeErrorKind::UnknownField`] at its key, with the key in the
1059    /// path. For a type that refuses unknown members.
1060    ///
1061    /// # Examples
1062    ///
1063    /// ```
1064    /// use jsonx_lib::{DecodeError, FromJson, Reader};
1065    ///
1066    /// struct Strict { a: u8 }
1067    ///
1068    /// impl<'de> FromJson<'de> for Strict {
1069    ///     fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1070    ///         let mut a = None;
1071    ///         let mut o = reader.read_object()?;
1072    ///         while let Some(key) = o.next_key()? {
1073    ///             match &*key {
1074    ///                 "a" => o.field(&mut a)?,
1075    ///                 _ => return Err(o.unknown_field()),
1076    ///             }
1077    ///         }
1078    ///         Ok(Strict { a: o.required(a, "a")? })
1079    ///     }
1080    /// }
1081    ///
1082    /// let err = jsonx_lib::from_str::<Strict>(r#"{"a": 1, "b": 2}"#).err();
1083    /// assert_eq!(err.map(|e| e.to_string()).as_deref(), Some("unknown field at byte 9 (at /b)"));
1084    /// ```
1085    pub fn unknown_field(&self) -> DecodeError {
1086        self.in_member(DecodeError::new(
1087            DecodeErrorKind::UnknownField,
1088            self.key_offset,
1089        ))
1090    }
1091
1092    /// The value of a field read with [`field`](Self::field): `slot`'s
1093    /// value, or if the field was absent `T`'s [`absent`](FromJson::absent)
1094    /// value (`None` for an `Option`), or else
1095    /// [`DecodeErrorKind::MissingField`] at the object's `{`.
1096    ///
1097    /// # Errors
1098    ///
1099    /// [`DecodeErrorKind::MissingField`].
1100    ///
1101    /// # Examples
1102    ///
1103    /// ```
1104    /// let mut r = jsonx_lib::Reader::new("{}");
1105    /// let mut o = r.read_object()?;
1106    /// assert_eq!(o.next_key()?, None);
1107    /// assert_eq!(o.required::<Option<u8>>(None, "maybe")?, None);
1108    /// assert_eq!(o.required::<u8>(None, "must").unwrap_err().to_string(), "missing field `must` at byte 0");
1109    /// # Ok::<(), jsonx_lib::DecodeError>(())
1110    /// ```
1111    pub fn required<T: FromJson<'de>>(
1112        &self,
1113        slot: Option<T>,
1114        name: &'static str,
1115    ) -> Result<T, DecodeError> {
1116        slot.or_else(T::absent)
1117            .ok_or_else(|| DecodeError::missing_field(name, self.start))
1118    }
1119
1120    /// The byte offset of the object's `{`.
1121    #[must_use]
1122    pub fn offset(&self) -> usize {
1123        self.start
1124    }
1125}
1126
1127/// Reads the items of an array one by one; from [`Reader::read_array`].
1128///
1129/// Errors in an item get its index in their path.
1130pub struct ArrayReader<'r, 'de> {
1131    reader: &'r mut Reader<'de>,
1132    start: usize,
1133    index: usize,
1134    done: bool,
1135}
1136
1137impl<'de> ArrayReader<'_, 'de> {
1138    /// Whether another item comes; consumes the `]` when not.
1139    #[inline(always)]
1140    fn more(&mut self) -> Result<bool, DecodeError> {
1141        if self.done {
1142            return Ok(false);
1143        }
1144        if self.reader.at_item()? {
1145            return Ok(true);
1146        }
1147        match self.reader.next_event()? {
1148            Some(Event::EndArray) => {
1149                self.done = true;
1150                Ok(false)
1151            }
1152            _ => Err(DecodeError::new(
1153                DecodeErrorKind::Syntax(ErrorKind::ExpectedCommaOrBracket),
1154                self.reader.event_offset(),
1155            )),
1156        }
1157    }
1158
1159    /// Reads the next item as a `T`, or `None` after the last one, when the
1160    /// array's `]` has been read.
1161    ///
1162    /// # Errors
1163    ///
1164    /// The [`DecodeError`] of `T`, with the item's index in its path.
1165    ///
1166    /// # Examples
1167    ///
1168    /// ```
1169    /// let mut r = jsonx_lib::Reader::new(r#"[1, "x"]"#);
1170    /// let mut items = r.read_array()?;
1171    /// assert_eq!(items.next_item::<u8>()?, Some(1));
1172    /// assert_eq!(items.next_item::<u8>().unwrap_err().pointer(), "/1");
1173    /// # Ok::<(), jsonx_lib::DecodeError>(())
1174    /// ```
1175    #[inline]
1176    pub fn next_item<T: FromJson<'de>>(&mut self) -> Result<Option<T>, DecodeError> {
1177        self.next_with(T::from_json)
1178    }
1179
1180    /// Reads the next item with `read`, or returns `None` after the last.
1181    ///
1182    /// # Errors
1183    ///
1184    /// Whatever `read` returns, with the item's index in its path.
1185    ///
1186    /// # Examples
1187    ///
1188    /// ```
1189    /// let mut r = jsonx_lib::Reader::new("[[1, 2], [3]]");
1190    /// let mut rows = r.read_array()?;
1191    /// let mut lengths = Vec::new();
1192    /// while let Some(n) = rows.next_with(|r| Ok(r.decode::<Vec<u8>>()?.len()))? {
1193    ///     lengths.push(n);
1194    /// }
1195    /// assert_eq!(lengths, [2, 1]);
1196    /// # Ok::<(), jsonx_lib::DecodeError>(())
1197    /// ```
1198    pub fn next_with<T>(
1199        &mut self,
1200        read: impl FnOnce(&mut Reader<'de>) -> Result<T, DecodeError>,
1201    ) -> Result<Option<T>, DecodeError> {
1202        if !self.more()? {
1203            return Ok(None);
1204        }
1205        let index = self.index;
1206        self.index += 1;
1207        let depth = self.reader.depth();
1208        let result = read(self.reader).and_then(|value| {
1209            while self.reader.depth() > depth {
1210                if self.reader.next_event()?.is_none() {
1211                    break;
1212                }
1213            }
1214            Ok(value)
1215        });
1216        result.map(Some).map_err(|e| e.at_index(index))
1217    }
1218
1219    /// Skips the next item, validating it; `false` after the last.
1220    ///
1221    /// # Errors
1222    ///
1223    /// Any error of the reader inside the item.
1224    ///
1225    /// # Examples
1226    ///
1227    /// ```
1228    /// let mut r = jsonx_lib::Reader::new("[{}, []]");
1229    /// let mut items = r.read_array()?;
1230    /// assert!(items.skip()? && items.skip()?);
1231    /// assert!(!items.skip()?);
1232    /// # Ok::<(), jsonx_lib::DecodeError>(())
1233    /// ```
1234    pub fn skip(&mut self) -> Result<bool, DecodeError> {
1235        let index = self.index;
1236        if !self.more()? {
1237            return Ok(false);
1238        }
1239        self.index += 1;
1240        match self.reader.read_raw() {
1241            Ok(_) => Ok(true),
1242            Err(e) => Err(DecodeError::from(e).at_index(index)),
1243        }
1244    }
1245
1246    /// Checks that no item is left: for a fixed-length array or a tuple,
1247    /// after its items were read.
1248    ///
1249    /// # Errors
1250    ///
1251    /// [`DecodeErrorKind::WrongLength`] at the `[` if items remain (all of
1252    /// them are skipped and counted), or an error of the reader.
1253    ///
1254    /// # Examples
1255    ///
1256    /// ```
1257    /// use jsonx_lib::DecodeErrorKind;
1258    ///
1259    /// let mut r = jsonx_lib::Reader::new("[1, 2, 3]");
1260    /// let mut items = r.read_array()?;
1261    /// items.next_item::<u8>()?;
1262    /// let err = items.end().unwrap_err();
1263    /// assert_eq!(err.kind(), &DecodeErrorKind::WrongLength { expected: 1, found: 3 });
1264    /// # Ok::<(), jsonx_lib::DecodeError>(())
1265    /// ```
1266    pub fn end(mut self) -> Result<(), DecodeError> {
1267        let expected = self.index;
1268        if !self.more()? {
1269            return Ok(());
1270        }
1271        while self.skip()? {}
1272        Err(DecodeError::new(
1273            DecodeErrorKind::WrongLength {
1274                expected,
1275                found: self.index,
1276            },
1277            self.start,
1278        ))
1279    }
1280
1281    /// How many items have been read or skipped.
1282    #[must_use]
1283    pub fn index(&self) -> usize {
1284        self.index
1285    }
1286
1287    /// The byte offset of the array's `[`.
1288    #[must_use]
1289    pub fn offset(&self) -> usize {
1290        self.start
1291    }
1292}
1293
1294// ---- Entry points ------------------------------------------------------------
1295
1296/// Reads `text` as one `T` ([`FromJson`]), with the default [`Limits`] and
1297/// duplicate keys refused. The whole text must be that one value.
1298///
1299/// # Errors
1300///
1301/// The [`DecodeError`] of `T`, or the parse error of the text (including
1302/// the rest of the document after the value).
1303///
1304/// # Examples
1305///
1306/// ```
1307/// use std::collections::BTreeMap;
1308///
1309/// let scores: BTreeMap<String, Vec<u32>> = jsonx_lib::from_str(r#"{"ada": [3, 5]}"#)?;
1310/// assert_eq!(scores["ada"], [3, 5]);
1311///
1312/// let err = jsonx_lib::from_str::<u8>("300").unwrap_err();
1313/// assert_eq!(err.to_string(), "number out of range for u8 at byte 0");
1314/// # Ok::<(), jsonx_lib::DecodeError>(())
1315/// ```
1316pub fn from_str<'de, T: FromJson<'de>>(text: &'de str) -> Result<T, DecodeError> {
1317    Parser::new().decode(text)
1318}
1319
1320/// Reads `bytes`, which must be UTF-8, as one `T`; see [`from_str`].
1321///
1322/// # Errors
1323///
1324/// As [`from_str`], plus [`ErrorKind::InvalidUtf8`] and
1325/// [`ErrorKind::InputTooLarge`] as for [`parse_bytes`](crate::parse_bytes).
1326///
1327/// # Examples
1328///
1329/// ```
1330/// let pair: (bool, u8) = jsonx_lib::from_bytes(b"[true, 2]")?;
1331/// assert_eq!(pair, (true, 2));
1332/// # Ok::<(), jsonx_lib::DecodeError>(())
1333/// ```
1334pub fn from_bytes<'de, T: FromJson<'de>>(bytes: &'de [u8]) -> Result<T, DecodeError> {
1335    Parser::new().decode_bytes(bytes)
1336}
1337
1338/// Reads an already built [`Value`] as a `T`, for a type that owns its data.
1339///
1340/// The value is written as compact text and read back, so this costs a write
1341/// and a scan; byte offsets in an error point into that text (the path is
1342/// the useful part). The default [`Limits`] apply, which bounds the
1343/// recursion of a deeply nested type.
1344///
1345/// # Errors
1346///
1347/// The [`DecodeError`] of `T`.
1348///
1349/// # Examples
1350///
1351/// ```
1352/// let v = jsonx_lib::json!({ "list": [1, 2] });
1353/// let list: Vec<u8> = jsonx_lib::from_value(&v["list"])?;
1354/// assert_eq!(list, [1, 2]);
1355/// # Ok::<(), jsonx_lib::DecodeError>(())
1356/// ```
1357pub fn from_value<T: for<'de> FromJson<'de>>(value: &Value<'_>) -> Result<T, DecodeError> {
1358    let text = crate::to_string(value);
1359    from_str(&text)
1360}
1361
1362/// Builds a [`Value`] from any [`ToJson`] type, by writing it and reading it
1363/// back (members exactly as written, duplicates included).
1364///
1365/// # Examples
1366///
1367/// ```
1368/// let v = jsonx_lib::to_value(&(1, "two", [true]));
1369/// assert_eq!(v[2][0], true);
1370/// ```
1371#[must_use]
1372pub fn to_value<T: ToJson + ?Sized>(value: &T) -> Value<'static> {
1373    let text = crate::to_string(value);
1374    Parser::new()
1375        .limits(Limits::unlimited())
1376        .duplicate_keys(DuplicateKeys::KeepAll)
1377        .parse(&text)
1378        .map(Value::into_owned)
1379        .unwrap_or_default()
1380}
1381
1382impl Parser {
1383    /// Reads `text` as one `T` with this parser's budgets and duplicate-key
1384    /// policy; see [`from_str`].
1385    ///
1386    /// # Errors
1387    ///
1388    /// As [`from_str`].
1389    ///
1390    /// # Examples
1391    ///
1392    /// ```
1393    /// use jsonx_lib::{ErrorKind, Limits, Parser};
1394    ///
1395    /// let shallow = Parser::new().limits(Limits::new().with_max_depth(1));
1396    /// assert_eq!(shallow.decode::<Vec<u8>>("[1]")?, [1]);
1397    /// let err = shallow.decode::<Vec<Vec<u8>>>("[[1]]").unwrap_err();
1398    /// assert_eq!(err.syntax_error().map(|e| e.kind()), Some(ErrorKind::DepthLimitExceeded));
1399    /// # Ok::<(), jsonx_lib::DecodeError>(())
1400    /// ```
1401    pub fn decode<'de, T: FromJson<'de>>(&self, text: &'de str) -> Result<T, DecodeError> {
1402        let mut reader = self.reader(text);
1403        let value = reader.decode()?;
1404        reader.read_to_end()?;
1405        Ok(value)
1406    }
1407
1408    /// Reads `bytes`, which must be UTF-8, as one `T`; see
1409    /// [`decode`](Self::decode).
1410    ///
1411    /// # Errors
1412    ///
1413    /// As [`from_bytes`].
1414    ///
1415    /// # Examples
1416    ///
1417    /// ```
1418    /// assert_eq!(jsonx_lib::Parser::new().decode_bytes::<&str>(b"\"x\"")?, "x");
1419    /// # Ok::<(), jsonx_lib::DecodeError>(())
1420    /// ```
1421    pub fn decode_bytes<'de, T: FromJson<'de>>(&self, bytes: &'de [u8]) -> Result<T, DecodeError> {
1422        let mut reader = self.reader_bytes(bytes)?;
1423        let value = reader.decode()?;
1424        reader.read_to_end()?;
1425        Ok(value)
1426    }
1427}
1428
1429// ---- Nullable ----------------------------------------------------------------
1430
1431/// A member that may be absent, `null`, or a value, keeping the three apart.
1432///
1433/// LSP and MCP use both TypeScript's optional `key?: T` and nullable
1434/// `key: T | null`, and sometimes `key?: T | null`, where "left out" and
1435/// "`null`" mean different things (`null` often clears a setting). An
1436/// `Option<T>` reads both as `None`; a `Nullable<T>` tells them apart, and
1437/// writes back what it read: [`ObjectWriter::optional`](crate::ObjectWriter::optional)
1438/// leaves out `Absent` and writes `Null` as `null`.
1439///
1440/// # Examples
1441///
1442/// ```
1443/// use jsonx_lib::{DecodeError, FromJson, Nullable, Reader, ToJson, ValueWriter, Written};
1444///
1445/// struct Settings { tab_size: Nullable<u8> }
1446///
1447/// impl<'de> FromJson<'de> for Settings {
1448///     fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1449///         let mut tab_size = None;
1450///         let mut o = reader.read_object()?;
1451///         while let Some(key) = o.next_key()? {
1452///             if key == "tabSize" { o.field(&mut tab_size)?; }
1453///         }
1454///         Ok(Settings { tab_size: o.required(tab_size, "tabSize")? })
1455///     }
1456/// }
1457///
1458/// impl ToJson for Settings {
1459///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
1460///         out.object(|o| o.optional("tabSize", &self.tab_size))
1461///     }
1462/// }
1463///
1464/// for text in ["{}", r#"{"tabSize":null}"#, r#"{"tabSize":4}"#] {
1465///     let s: Settings = jsonx_lib::from_str(text)?;
1466///     assert_eq!(jsonx_lib::to_string(&s), text);
1467/// }
1468/// # Ok::<(), DecodeError>(())
1469/// ```
1470#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
1471pub enum Nullable<T> {
1472    /// The member is not there.
1473    #[default]
1474    Absent,
1475    /// The member is there, and `null`.
1476    Null,
1477    /// The member is there, with a value.
1478    Value(T),
1479}
1480
1481impl<T> Nullable<T> {
1482    /// The value, if there is one: `Absent` and `Null` are both `None`.
1483    ///
1484    /// # Examples
1485    ///
1486    /// ```
1487    /// use jsonx_lib::Nullable;
1488    ///
1489    /// assert_eq!(Nullable::Value(3).into_option(), Some(3));
1490    /// assert_eq!(Nullable::<u8>::Null.into_option(), None);
1491    /// ```
1492    #[inline]
1493    pub fn into_option(self) -> Option<T> {
1494        match self {
1495            Self::Value(value) => Some(value),
1496            Self::Absent | Self::Null => None,
1497        }
1498    }
1499
1500    /// A reference to the value, if there is one.
1501    ///
1502    /// # Examples
1503    ///
1504    /// ```
1505    /// assert_eq!(jsonx_lib::Nullable::Value(3).as_ref(), jsonx_lib::Nullable::Value(&3));
1506    /// ```
1507    #[inline]
1508    pub const fn as_ref(&self) -> Nullable<&T> {
1509        match self {
1510            Self::Value(value) => Nullable::Value(value),
1511            Self::Null => Nullable::Null,
1512            Self::Absent => Nullable::Absent,
1513        }
1514    }
1515
1516    /// Whether the member is there with `null`.
1517    ///
1518    /// # Examples
1519    ///
1520    /// ```
1521    /// assert!(jsonx_lib::Nullable::<u8>::Null.is_null());
1522    /// ```
1523    #[inline]
1524    #[must_use]
1525    pub const fn is_null(&self) -> bool {
1526        matches!(self, Self::Null)
1527    }
1528}
1529
1530impl<'de, T: FromJson<'de>> FromJson<'de> for Nullable<T> {
1531    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1532        if reader.peek_kind()? == Some(Kind::Null) {
1533            let _null = reader.next_event()?;
1534            Ok(Self::Null)
1535        } else {
1536            decode_value(reader).map(Self::Value)
1537        }
1538    }
1539
1540    #[inline]
1541    fn absent() -> Option<Self> {
1542        Some(Self::Absent)
1543    }
1544}
1545
1546impl<T: ToJson> ToJson for Nullable<T> {
1547    fn to_json(&self, out: ValueWriter<'_>) -> Written {
1548        match self {
1549            Self::Value(value) => value.to_json(out),
1550            Self::Absent | Self::Null => out.null(),
1551        }
1552    }
1553
1554    #[inline]
1555    fn is_absent(&self) -> bool {
1556        matches!(self, Self::Absent)
1557    }
1558}
1559
1560// ---- Implementations ---------------------------------------------------------
1561
1562impl<'de> FromJson<'de> for bool {
1563    #[inline]
1564    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1565        match reader.scalar("a boolean")? {
1566            (Event::Bool(b), _) => Ok(b),
1567            (other, at) => Err(DecodeError::wrong_type("a boolean", event_kind(&other), at)),
1568        }
1569    }
1570}
1571
1572/// Reads a number value for the target type `name`.
1573#[inline]
1574fn number<'de>(
1575    reader: &mut Reader<'de>,
1576    name: &'static str,
1577) -> Result<(Number<'de>, usize), DecodeError> {
1578    match reader.scalar(name)? {
1579        (Event::Number(n), at) => Ok((n, at)),
1580        (other, at) => Err(DecodeError::wrong_type(name, event_kind(&other), at)),
1581    }
1582}
1583
1584/// An integer read whose text is not an integer in range: under
1585/// [`Numbers::WholeValues`], the value of any spelling of a whole number;
1586/// otherwise (or out of range) [`DecodeErrorKind::OutOfRange`].
1587#[cold]
1588#[inline(never)]
1589fn whole_value<T: TryFrom<i128>>(
1590    n: &Number<'_>,
1591    lenient: bool,
1592    at: usize,
1593    expected: &'static str,
1594) -> Result<T, DecodeError> {
1595    lenient
1596        .then(|| n.whole_value())
1597        .flatten()
1598        .and_then(|w| T::try_from(w).ok())
1599        .ok_or_else(|| DecodeError::new(DecodeErrorKind::OutOfRange { expected }, at))
1600}
1601
1602macro_rules! from_json_integer {
1603    ($($t:ty => $via:ident),* $(,)?) => {$(
1604        impl<'de> FromJson<'de> for $t {
1605            #[inline]
1606            fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1607                let lenient = reader.number_policy() == Numbers::WholeValues;
1608                let (n, at) = number(reader, stringify!($t))?;
1609                match n.$via().and_then(|wide| <$t>::try_from(wide).ok()) {
1610                    Some(value) => Ok(value),
1611                    None => whole_value(&n, lenient, at, stringify!($t)),
1612                }
1613            }
1614        }
1615    )*};
1616}
1617
1618from_json_integer!(
1619    i8 => as_i64, i16 => as_i64, i32 => as_i64, i64 => as_i64, isize => as_i128, i128 => as_i128,
1620    u8 => as_u64, u16 => as_u64, u32 => as_u64, u64 => as_u64, usize => as_u128, u128 => as_u128,
1621);
1622
1623impl<'de> FromJson<'de> for f64 {
1624    #[inline]
1625    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1626        let (n, at) = number(reader, "f64")?;
1627        n.as_f64()
1628            .ok_or_else(|| DecodeError::new(DecodeErrorKind::OutOfRange { expected: "f64" }, at))
1629    }
1630}
1631
1632impl<'de> FromJson<'de> for f32 {
1633    #[inline]
1634    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1635        let (n, at) = number(reader, "f32")?;
1636        n.as_f32()
1637            .ok_or_else(|| DecodeError::new(DecodeErrorKind::OutOfRange { expected: "f32" }, at))
1638    }
1639}
1640
1641/// Reads a string value for the target type `name`.
1642#[inline]
1643fn string<'de>(
1644    reader: &mut Reader<'de>,
1645    name: &'static str,
1646) -> Result<(Cow<'de, str>, usize), DecodeError> {
1647    match reader.scalar(name)? {
1648        (Event::String(s), at) => Ok((s, at)),
1649        (other, at) => Err(DecodeError::wrong_type(name, event_kind(&other), at)),
1650    }
1651}
1652
1653impl<'de> FromJson<'de> for Cow<'de, str> {
1654    #[inline]
1655    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1656        let (s, _) = string(reader, "a string")?;
1657        if let Cow::Owned(decoded) = &s {
1658            reader.hold(decoded.capacity())?;
1659        }
1660        Ok(s)
1661    }
1662}
1663
1664impl<'de> FromJson<'de> for &'de str {
1665    #[inline]
1666    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1667        match string(reader, "a string")? {
1668            (Cow::Borrowed(s), _) => Ok(s),
1669            (Cow::Owned(_), at) => Err(DecodeError::new(DecodeErrorKind::StringNotBorrowable, at)),
1670        }
1671    }
1672}
1673
1674impl<'de> FromJson<'de> for String {
1675    #[inline]
1676    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1677        let (s, _) = string(reader, "a string")?;
1678        reader.hold(match &s {
1679            Cow::Owned(decoded) => decoded.capacity(),
1680            Cow::Borrowed(text) => text.len(),
1681        })?;
1682        Ok(s.into_owned())
1683    }
1684}
1685
1686impl<'de> FromJson<'de> for Box<str> {
1687    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1688        String::from_json(reader).map(String::into_boxed_str)
1689    }
1690}
1691
1692impl<'de> FromJson<'de> for char {
1693    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1694        let (s, at) = string(reader, "a character")?;
1695        let mut chars = s.chars();
1696        match (chars.next(), chars.next()) {
1697            (Some(c), None) => Ok(c),
1698            _ => Err(DecodeError::invalid_value("a single character", at)),
1699        }
1700    }
1701}
1702
1703impl<'de> FromJson<'de> for () {
1704    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1705        match reader.scalar("null")? {
1706            (Event::Null, _) => Ok(()),
1707            (other, at) => Err(DecodeError::wrong_type("null", event_kind(&other), at)),
1708        }
1709    }
1710}
1711
1712impl<'de, T: FromJson<'de>> FromJson<'de> for Option<T> {
1713    #[inline]
1714    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1715        if reader.peek_kind()? == Some(Kind::Null) {
1716            let _null = reader.next_event()?;
1717            Ok(None)
1718        } else {
1719            decode_value(reader).map(Some)
1720        }
1721    }
1722
1723    #[inline]
1724    fn absent() -> Option<Self> {
1725        Some(None)
1726    }
1727}
1728
1729impl<'de, T: FromJson<'de>> FromJson<'de> for Box<T> {
1730    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1731        let value = T::from_json(reader)?;
1732        reader.hold(size_of::<T>())?;
1733        Ok(Box::new(value))
1734    }
1735
1736    fn absent() -> Option<Self> {
1737        T::absent().map(Box::new)
1738    }
1739}
1740
1741impl<'de, T: FromJson<'de>> FromJson<'de> for Rc<T> {
1742    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1743        let value = T::from_json(reader)?;
1744        reader.hold(size_of::<T>() + 2 * size_of::<usize>())?;
1745        Ok(Rc::new(value))
1746    }
1747
1748    fn absent() -> Option<Self> {
1749        T::absent().map(Rc::new)
1750    }
1751}
1752
1753#[cfg(target_has_atomic = "ptr")]
1754impl<'de, T: FromJson<'de>> FromJson<'de> for Arc<T> {
1755    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1756        let value = T::from_json(reader)?;
1757        reader.hold(size_of::<T>() + 2 * size_of::<usize>())?;
1758        Ok(Arc::new(value))
1759    }
1760
1761    fn absent() -> Option<Self> {
1762        T::absent().map(Arc::new)
1763    }
1764}
1765
1766/// Reads every item of an array into `push`.
1767/// What a collection holds per item, for the memory budget.
1768#[derive(Clone, Copy)]
1769enum Cost {
1770    /// A vector of items of this size: its buffer, counted as it doubles.
1771    Buffer(usize),
1772    /// A tree or hash set: about this many bytes per item.
1773    PerItem(usize),
1774}
1775
1776/// The bytes a hash or tree collection holds per entry of `entry` bytes: an
1777/// estimate (a B-tree node's spare slots and links, a hash table's spare
1778/// capacity and control bytes), at about twice the entries themselves.
1779const fn per_entry(entry: usize) -> usize {
1780    2 * entry + size_of::<usize>()
1781}
1782
1783fn items<'de, T: FromJson<'de>>(
1784    reader: &mut Reader<'de>,
1785    expected: &'static str,
1786    cost: Cost,
1787    mut push: impl FnMut(T),
1788) -> Result<(), DecodeError> {
1789    let start = reader.open(Kind::Array, expected)?;
1790    let mut array = ArrayReader {
1791        reader,
1792        start,
1793        index: 0,
1794        done: false,
1795    };
1796    // The buffer a vector of `count` items has grown to (they double, from
1797    // four), so the charge is made before each growth, at its new size.
1798    let mut capacity = 0usize;
1799    while let Some(item) = array.next_item()? {
1800        let more = match cost {
1801            Cost::Buffer(size) if array.index > capacity => {
1802                let grown = capacity.saturating_mul(2).max(4);
1803                let bytes = (grown - capacity).saturating_mul(size);
1804                capacity = grown;
1805                bytes
1806            }
1807            Cost::Buffer(_) => 0,
1808            Cost::PerItem(bytes) => bytes,
1809        };
1810        array.reader.hold(more)?;
1811        push(item);
1812    }
1813    Ok(())
1814}
1815
1816impl<'de, T: FromJson<'de>> FromJson<'de> for Vec<T> {
1817    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1818        let mut out = Vec::new();
1819        items(reader, "an array", Cost::Buffer(size_of::<T>()), |item| {
1820            out.push(item)
1821        })?;
1822        Ok(out)
1823    }
1824}
1825
1826impl<'de, T: FromJson<'de>> FromJson<'de> for Box<[T]> {
1827    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1828        Vec::from_json(reader).map(Vec::into_boxed_slice)
1829    }
1830}
1831
1832impl<'de, T: FromJson<'de>> FromJson<'de> for VecDeque<T> {
1833    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1834        let mut out = VecDeque::new();
1835        items(reader, "an array", Cost::Buffer(size_of::<T>()), |item| {
1836            out.push_back(item);
1837        })?;
1838        Ok(out)
1839    }
1840}
1841
1842impl<'de, T: FromJson<'de> + Ord> FromJson<'de> for BTreeSet<T> {
1843    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1844        let mut out = BTreeSet::new();
1845        items(
1846            reader,
1847            "an array",
1848            Cost::PerItem(per_entry(size_of::<T>())),
1849            |item| {
1850                let _new = out.insert(item);
1851            },
1852        )?;
1853        Ok(out)
1854    }
1855}
1856
1857#[cfg(feature = "std")]
1858impl<'de, T, S> FromJson<'de> for std::collections::HashSet<T, S>
1859where
1860    T: FromJson<'de> + Eq + core::hash::Hash,
1861    S: core::hash::BuildHasher + Default,
1862{
1863    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1864        let mut out = Self::default();
1865        items(
1866            reader,
1867            "an array",
1868            Cost::PerItem(per_entry(size_of::<T>())),
1869            |item| {
1870                let _new = out.insert(item);
1871            },
1872        )?;
1873        Ok(out)
1874    }
1875}
1876
1877impl<'de, T: FromJson<'de>, const N: usize> FromJson<'de> for [T; N] {
1878    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1879        let mut array = reader.read_array()?;
1880        let mut out = Vec::with_capacity(N.min(1024));
1881        while out.len() < N {
1882            match array.next_item()? {
1883                Some(item) => out.push(item),
1884                None => {
1885                    return Err(DecodeError::new(
1886                        DecodeErrorKind::WrongLength {
1887                            expected: N,
1888                            found: out.len(),
1889                        },
1890                        array.offset(),
1891                    ));
1892                }
1893            }
1894        }
1895        array.end()?;
1896        out.try_into().map_err(|_unreachable: Vec<T>| {
1897            DecodeError::new(
1898                DecodeErrorKind::WrongLength {
1899                    expected: N,
1900                    found: N,
1901                },
1902                0,
1903            )
1904        })
1905    }
1906}
1907
1908macro_rules! from_json_tuple {
1909    ($(($len:literal: $($name:ident),+))*) => {$(
1910        impl<'de, $($name: FromJson<'de>),+> FromJson<'de> for ($($name,)+) {
1911            fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
1912                let mut array = reader.read_array()?;
1913                let tuple = ($(
1914                    match array.next_item::<$name>()? {
1915                        Some(item) => item,
1916                        None => {
1917                            return Err(DecodeError::new(
1918                                DecodeErrorKind::WrongLength { expected: $len, found: array.index() },
1919                                array.offset(),
1920                            ));
1921                        }
1922                    },
1923                )+);
1924                array.end()?;
1925                Ok(tuple)
1926            }
1927        }
1928    )*};
1929}
1930
1931from_json_tuple! {
1932    (1: A)
1933    (2: A, B)
1934    (3: A, B, C)
1935    (4: A, B, C, D)
1936    (5: A, B, C, D, E)
1937    (6: A, B, C, D, E, F)
1938    (7: A, B, C, D, E, F, G)
1939    (8: A, B, C, D, E, F, G, H)
1940}
1941
1942/// A map a JSON object can be read into.
1943trait Map<K, V> {
1944    fn has(&self, key: &K) -> bool;
1945    fn put(&mut self, key: K, value: V);
1946}
1947
1948impl<K: Ord, V> Map<K, V> for BTreeMap<K, V> {
1949    fn has(&self, key: &K) -> bool {
1950        self.contains_key(key)
1951    }
1952    fn put(&mut self, key: K, value: V) {
1953        let _old = self.insert(key, value);
1954    }
1955}
1956
1957#[cfg(feature = "std")]
1958impl<K: Eq + core::hash::Hash, V, S: core::hash::BuildHasher> Map<K, V>
1959    for std::collections::HashMap<K, V, S>
1960{
1961    fn has(&self, key: &K) -> bool {
1962        self.contains_key(key)
1963    }
1964    fn put(&mut self, key: K, value: V) {
1965        let _old = self.insert(key, value);
1966    }
1967}
1968
1969/// Reads every member of an object into `map`. A key that repeats one
1970/// already in the map (two spellings of one key, or two texts one
1971/// [`FromJsonKey`] makes equal) follows the reader's policy: refused under
1972/// `Error`, the later value skipped under `First`, kept under `Last` and
1973/// `KeepAll`.
1974fn members<'de, K: FromJsonKey<'de>, V: FromJson<'de>>(
1975    reader: &mut Reader<'de>,
1976    map: &mut impl Map<K, V>,
1977) -> Result<(), DecodeError> {
1978    let policy = reader.duplicate_policy();
1979    let mut object = reader.read_object()?;
1980    while let Some(text) = object.next_key()? {
1981        let key = K::from_json_key(text)
1982            .map_err(|kind| object.in_member(DecodeError::new(kind, object.key_offset)))?;
1983        if map.has(&key) {
1984            match policy {
1985                DuplicateKeys::First => {
1986                    object.skip()?;
1987                    continue;
1988                }
1989                DuplicateKeys::Last | DuplicateKeys::KeepAll => {}
1990                _ => {
1991                    let e = DecodeError::new(DecodeErrorKind::DuplicateField, object.key_offset);
1992                    return Err(object.in_member(e));
1993                }
1994            }
1995        }
1996        let value = object.value()?;
1997        object.reader.hold(per_entry(size_of::<(K, V)>()))?;
1998        map.put(key, value);
1999    }
2000    Ok(())
2001}
2002
2003impl<'de, K: FromJsonKey<'de> + Ord, V: FromJson<'de>> FromJson<'de> for BTreeMap<K, V> {
2004    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
2005        let mut out = BTreeMap::new();
2006        members(reader, &mut out)?;
2007        Ok(out)
2008    }
2009}
2010
2011#[cfg(feature = "std")]
2012impl<'de, K, V, S> FromJson<'de> for std::collections::HashMap<K, V, S>
2013where
2014    K: FromJsonKey<'de> + Eq + core::hash::Hash,
2015    V: FromJson<'de>,
2016    S: core::hash::BuildHasher + Default,
2017{
2018    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
2019        let mut out = Self::default();
2020        members(reader, &mut out)?;
2021        Ok(out)
2022    }
2023}
2024
2025impl<'de> FromJsonKey<'de> for String {
2026    #[inline]
2027    fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind> {
2028        Ok(key.into_owned())
2029    }
2030}
2031
2032impl<'de> FromJsonKey<'de> for Box<str> {
2033    #[inline]
2034    fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind> {
2035        Ok(key.into_owned().into_boxed_str())
2036    }
2037}
2038
2039impl<'de> FromJsonKey<'de> for Cow<'de, str> {
2040    #[inline]
2041    fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind> {
2042        Ok(key)
2043    }
2044}
2045
2046impl<'de> FromJsonKey<'de> for &'de str {
2047    #[inline]
2048    fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind> {
2049        match key {
2050            Cow::Borrowed(key) => Ok(key),
2051            Cow::Owned(_) => Err(DecodeErrorKind::StringNotBorrowable),
2052        }
2053    }
2054}
2055
2056impl<'de> FromJson<'de> for Value<'de> {
2057    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
2058        match reader.read_value()? {
2059            Some(value) => Ok(value),
2060            None => Err(DecodeError::new(
2061                DecodeErrorKind::Syntax(ErrorKind::ExpectedValue),
2062                reader.offset(),
2063            )),
2064        }
2065    }
2066}
2067
2068impl<'de> FromJson<'de> for Number<'de> {
2069    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
2070        number(reader, "a number").map(|(n, _)| n)
2071    }
2072}
2073
2074/// Reads a whole value of `kind` as a [`Value`].
2075fn tree<'de>(
2076    reader: &mut Reader<'de>,
2077    kind: Kind,
2078    expected: &'static str,
2079) -> Result<Value<'de>, DecodeError> {
2080    match reader.peek_kind()? {
2081        Some(found) if found != kind => {
2082            Err(DecodeError::wrong_type(expected, found, reader.offset()))
2083        }
2084        _ => Value::from_json(reader),
2085    }
2086}
2087
2088impl<'de> FromJson<'de> for Array<'de> {
2089    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
2090        match tree(reader, Kind::Array, "an array")? {
2091            Value::Array(array) => Ok(array),
2092            other => Err(DecodeError::wrong_type(
2093                "an array",
2094                other.kind(),
2095                reader.event_offset(),
2096            )),
2097        }
2098    }
2099}
2100
2101impl<'de> FromJson<'de> for Object<'de> {
2102    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
2103        match tree(reader, Kind::Object, "an object")? {
2104            Value::Object(object) => Ok(object),
2105            other => Err(DecodeError::wrong_type(
2106                "an object",
2107                other.kind(),
2108                reader.event_offset(),
2109            )),
2110        }
2111    }
2112}