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