deser_json/de.rs
1// @generated from deser-template-json/src/de.rs by
2// deser-template-json/generate.py. Do not edit.
3use alloc::string::String;
4use alloc::sync::Arc;
5use core::marker::PhantomData;
6use core::str;
7
8use deser_core::de::{self, Deserialize, DeserializeDriver, deserialize_value};
9use deser_core::{Error, ErrorKind, Source, TrackLocations};
10
11use crate::Trailing;
12use crate::parser::{Borrowing, Cursor, Options, Parser, Progress};
13
14/// Configures how JSON is deserialized.
15///
16/// The configuration is independent of the input so it can be created once
17/// (even as a constant) and used for many inputs. The methods
18/// [`from_str`](Self::from_str) and [`from_slice`](Self::from_slice) work
19/// like the functions of the same name. To create a [`Deserializer`] with
20/// the configuration use [`Deserializer::from_str_with_config`] or
21/// [`Deserializer::from_slice_with_config`].
22///
23/// ```
24/// use deser_json::DeserializerConfig;
25///
26/// const CONFIG: DeserializerConfig =
27/// DeserializerConfig::builder().exact_numbers(false).build();
28/// let value: Vec<f64> = CONFIG.from_str("[0.10, 1e5]").unwrap();
29/// assert_eq!(value, [0.1, 1e5]);
30/// ```
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct DeserializerConfig {
33 exact_numbers: bool,
34 trailing: Trailing,
35 context: deser_core::Context,
36}
37
38impl Default for DeserializerConfig {
39 fn default() -> DeserializerConfig {
40 DeserializerConfig::new()
41 }
42}
43
44impl DeserializerConfig {
45 /// Creates the default configuration.
46 pub const fn new() -> DeserializerConfig {
47 DeserializerConfig {
48 exact_numbers: true,
49 trailing: Trailing::Strict,
50 context: deser_core::Context::new(),
51 }
52 }
53
54 /// Returns a builder for the configuration (see [`DeserializerConfigBuilder`]).
55 pub const fn builder() -> DeserializerConfigBuilder {
56 DeserializerConfigBuilder::new()
57 }
58
59 /// Returns a builder that starts with this configuration.
60 pub const fn into_builder(self) -> DeserializerConfigBuilder {
61 DeserializerConfigBuilder { value: self }
62 }
63
64 /// Sets the context the values are deserialized in.
65 ///
66 /// The values of the context are the defaults of the extension values
67 /// of the state (see [`Context`](deser_core::Context)), for instance
68 /// the variants of open enums. The deserializers and readers created
69 /// with the configuration use this context. A context set
70 /// on the driver takes precedence.
71 ///
72 /// ```
73 /// use deser::Context;
74 /// use deser::de::DuplicateKeys;
75 /// use deser_json::DeserializerConfig;
76 /// use std::collections::BTreeMap;
77 ///
78 /// let config = DeserializerConfig::builder()
79 /// .context(Context::with(DuplicateKeys::Last))
80 /// .build();
81 /// let value: BTreeMap<String, u32> =
82 /// config.from_str(r#"{"a": 1, "a": 2}"#).unwrap();
83 /// assert_eq!(value["a"], 2);
84 /// ```
85 pub fn set_context(&mut self, context: deser_core::Context) {
86 self.context = context;
87 }
88
89 /// Returns the context the values are deserialized in.
90 pub fn context(&self) -> &deser_core::Context {
91 &self.context
92 }
93
94 /// Controls what may follow a value.
95 ///
96 /// By default ([`Trailing::Strict`]) only whitespace may follow the
97 /// value. [`Trailing::Newline`] reads [JSON
98 /// Lines](https://jsonlines.org/) and [`Trailing::Stop`] stops after
99 /// the value without looking at what follows:
100 ///
101 /// ```
102 /// use deser_json::{DeserializerConfig, Trailing};
103 ///
104 /// assert!(
105 /// deser_json::from_str::<Vec<u32>>("[1] trash")
106 /// .is_err()
107 /// );
108 /// const STOP: DeserializerConfig =
109 /// DeserializerConfig::builder().trailing(Trailing::Stop).build();
110 /// assert_eq!(STOP.from_str::<Vec<u32>>("[1] trash").unwrap(), [1]);
111 /// ```
112 ///
113 /// With [`Trailing::Newline`] a [`Deserializer`] reads the lines one by
114 /// one. Errors only discard their line:
115 ///
116 /// ```
117 /// use deser_json::{
118 /// Deserializer, DeserializerConfig, Trailing,
119 /// };
120 ///
121 /// const LINES: DeserializerConfig =
122 /// DeserializerConfig::builder().trailing(Trailing::Newline).build();
123 /// let mut de =
124 /// Deserializer::from_str_with_config("1\n\nnope\n3\n", LINES);
125 /// let mut values = Vec::new();
126 /// while !de.is_end() {
127 /// match de.deserialize::<u32>() {
128 /// Ok(value) => values.push(value),
129 /// Err(err) => assert_eq!(err.line(), Some(3)),
130 /// }
131 /// }
132 /// assert_eq!(values, [1, 3]);
133 /// ```
134 pub const fn set_trailing(&mut self, trailing: Trailing) {
135 self.trailing = trailing;
136 }
137
138 /// Returns what may follow a value.
139 pub(crate) fn trailing_mode(&self) -> Trailing {
140 self.trailing
141 }
142
143 /// Returns `true` if exact numbers are enabled.
144 pub(crate) fn exact_numbers_enabled(&self) -> bool {
145 self.exact_numbers
146 }
147
148 /// Enables or disables exact numbers.
149 ///
150 /// When enabled (which is the default) floats which lose precision as
151 /// `f64` and integers that do not fit into 128 bits are emitted as
152 /// [`Number`](deser_core::ext::Number) extension values. These carry the
153 /// text of the number together with its value as `f64`, which is what
154 /// types that do not know about exact numbers receive. Types like
155 /// [`Decimal`](deser_core::ext::Decimal) (and the types of `rust_decimal` or
156 /// `bigdecimal`) use the text to deserialize the number exactly:
157 ///
158 /// ```
159 /// use deser::ext::Decimal;
160 ///
161 /// let value: Decimal =
162 /// deser_json::from_str("0.10000000000000000001")
163 /// .unwrap();
164 /// assert_eq!(value.as_str(), "0.10000000000000000001");
165 /// let value: f64 =
166 /// deser_json::from_str("0.10000000000000000001")
167 /// .unwrap();
168 /// assert_eq!(value, 0.1);
169 /// ```
170 ///
171 /// Floats whose text is the shortest representation of their value (as
172 /// formatted by `Debug`, for instance `0.5` or `3.14`) are emitted as
173 /// plain floats as the text can be recovered from the value. This keeps
174 /// the common case fast. When disabled, all floats are emitted as plain
175 /// floats.
176 pub const fn set_exact_numbers(&mut self, yes: bool) {
177 self.exact_numbers = yes;
178 }
179
180 /// Deserializes JSON from the given string.
181 ///
182 /// What may follow the value depends on [`set_trailing`](Self::set_trailing).
183 /// With [`Trailing::Newline`] this reads the first line.
184 pub fn from_str<'de, T: Deserialize<'de>>(&self, s: &'de str) -> Result<T, Error> {
185 deserialize_value(|driver| self.drive_str(s, driver))
186 }
187
188 /// The part of [`from_str`](Self::from_str) that does not depend on the type
189 /// of the value, it exists once.
190 fn drive_str<'de>(
191 &self,
192 s: &'de str,
193 driver: &mut DeserializeDriver<'_, 'de>,
194 ) -> Result<(), Error> {
195 de::Deserializer::drive(
196 &mut Deserializer::from_str_with_config(s, self.clone()),
197 driver,
198 )
199 }
200
201 /// Deserializes JSON from the given bytes.
202 ///
203 /// The input must be UTF-8. Rather than validating the input upfront,
204 /// the strings are validated while parsing (see
205 /// [`Deserializer::from_slice`]).
206 pub fn from_slice<'de, T: Deserialize<'de>>(&self, bytes: &'de [u8]) -> Result<T, Error> {
207 deserialize_value(|driver| self.drive_slice(bytes, driver))
208 }
209
210 /// The part of [`from_slice`](Self::from_slice) that does not depend on the type
211 /// of the value, it exists once.
212 fn drive_slice<'de>(
213 &self,
214 bytes: &'de [u8],
215 driver: &mut DeserializeDriver<'_, 'de>,
216 ) -> Result<(), Error> {
217 de::Deserializer::drive(
218 &mut Deserializer::from_slice_with_config(bytes, self.clone()),
219 driver,
220 )
221 }
222}
223
224/// Builds a [`DeserializerConfig`].
225///
226/// The methods have the names of the setters of [`DeserializerConfig`] (without `set_`).
227#[derive(Debug, Clone)]
228#[must_use]
229pub struct DeserializerConfigBuilder {
230 value: DeserializerConfig,
231}
232
233impl DeserializerConfigBuilder {
234 /// Creates a builder that starts with the default.
235 pub const fn new() -> DeserializerConfigBuilder {
236 DeserializerConfigBuilder {
237 value: DeserializerConfig::new(),
238 }
239 }
240
241 /// Controls what may follow a value.
242 ///
243 /// See [`DeserializerConfig::set_trailing`].
244 pub const fn trailing(mut self, trailing: Trailing) -> DeserializerConfigBuilder {
245 self.value.set_trailing(trailing);
246 self
247 }
248
249 /// Enables or disables exact numbers.
250 ///
251 /// See [`DeserializerConfig::set_exact_numbers`].
252 pub const fn exact_numbers(mut self, yes: bool) -> DeserializerConfigBuilder {
253 self.value.set_exact_numbers(yes);
254 self
255 }
256
257 /// Sets the context the values are deserialized in.
258 ///
259 /// See [`DeserializerConfig::set_context`].
260 pub fn context(mut self, context: deser_core::Context) -> DeserializerConfigBuilder {
261 self.value.set_context(context);
262 self
263 }
264
265 /// Returns the built [`DeserializerConfig`].
266 pub const fn build(self) -> DeserializerConfig {
267 // the value cannot be moved out of the builder in a const fn as the
268 // builder needs dropping (the context has a destructor)
269 // SAFETY: the value is read once and the builder is forgotten
270 let value = unsafe { core::ptr::read(&self.value) };
271 core::mem::forget(self);
272 value
273 }
274}
275
276impl Default for DeserializerConfigBuilder {
277 fn default() -> DeserializerConfigBuilder {
278 DeserializerConfigBuilder::new()
279 }
280}
281
282/// Deserializes a serializable from JSON.
283///
284/// Every call to [`deserialize`](Self::deserialize) reads the next value.
285/// What may follow a value is controlled by
286/// [`DeserializerConfig::set_trailing`]. By default only whitespace may follow
287/// so there is only a single value. With [`Trailing::Newline`] the
288/// deserializer reads [JSON Lines](https://jsonlines.org/):
289///
290/// ```
291/// use deser_json::{
292/// Deserializer, DeserializerConfig, Trailing,
293/// };
294///
295/// let config = DeserializerConfig::builder().trailing(Trailing::Newline).build();
296/// let mut de =
297/// Deserializer::from_str_with_config("[1, 2]\n[3]\n", config);
298/// assert_eq!(de.deserialize::<Vec<u32>>().unwrap(), [1, 2]);
299/// assert_eq!(de.deserialize::<Vec<u32>>().unwrap(), [3]);
300/// assert!(de.is_end());
301/// ```
302///
303/// To deserialize a single value, use [`from_str`] and
304/// [`from_slice`] (or the methods of the same name on
305/// [`DeserializerConfig`]). The deserializer is also useful to
306/// [`drive`](Self::drive) a custom sink.
307pub struct Deserializer<'a> {
308 input: &'a [u8],
309 pos: usize,
310 parser: Parser,
311 // `true` if the input is a byte slice which needs to be validated
312 validate_utf8: bool,
313 // `true` if a value failed and the stream cannot be continued
314 failed: bool,
315 // the input as source for location tracking, shared by all values
316 source: Option<Arc<str>>,
317 config: DeserializerConfig,
318}
319
320impl<'a> Deserializer<'a> {
321 /// Creates a new deserializer for a string.
322 #[allow(clippy::should_implement_trait)]
323 pub fn from_str(input: &'a str) -> Deserializer<'a> {
324 Deserializer::from_str_with_config(input, DeserializerConfig::new())
325 }
326
327 /// Creates a new deserializer for a string with the given configuration.
328 pub fn from_str_with_config(input: &'a str, config: DeserializerConfig) -> Deserializer<'a> {
329 Deserializer {
330 // the parser works on bytes but relies on the input being valid
331 // UTF-8 when it hands out string slices.
332 input: input.as_bytes(),
333 validate_utf8: false,
334 pos: 0,
335 parser: Parser::default(),
336 failed: false,
337 source: None,
338 config,
339 }
340 }
341
342 /// Creates a new deserializer for a byte slice.
343 ///
344 /// The input is not validated upfront. Instead strings are validated as
345 /// UTF-8 when they are parsed (bytes outside of strings are only ever
346 /// accepted if they are ASCII). Invalid UTF-8 is an error.
347 pub fn from_slice(input: &'a [u8]) -> Deserializer<'a> {
348 Deserializer::from_slice_with_config(input, DeserializerConfig::new())
349 }
350
351 /// Creates a new deserializer for a byte slice with the given
352 /// configuration.
353 ///
354 /// See [`from_slice`](Self::from_slice).
355 pub fn from_slice_with_config(input: &'a [u8], config: DeserializerConfig) -> Deserializer<'a> {
356 Deserializer {
357 input,
358 validate_utf8: true,
359 pos: 0,
360 parser: Parser::default(),
361 failed: false,
362 source: None,
363 config,
364 }
365 }
366
367 /// Creates a deserializer for the frame of a value in a stream.
368 ///
369 /// Only whitespace may follow the value in the frame.
370 pub(crate) fn from_frame(input: &'a [u8], config: &DeserializerConfig) -> Deserializer<'a> {
371 let mut de = Deserializer::from_slice_with_config(input, config.clone());
372 de.config.trailing = Trailing::Strict;
373 de
374 }
375
376 /// Returns the configuration.
377 pub fn config(&self) -> &DeserializerConfig {
378 &self.config
379 }
380
381 /// Returns the current offset in the input.
382 pub fn offset(&self) -> usize {
383 self.pos
384 }
385
386 /// Returns `true` if there are no more values.
387 ///
388 /// This is the case if only whitespace is left or if a value failed and
389 /// the stream cannot be continued (see [`deserialize`](Self::deserialize)).
390 pub fn is_end(&self) -> bool {
391 self.failed || self.next_token() == self.input.len()
392 }
393
394 /// Fails if there is more than whitespace left.
395 ///
396 /// This is useful with [`Trailing::Stop`] to check that the input was
397 /// consumed.
398 pub fn end(&self) -> Result<(), Error> {
399 if self.is_end() {
400 return Ok(());
401 }
402 let mut err =
403 Error::with_offset(ErrorKind::Syntax, "garbage after input", self.next_token());
404 err.resolve_position(self.input);
405 Err(err)
406 }
407
408 /// Returns where the next token starts (or the end of the input).
409 fn next_token(&self) -> usize {
410 let mut cursor = Cursor::new(self.input, self.pos);
411 cursor.parse_whitespace();
412 cursor.pos
413 }
414
415 /// Returns the input as string for the source.
416 fn source(&self) -> alloc::borrow::Cow<'a, str> {
417 if self.validate_utf8 {
418 // invalid UTF-8 fails the parsing when reached, the offsets of
419 // the tokens before it are not affected by the replacements.
420 String::from_utf8_lossy(self.input)
421 } else {
422 // SAFETY: the input was created from a string
423 alloc::borrow::Cow::Borrowed(unsafe { str::from_utf8_unchecked(self.input) })
424 }
425 }
426
427 /// Deserializes the next value.
428 ///
429 /// What may follow the value depends on
430 /// [`DeserializerConfig::set_trailing`]. Fails with
431 /// [`ErrorKind::EndOfFile`] if there are no more values.
432 ///
433 /// If a value fails to deserialize (because it's malformed or does not
434 /// match the type), the stream ends: [`is_end`](Self::is_end) returns
435 /// `true` and further calls fail. With [`Trailing::Newline`] only the
436 /// rest of the line is skipped and the next call continues with the
437 /// next line.
438 ///
439 /// To configure the deserialization (for instance to add layers) use
440 /// [`deserialize_with`](Self::deserialize_with).
441 pub fn deserialize<T: Deserialize<'a>>(&mut self) -> Result<T, Error> {
442 de::Deserializer::deserialize(self)
443 }
444
445 /// Deserializes the next value with a configured driver.
446 ///
447 /// The callback is invoked with the driver before the value is
448 /// deserialized, for instance to add [`Layer`](deser_core::de::Layer)s.
449 pub fn deserialize_with<T, F>(&mut self, setup: F) -> Result<T, Error>
450 where
451 T: Deserialize<'a>,
452 F: FnOnce(&mut DeserializeDriver<'_, 'a>),
453 {
454 de::Deserializer::deserialize_with(self, setup)
455 }
456
457 /// Returns an iterator over the remaining values.
458 ///
459 /// This is useful to read JSON Lines (see [`Trailing::Newline`]). The
460 /// iterator stops after the first error.
461 ///
462 /// ```
463 /// use deser_json::{
464 /// Deserializer, DeserializerConfig, Trailing,
465 /// };
466 ///
467 /// let config = DeserializerConfig::builder().trailing(Trailing::Newline).build();
468 /// let mut de = Deserializer::from_str_with_config("1\n2\n3\n", config);
469 /// let items = de.iter::<u32>().collect::<Result<Vec<_>, _>>().unwrap();
470 /// assert_eq!(items, [1, 2, 3]);
471 /// ```
472 pub fn iter<T: Deserialize<'a>>(&mut self) -> Iter<'_, 'a, T> {
473 Iter {
474 de: self,
475 failed: false,
476 _marker: PhantomData,
477 }
478 }
479
480 /// Parses the next value and feeds the events into the given driver.
481 ///
482 /// This is useful to deserialize into a custom [`Sink`](deser_core::de::Sink).
483 /// See also [`deserialize_with`](Self::deserialize_with).
484 ///
485 /// Strings without escape sequences are passed on borrowed from the
486 /// input (see [`emit_borrowed`](DeserializeDriver::emit_borrowed)).
487 /// Errors carry the location in the input (see [`Error::line`]).
488 pub fn drive(&mut self, driver: &mut DeserializeDriver<'_, 'a>) -> Result<(), Error> {
489 if self.failed {
490 return Err(Error::new(
491 ErrorKind::InvalidState,
492 "cannot continue after an error",
493 ));
494 }
495 if TrackLocations::of(driver.state()) {
496 let source = match self.source {
497 Some(ref source) => source.clone(),
498 None => {
499 let source: Arc<str> = self.source().into();
500 self.source = Some(source.clone());
501 source
502 }
503 };
504 Source(source).set(driver.state_mut());
505 }
506
507 // for JSON Lines the input is cut off at the end of the line. The
508 // parser then fails if the value does not end on the line.
509 let input = self.input;
510 let line_end = if self.config.trailing == Trailing::Newline {
511 self.skip_whitespace();
512 let end = input[self.pos..]
513 .iter()
514 .position(|&b| b == b'\n')
515 .map_or(input.len(), |idx| self.pos + idx);
516 self.input = &input[..end];
517 Some(end)
518 } else {
519 None
520 };
521
522 let rv = self.drive_impl(driver);
523 self.input = input;
524
525 let rv = rv.map_err(|err| self.locate_error(err));
526 match line_end {
527 // the rest of the line is skipped, even after errors
528 Some(end) => self.pos = end,
529 // after an error the position within the value is unknown
530 None => self.failed = rv.is_err() && !self.is_end(),
531 }
532 rv
533 }
534
535 /// Attaches the location to an error.
536 #[cold]
537 fn locate_error(&self, mut err: Error) -> Error {
538 // errors of the parser are located at the current position, errors
539 // of the sinks at the event that failed
540 if err.offset().is_none() {
541 err.set_offset(self.pos);
542 }
543 err.resolve_position(self.input);
544 err
545 }
546
547 fn drive_impl(&mut self, driver: &mut DeserializeDriver<'_, 'a>) -> Result<(), Error> {
548 let options = Options {
549 validate_utf8: self.validate_utf8,
550 exact_numbers: self.config.exact_numbers,
551 };
552 let mut out = Borrowing(driver);
553 match self
554 .parser
555 .parse(self.input, self.pos, true, 0, options, &mut out)
556 {
557 Ok(Progress::Done(pos)) => {
558 self.pos = pos;
559 self.finish_value()
560 }
561 Ok(Progress::NeedMore(_)) => unreachable!("the input is complete"),
562 Err(err) => {
563 self.parser.reset();
564 Err(err)
565 }
566 }
567 }
568
569 /// Skips whitespace.
570 fn skip_whitespace(&mut self) {
571 self.pos = self.next_token();
572 }
573
574 /// Checks what follows a complete value.
575 #[inline]
576 fn finish_value(&mut self) -> Result<(), Error> {
577 let msg = match self.config.trailing {
578 Trailing::Strict => "garbage after input",
579 // the input was cut off at the end of the line
580 Trailing::Newline => "expected end of line after value",
581 Trailing::Stop => return Ok(()),
582 };
583 self.skip_whitespace();
584 if self.pos < self.input.len() {
585 return Err(Error::new(ErrorKind::Syntax, msg));
586 }
587 Ok(())
588 }
589}
590
591/// An iterator over the values of a JSON stream.
592///
593/// See [`Deserializer::iter`].
594pub struct Iter<'b, 'a, T> {
595 de: &'b mut Deserializer<'a>,
596 failed: bool,
597 _marker: PhantomData<fn() -> T>,
598}
599
600impl<'b, 'a, T: Deserialize<'a>> Iterator for Iter<'b, 'a, T> {
601 type Item = Result<T, Error>;
602
603 fn next(&mut self) -> Option<Self::Item> {
604 if self.failed || self.de.is_end() {
605 return None;
606 }
607 let rv = self.de.deserialize();
608 self.failed = rv.is_err();
609 Some(rv)
610 }
611}
612
613impl<'a> de::Deserializer<'a> for Deserializer<'a> {
614 fn drive(&mut self, driver: &mut DeserializeDriver<'_, 'a>) -> Result<(), Error> {
615 if !self.config.context.is_empty() {
616 driver.set_default_context(self.config.context.clone());
617 }
618 Deserializer::drive(self, driver)
619 }
620}
621
622/// Deserializes JSON from the given string.
623///
624/// The input must contain exactly one value, only whitespace may follow it.
625/// To read multiple values (for instance JSON Lines) use a [`Deserializer`]
626/// with [`Trailing::Newline`]. This uses the default
627/// [`DeserializerConfig`].
628pub fn from_str<'de, T: Deserialize<'de>>(s: &'de str) -> Result<T, Error> {
629 DeserializerConfig::new().from_str(s)
630}
631
632/// Deserializes JSON from the given bytes.
633///
634/// The input must be UTF-8. Rather than validating the input upfront, the
635/// strings are validated while parsing (see [`Deserializer::from_slice`]).
636/// This uses the default [`DeserializerConfig`].
637pub fn from_slice<'de, T: Deserialize<'de>>(bytes: &'de [u8]) -> Result<T, Error> {
638 DeserializerConfig::new().from_slice(bytes)
639}