jsonx_lib/lib.rs
1//! # jsonx_lib
2//!
3//! Strict RFC 8259 JSON: a parser that borrows from its input, pull and
4//! incremental readers, typed reading and writing through hand-written
5//! [`FromJson`] and [`ToJson`] impls, and deterministic writers, with
6//! budgets that refuse hostile input before it costs memory. No
7//! dependencies; `no_std` with `alloc`.
8//!
9//! ## Quick start
10//!
11//! ```
12//! use jsonx_lib::{json, json_struct, parse, to_string};
13//!
14//! // A document as a tree.
15//! let doc = parse(r#"{"name": "jsonx", "version": [0, 5, 0], "stable": false}"#)?;
16//! assert_eq!(doc["name"], "jsonx");
17//! assert_eq!(doc["version"][1].as_u64(), Some(5));
18//!
19//! // Or straight into your own types, and back, with no tree in between.
20//! struct Position { line: u32, character: u32 }
21//! json_struct!(Position { line, character });
22//!
23//! let p: Position = jsonx_lib::from_str(r#"{"line": 3, "character": 14}"#)?;
24//! assert_eq!((p.line, p.character), (3, 14));
25//! assert_eq!(to_string(&p), r#"{"line":3,"character":14}"#);
26//!
27//! let reply = json!({ "ok": true, "items": [1, 2, 3] });
28//! assert_eq!(to_string(&reply), r#"{"ok":true,"items":[1,2,3]}"#);
29//! # Ok::<(), Box<dyn std::error::Error>>(())
30//! ```
31//!
32//! ## The ways in
33//!
34//! 1. **[`parse`], [`from_str`], and [`to_string`]** (plus [`parse_bytes`],
35//! [`from_bytes`], [`to_string_pretty`], and [`to_string_with`]): one call
36//! each, default budgets, duplicate keys refused.
37//! 2. **[`Parser`]**: the same with your own [`Limits`], [`DuplicateKeys`]
38//! policy, and [`Numbers`] option, kept as a `const` and reused.
39//! 3. **[`Reader`]**: the document as a stream of [`Event`]s, with
40//! [`read_raw`](Reader::read_raw) to keep a value as its source text,
41//! [`read_value`](Reader::read_value) to build one part of it,
42//! [`decode`](Reader::decode) to read one part as a type, and
43//! [`find_pointer`](Reader::find_pointer) to go straight to one value.
44//! [`StreamReader`] is the same reader over input that arrives in chunks;
45//! both read sequences of documents (NDJSON) on request.
46//! 4. **Typed values**: [`FromJson`] reads a type from a [`Reader`],
47//! borrowing strings from the input; [`ToJson`] writes a type through a
48//! [`ValueWriter`], building nothing. Both are implemented by hand (or by
49//! the [`json_struct!`] macro for plain structs): no derive, no
50//! reflection. Errors are [`DecodeError`]s: what, at which byte, and where
51//! (a JSON Pointer path).
52//! 5. **[`Writer`]**: a push writer that takes events, checked as it goes,
53//! into a `String`, an `io::Write`, or a `fmt::Write`, in any [`Format`].
54//!
55//! ## What it guarantees
56//!
57//! - **RFC 8259 grammar.** Everything outside the grammar is refused with an
58//! [`Error`] that names the first byte at which the input stops being
59//! valid. Two grammatical inputs are refused by choice: unpaired UTF-16
60//! surrogate escapes, which decode to no Unicode text, and (under the
61//! default [`DuplicateKeys::Error`]) objects that repeat a key, on every
62//! way of reading.
63//! - **Borrowing.** Strings without escapes and every number are slices of the
64//! input; a string with escapes is decoded once into a buffer no larger than
65//! its escaped source text.
66//! - **Exact numbers.** A [`Number`] keeps its text; conversion to a Rust
67//! number happens when asked and never rounds silently into an integer.
68//! - **Budgets.** Depth, input size, string length, number length, value
69//! count, and the memory one read holds for what it builds (a tree or
70//! typed values) are all bounded
71//! ([`Limits`]), each checked before the memory it guards is used.
72//! - **No recursion on depth.** Parsing, the readers, writing, cloning,
73//! comparing, and hashing loop over explicit stacks; dropping recurses at
74//! most a fixed 32 levels. A million levels of nesting cannot overflow the
75//! stack. (A [`FromJson`] or [`ToJson`] impl for a recursive type of your
76//! own recurses; the depth budget bounds that on the reading side.)
77//! - **Round trip.** Written output parses back to an equal value (for
78//! objects without repeated keys, which the writers do not check), in every
79//! [`Format`], and no string can break out of its quotes ([`write_string`]).
80//! - **No panics** on any input, and `#![forbid(unsafe_code)]`.
81//!
82//! ## Feature flags
83//!
84//! - `std` (default): adds `to_writer`, `to_writer_pretty`, `to_writer_with`,
85//! `Writer::io`, `StreamReader::read_from`, and the `HashMap`/`HashSet`
86//! impls of the typed traits. Without it the crate is `no_std` and needs
87//! only `alloc`.
88
89#![cfg_attr(not(feature = "std"), no_std)]
90#![cfg_attr(docsrs, feature(doc_cfg))]
91#![forbid(unsafe_code)]
92#![deny(warnings)]
93#![deny(missing_docs)]
94#![deny(unused_must_use)]
95#![deny(unused_results)]
96#![deny(clippy::unwrap_used)]
97#![deny(clippy::expect_used)]
98#![deny(clippy::todo)]
99#![deny(clippy::unimplemented)]
100#![deny(clippy::print_stdout)]
101#![deny(clippy::print_stderr)]
102#![deny(clippy::dbg_macro)]
103#![deny(clippy::unreachable)]
104#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
105
106extern crate alloc;
107
108mod array;
109mod decode;
110mod dupes;
111mod encode;
112mod error;
113mod float;
114mod format;
115mod lexer;
116mod limits;
117mod machine;
118mod macros;
119mod number;
120mod object;
121mod parser;
122mod raw;
123mod reader;
124mod scan;
125mod small;
126mod stream;
127mod tree;
128mod value;
129mod write;
130mod writer;
131
132pub use array::Array;
133pub use decode::{
134 ArrayReader, DecodeError, DecodeErrorKind, FromJson, FromJsonKey, Nullable, ObjectReader,
135 PathSegment, from_bytes, from_str, from_value, to_value,
136};
137pub use encode::{ArrayWriter, ObjectWriter, ToJson, ToJsonKey, ValueWriter, Written};
138pub use error::{Error, ErrorKind};
139pub use format::Format;
140pub use limits::Limits;
141pub use number::Number;
142pub use object::{Entry, Iter, IterMut, Object, OccupiedEntry, VacantEntry};
143pub use parser::{DuplicateKeys, Numbers, Parser};
144pub use raw::RawValue;
145pub use reader::{Event, Reader};
146pub use stream::{Step, StreamReader};
147pub use value::{Kind, Value};
148pub use write::{
149 to_string, to_string_pretty, to_string_with, write_string, write_value, write_value_pretty,
150 write_value_with,
151};
152#[cfg(feature = "std")]
153pub use write::{to_writer, to_writer_pretty, to_writer_with};
154pub use writer::{WriteError, Writer};
155
156/// Parses one JSON document with the default [`Limits`], refusing duplicate
157/// keys.
158///
159/// The result borrows from `text`: strings without escapes and all numbers are
160/// slices of it. Call [`Value::into_owned`] to keep the value longer than the
161/// text. To change a budget or the duplicate-key policy, use [`Parser`].
162///
163/// # Errors
164///
165/// The first syntax error or exceeded budget, at its byte offset. See
166/// [`ErrorKind`] for every case.
167///
168/// # Examples
169///
170/// ```
171/// use jsonx_lib::{parse, ErrorKind};
172///
173/// let v = parse(r#"{"list": [1, 2.5, "three"]}"#)?;
174/// assert_eq!(v["list"][2], "three");
175///
176/// let err = parse(r#"{"a": tru}"#).unwrap_err();
177/// assert_eq!(err.kind(), ErrorKind::InvalidLiteral);
178/// assert_eq!(err.offset(), 9);
179/// # Ok::<(), jsonx_lib::Error>(())
180/// ```
181pub fn parse(text: &str) -> Result<Value<'_>, Error> {
182 Parser::new().parse(text)
183}
184
185/// Parses one JSON document from bytes, which must be UTF-8, with the default
186/// [`Limits`]. See [`Parser::parse_bytes`].
187///
188/// # Errors
189///
190/// [`ErrorKind::InvalidUtf8`] for bytes that are not UTF-8; otherwise as
191/// [`parse`].
192///
193/// # Examples
194///
195/// ```
196/// let body: &[u8] = br#"{"id": 1}"#;
197/// assert_eq!(jsonx_lib::parse_bytes(body)?["id"], 1);
198/// # Ok::<(), jsonx_lib::Error>(())
199/// ```
200pub fn parse_bytes(bytes: &[u8]) -> Result<Value<'_>, Error> {
201 Parser::new().parse_bytes(bytes)
202}
203
204/// The examples in `README.md`, compiled and run as doctests.
205#[cfg(doctest)]
206#[doc = include_str!("../README.md")]
207pub struct ReadmeDoctests;
208
209/// The examples in `docs/API.md`, compiled and run as doctests (with `std`,
210/// which its `to_writer` example needs).
211#[cfg(all(doctest, feature = "std"))]
212#[doc = include_str!("../docs/API.md")]
213pub struct ApiDoctests;
214
215/// Support for the [`json!`] macro. Not public API.
216#[doc(hidden)]
217pub mod __private {
218 use alloc::borrow::Cow;
219
220 pub use alloc::vec;
221
222 use crate::Value;
223
224 /// Makes one object member.
225 #[inline]
226 pub fn member<'a>(key: impl Into<Cow<'a, str>>, value: Value<'a>) -> (Cow<'a, str>, Value<'a>) {
227 (key.into(), value)
228 }
229}