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