Skip to main content

jsonx_lib/
lib.rs

1//! # jsonx_lib
2//!
3//! Strict RFC 8259 JSON: a parser that borrows from its input, a pull reader,
4//! and a deterministic writer, with budgets that refuse hostile input before
5//! it costs memory. No dependencies; `no_std` with `alloc`.
6//!
7//! ## Quick start
8//!
9//! ```
10//! use jsonx_lib::{json, parse, to_string};
11//!
12//! let doc = parse(r#"{"name": "jsonx", "version": [0, 2, 0], "stable": false}"#)?;
13//! assert_eq!(doc["name"], "jsonx");
14//! assert_eq!(doc["version"][1].as_u64(), Some(2));
15//!
16//! let reply = json!({ "ok": true, "items": [1, 2, 3] });
17//! assert_eq!(to_string(&reply), r#"{"ok":true,"items":[1,2,3]}"#);
18//! # Ok::<(), jsonx_lib::Error>(())
19//! ```
20//!
21//! ## The three ways in
22//!
23//! 1. **[`parse`] and [`to_string`]** (plus [`parse_bytes`] and
24//!    [`to_string_pretty`]): one call each, default budgets, duplicate keys
25//!    refused.
26//! 2. **[`Parser`]**: the same parse with your own [`Limits`] and
27//!    [`DuplicateKeys`] policy, kept as a `const` and reused.
28//! 3. **[`Reader`]**: the document as a stream of [`Event`]s, with
29//!    [`read_raw`](Reader::read_raw) to keep a value as its source text and
30//!    [`read_value`](Reader::read_value) to build just one part of it.
31//!
32//! ## What it guarantees
33//!
34//! - **Exactly RFC 8259.** Everything the grammar allows is accepted;
35//!   everything else is refused with an [`Error`] that names the first byte at
36//!   which the input stops being valid. Unpaired UTF-16 surrogate escapes,
37//!   which the grammar allows but which decode to no Unicode text, are
38//!   refused too.
39//! - **Borrowing.** Strings without escapes and every number are slices of the
40//!   input; only strings with escapes are copied, once, into a buffer of
41//!   exactly the right size.
42//! - **Exact numbers.** A [`Number`] keeps its text; conversion to `i64`,
43//!   `u64`, or `f64` happens when asked and never rounds silently into an
44//!   integer.
45//! - **Budgets before allocation.** Depth, input size, string length, number
46//!   length, and value count are all checked before the memory they guard is
47//!   used ([`Limits`]).
48//! - **No recursion on depth.** Parsing, writing, cloning, and comparing loop
49//!   over explicit stacks; dropping recurses at most a fixed 32 levels. A
50//!   million levels of nesting cannot overflow the stack.
51//! - **Round trip.** Written output parses back to an equal value, and the
52//!   escaping cannot be broken out of by any string ([`write_string`]).
53//! - **No panics** on any input, and `#![forbid(unsafe_code)]`.
54//!
55//! ## Feature flags
56//!
57//! - `std` (default): adds [`to_writer`] and [`to_writer_pretty`]. Without it
58//!   the crate is `no_std` and needs only `alloc`.
59
60#![cfg_attr(not(feature = "std"), no_std)]
61#![cfg_attr(docsrs, feature(doc_cfg))]
62#![forbid(unsafe_code)]
63#![deny(missing_docs)]
64#![deny(unused_must_use)]
65#![deny(unused_results)]
66#![deny(clippy::unwrap_used)]
67#![deny(clippy::expect_used)]
68#![deny(clippy::todo)]
69#![deny(clippy::unimplemented)]
70#![deny(clippy::print_stdout)]
71#![deny(clippy::print_stderr)]
72#![deny(clippy::dbg_macro)]
73#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
74
75extern crate alloc;
76
77mod array;
78mod error;
79mod lexer;
80mod limits;
81mod macros;
82mod number;
83mod object;
84mod parser;
85mod reader;
86mod scan;
87mod tree;
88mod value;
89mod write;
90
91pub use array::Array;
92pub use error::{Error, ErrorKind};
93pub use limits::Limits;
94pub use number::Number;
95pub use object::{Iter, IterMut, Object};
96pub use parser::{DuplicateKeys, Parser};
97pub use reader::{Event, Reader};
98pub use value::{Kind, Value};
99pub use write::{to_string, to_string_pretty, write_string, write_value, write_value_pretty};
100#[cfg(feature = "std")]
101pub use write::{to_writer, to_writer_pretty};
102
103/// Parses one JSON document with the default [`Limits`], refusing duplicate
104/// keys.
105///
106/// The result borrows from `text`: strings without escapes and all numbers are
107/// slices of it. Call [`Value::into_owned`] to keep the value longer than the
108/// text. To change a budget or the duplicate-key policy, use [`Parser`].
109///
110/// # Errors
111///
112/// The first syntax error or exceeded budget, at its byte offset. See
113/// [`ErrorKind`] for every case.
114///
115/// # Examples
116///
117/// ```
118/// use jsonx_lib::{parse, ErrorKind};
119///
120/// let v = parse(r#"{"list": [1, 2.5, "three"]}"#)?;
121/// assert_eq!(v["list"][2], "three");
122///
123/// let err = parse(r#"{"a": tru}"#).unwrap_err();
124/// assert_eq!(err.kind(), ErrorKind::InvalidLiteral);
125/// assert_eq!(err.offset(), 9);
126/// # Ok::<(), jsonx_lib::Error>(())
127/// ```
128pub fn parse(text: &str) -> Result<Value<'_>, Error> {
129    Parser::new().parse(text)
130}
131
132/// Parses one JSON document from bytes, which must be UTF-8, with the default
133/// [`Limits`]. See [`Parser::parse_bytes`].
134///
135/// # Errors
136///
137/// [`ErrorKind::InvalidUtf8`] for bytes that are not UTF-8; otherwise as
138/// [`parse`].
139///
140/// # Examples
141///
142/// ```
143/// let body: &[u8] = br#"{"id": 1}"#;
144/// assert_eq!(jsonx_lib::parse_bytes(body)?["id"], 1);
145/// # Ok::<(), jsonx_lib::Error>(())
146/// ```
147pub fn parse_bytes(bytes: &[u8]) -> Result<Value<'_>, Error> {
148    Parser::new().parse_bytes(bytes)
149}
150
151/// The examples in `README.md`, compiled and run as doctests.
152#[cfg(doctest)]
153#[doc = include_str!("../README.md")]
154pub struct ReadmeDoctests;
155
156/// The examples in `docs/API.md`, compiled and run as doctests (with `std`,
157/// which its `to_writer` example needs).
158#[cfg(all(doctest, feature = "std"))]
159#[doc = include_str!("../docs/API.md")]
160pub struct ApiDoctests;
161
162/// Support for the [`json!`] macro. Not public API.
163#[doc(hidden)]
164pub mod __private {
165    use alloc::borrow::Cow;
166
167    pub use alloc::vec;
168
169    use crate::Value;
170
171    /// Makes one object member.
172    #[inline]
173    pub fn member<'a>(key: impl Into<Cow<'a, str>>, value: Value<'a>) -> (Cow<'a, str>, Value<'a>) {
174        (key.into(), value)
175    }
176}