Skip to main content

deser_core/
state.rs

1//! The state shared between data formats and the types they process.
2use alloc::vec::Vec;
3use core::any::TypeId;
4use core::fmt;
5
6use crate::de::arena::{Arena, Buffer};
7use crate::error::{Error, ErrorContext};
8use crate::event::ContainerShape;
9use crate::extensions::{EventData, Extensions};
10
11/// The input range of events without one.
12pub(crate) const NO_RANGE: (usize, usize) = (usize::MAX, 0);
13
14/// Gives access to the state of an ongoing serialization or deserialization.
15///
16/// The state acts as a communication channel between the data format and
17/// the types that are serialized or deserialized.  It is used in both
18/// directions: [`Sink`](crate::de::Sink)s receive it during deserialization
19/// and [`Serialize`](crate::ser::Serialize) implementations and emitters
20/// receive it during serialization.  Formats get mutable access to it through
21/// the drivers.
22///
23/// Besides some information about the current position (such as the
24/// [`depth`](Self::depth)) it holds typed values that can be used by formats
25/// and types to exchange information that is not part of the data model:
26///
27/// * Extension values ([`get`](Self::get) and [`get_mut`](Self::get_mut))
28///   remain in the state until they are changed.  They are used for
29///   information that spans many events such as the current path.
30/// * Event data ([`event`](Self::event) and [`event_mut`](Self::event_mut))
31///   is attached to a single event and detached by the drivers after the
32///   event was delivered.  It is used for information about an individual
33///   value, such as a tag.
34///
35/// Some extension values are well-known: the policy for keys that are
36/// given more than once ([`DuplicateKeys`](crate::de::DuplicateKeys)),
37/// the policy for keys that no field of a struct takes
38/// ([`UnknownFields`](crate::de::UnknownFields)), how bytes are decoded
39/// from strings ([`BytesFormat`](crate::BytesFormat)) and the source the
40/// input ranges refer to ([`Source`](crate::Source)).  They are read and
41/// set with their `of` and `set` functions.
42///
43/// Additionally formats can publish the byte range in the input of every
44/// event (see [`input_range`](Self::input_range)) and extensions can
45/// register types that add context to errors (see
46/// [`add_error_context`](Self::add_error_context)).
47///
48/// Extension values have to be [`Send`] and [`Sync`] so that the state is
49/// too.  This means that the state never prevents an ongoing serialization
50/// or deserialization from moving between threads.  They are `Sync` as
51/// event data is recorded (see [`Recording`](crate::de::Recording)) and
52/// recordings can be serialized.
53pub struct State {
54    extensions: Extensions,
55    // the number of open containers
56    pub(crate) depth: usize,
57    // the shape of the container that is currently started
58    pub(crate) container_shape: ContainerShape,
59    pub(crate) is_map_key: bool,
60    // `true` if the innermost open container is a multimap
61    pub(crate) is_multimap: bool,
62    // the key of the content of maps, empty if there is none (see
63    // `ContentKey`)
64    pub(crate) content_key: &'static str,
65    // the byte range of the current event, `NO_RANGE` if there is none.
66    // This is not an option so that it can be cleared with a single store.
67    pub(crate) input_range: (usize, usize),
68    // keyed by type as function pointers cannot be compared reliably
69    error_context: Vec<(TypeId, AddContextFn)>,
70    // `true` while errors are thrown away, see `discard_errors`.
71    pub(crate) discards_errors: bool,
72    // `true` if containers collect the errors of their items, see
73    // `set_collect_errors`.
74    collect_errors: bool,
75    // the number of errors that can still be collected
76    remaining_errors: usize,
77    // `true` once an error was not collected because of the limit
78    error_limit_reached: bool,
79    // the arena the sinks of the deserialization are allocated in
80    pub(crate) arena: Arena,
81}
82
83/// The function of an [`ErrorContext`].
84type AddContextFn = fn(Error, &State) -> Error;
85
86impl State {
87    /// Creates an empty state.
88    ///
89    /// Drivers create their state, this is useful for code that processes
90    /// events without a driver.
91    #[allow(clippy::new_without_default)]
92    pub fn new() -> State {
93        State {
94            extensions: Extensions::default(),
95            depth: 0,
96            container_shape: ContainerShape::new(),
97            is_map_key: false,
98            is_multimap: false,
99            content_key: "",
100            input_range: NO_RANGE,
101            error_context: Vec::new(),
102            discards_errors: false,
103            collect_errors: false,
104            remaining_errors: usize::MAX,
105            error_limit_reached: false,
106            arena: Arena::new(),
107        }
108    }
109
110    /// Sets if maps and sequences collect the errors of their items.
111    ///
112    /// By default the first error ends the deserialization.  If errors are
113    /// collected, the sinks of the containers that support it (derived
114    /// structs and the standard collections) recover from the errors of
115    /// their items (see [`Sink::recover`](crate::de::Sink::recover)) and
116    /// deserialization continues to find the other errors.  The container
117    /// fails once it's complete with all errors it collected (see
118    /// [`Error::errors`]), including the fields that are missing.  This
119    /// makes it possible to report all problems of the input at once:
120    ///
121    /// ```
122    /// use deser::de::DeserializeDriver;
123    /// use deser::{Deserialize, Event};
124    ///
125    /// #[derive(Deserialize, Debug)]
126    /// struct Server {
127    ///     host: String,
128    ///     port: u16,
129    /// }
130    ///
131    /// let mut out = None::<Vec<Server>>;
132    /// let mut driver = DeserializeDriver::new(&mut out);
133    /// driver.state_mut().set_collect_errors(true);
134    /// let mut rv = Ok(());
135    /// for event in [
136    ///     Event::seq_start(),
137    ///     Event::map_start(),
138    ///     "host".into(),
139    ///     42u64.into(),
140    ///     "port".into(),
141    ///     80u64.into(),
142    ///     Event::MapEnd,
143    ///     Event::map_start(),
144    ///     "host".into(),
145    ///     "b".into(),
146    ///     "port".into(),
147    ///     "http".into(),
148    ///     Event::MapEnd,
149    ///     Event::map_start(),
150    ///     Event::MapEnd,
151    ///     Event::SeqEnd,
152    /// ] {
153    ///     rv = rv.and_then(|()| driver.emit(event));
154    /// }
155    /// let err = rv.unwrap_err();
156    /// let errors: Vec<_> = err.errors().map(|err| err.message()).collect();
157    /// assert_eq!(
158    ///     errors,
159    ///     [
160    ///         "unexpected unsigned integer, expected string",
161    ///         "unexpected string, expected u16",
162    ///         "missing field `host`",
163    ///         "missing field `port`",
164    ///     ]
165    /// );
166    /// ```
167    ///
168    /// Types can change this for the values in them, for instance to
169    /// collect the errors of a part of the input.  The previous setting is
170    /// returned.  While errors are thrown away (for instance while an
171    /// untagged enum tries its variants) they are never collected.  See
172    /// [`set_max_errors`](Self::set_max_errors) to limit the number of
173    /// errors that are collected.
174    pub fn set_collect_errors(&mut self, yes: bool) -> bool {
175        core::mem::replace(&mut self.collect_errors, yes)
176    }
177
178    /// Returns `true` if the errors of items are collected.
179    ///
180    /// See [`set_collect_errors`](Self::set_collect_errors).
181    pub fn collects_errors(&self) -> bool {
182        self.collect_errors && !self.discards_errors
183    }
184
185    /// Limits the number of errors that are collected.
186    ///
187    /// Once the limit is reached, the next error ends the deserialization
188    /// (together with the errors collected so far).  By default there is no
189    /// limit.  This counts from the current number of collected errors.
190    pub fn set_max_errors(&mut self, max: usize) {
191        self.remaining_errors = max;
192        self.error_limit_reached = false;
193    }
194
195    /// Returns `true` once the limit of errors was reached.
196    ///
197    /// The error that exceeded the limit (see
198    /// [`set_max_errors`](Self::set_max_errors)) ends the deserialization.
199    /// Sinks that keep the errors of their values instead of returning
200    /// them should return errors once this is set.
201    pub fn error_limit_reached(&self) -> bool {
202        self.error_limit_reached
203    }
204
205    /// Takes a number of the errors that can still be collected.
206    ///
207    /// Returns `false` if errors are not collected or the limit is reached.
208    pub(crate) fn take_error_slots(&mut self, count: usize) -> bool {
209        if !self.collects_errors() {
210            false
211        } else if self.remaining_errors >= count {
212            self.remaining_errors -= count;
213            true
214        } else {
215            self.error_limit_reached = true;
216            false
217        }
218    }
219
220    /// Returns `true` while errors are thrown away.
221    ///
222    /// While an untagged enum tries its variants only whether a variant
223    /// accepts the value matters.  The errors are created without a message
224    /// then, and the driver does not attach context to them.  Sinks that
225    /// keep the errors of their values (instead of returning them) should
226    /// return them while this is set.
227    pub fn discards_errors(&self) -> bool {
228        self.discards_errors
229    }
230
231    /// Runs a function during which errors are thrown away.
232    ///
233    /// This is used while an untagged enum tries its variants: only whether
234    /// a variant accepts the value matters, so the errors that are returned
235    /// are created without a message (see
236    /// [`discarded_error`](crate::error::discarded_error)) and the driver
237    /// does not attach context to them.  Errors that are kept rather than
238    /// returned (for instance collected unknown fields) are unaffected.
239    pub(crate) fn discard_errors<R>(&mut self, f: impl FnOnce(&mut State) -> R) -> R {
240        let outer = core::mem::replace(&mut self.discards_errors, true);
241        let rv = f(self);
242        self.discards_errors = outer;
243        rv
244    }
245
246    /// Takes the scratch space of a format that was kept from the last
247    /// deserialization (see
248    /// [`__private_put_scratch`](Self::__private_put_scratch)).
249    ///
250    /// This is not public API.
251    #[doc(hidden)]
252    #[inline]
253    pub fn __private_take_scratch(&mut self) -> Vec<u8> {
254        self.arena.take_vec(Buffer::Scratch).unwrap_or_default()
255    }
256
257    /// Keeps the scratch space of a format for the next deserialization.
258    ///
259    /// Formats that unescape strings into a buffer would otherwise grow it
260    /// again for every document.  The buffer is cleared.
261    ///
262    /// This is not public API.
263    #[doc(hidden)]
264    #[inline]
265    pub fn __private_put_scratch(&mut self, buffer: Vec<u8>) {
266        self.arena.put_vec(Buffer::Scratch, buffer);
267    }
268
269    /// Takes the state out, leaving an empty state that does not allocate.
270    pub(crate) fn take(&mut self) -> State {
271        core::mem::replace(self, State::new())
272    }
273
274    #[inline]
275    pub(crate) fn extensions(&self) -> &Extensions {
276        &self.extensions
277    }
278
279    #[inline]
280    pub(crate) fn extensions_mut(&mut self) -> &mut Extensions {
281        &mut self.extensions
282    }
283
284    /// Returns an extension value.
285    ///
286    /// Returns `None` if the value was never set.
287    #[inline]
288    pub fn get<T: fmt::Debug + Send + Sync + 'static>(&self) -> Option<&T> {
289        self.extensions.get()
290    }
291
292    /// Returns a mutable extension value.
293    ///
294    /// If the value was never set, it's initialized with the default value.
295    #[inline]
296    pub fn get_mut<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self) -> &mut T {
297        self.extensions.get_mut()
298    }
299
300    /// Marks an extension type as replayable.
301    ///
302    /// When a value is internally buffered during deserialization (for
303    /// instance for internally tagged enums, see
304    /// [`Recording`](crate::de::Recording)) the values of replayable
305    /// extensions are captured for every event and restored when the event is
306    /// replayed.  This is used for information that changes from event to
307    /// event but remains in the state, such as the current path.  Event data
308    /// is always captured, it does not need to be marked.
309    pub fn set_replayable<T: Clone + Default + fmt::Debug + Send + Sync + 'static>(&mut self) {
310        self.extensions.set_replayable::<T>();
311    }
312
313    /// Returns the data of a type attached to the current event.
314    ///
315    /// Returns `None` if no such data is attached to the event.
316    ///
317    /// Event data is attached to the next event and detached by the driver
318    /// after that event was delivered:
319    ///
320    /// * During deserialization, formats attach data with
321    ///   [`event_mut`](Self::event_mut) before they emit the event with the
322    ///   [`DeserializeDriver`](crate::de::DeserializeDriver).  The sinks
323    ///   that receive the event (including the
324    ///   [`finish`](crate::de::Sink::finish) of a container on its end event)
325    ///   can access it.
326    /// * During serialization, [`Serialize`](crate::ser::Serialize)
327    ///   implementations and emitters attach data while they produce a
328    ///   value.  The format receives it together with the first event of the
329    ///   value from the [`SerializeDriver`](crate::ser::SerializeDriver).
330    ///
331    /// Event data is captured by a [`Recording`](crate::de::Recording) and
332    /// restored when the events are replayed.
333    #[inline(always)]
334    pub fn event<T: fmt::Debug + Send + Sync + 'static>(&self) -> Option<&T> {
335        self.extensions.event()
336    }
337
338    /// Returns the data of a type attached to the current event mutably.
339    ///
340    /// If no data of this type is attached to the current event yet, the
341    /// default value is attached.  See [`event`](Self::event) for more
342    /// information.
343    ///
344    /// Event data has to be [`Send`] and [`Sync`] so that it can be captured
345    /// (see [`capture_event_data`](Self::capture_event_data)) without
346    /// preventing the captured data from being shared between threads.
347    ///
348    /// Detached values are retained and reused for later events.  They are
349    /// reset with [`clone_from`](Clone::clone_from) from the default value,
350    /// which means that types which forward `clone_from` to their fields
351    /// (unlike derived implementations of [`Clone`]) reuse the memory of
352    /// collections such as [`Vec`].
353    ///
354    /// ```
355    /// # use deser::State;
356    /// #[derive(Debug, Default, Clone)]
357    /// struct Tags(Vec<u64>);
358    ///
359    /// fn push_tag(state: &mut State, tag: u64) {
360    ///     state.event_mut::<Tags>().0.push(tag);
361    /// }
362    /// ```
363    #[inline]
364    pub fn event_mut<T: Default + Clone + fmt::Debug + Send + Sync + 'static>(&mut self) -> &mut T {
365        self.extensions.event_mut()
366    }
367
368    /// Takes the data of a type from the current event.
369    ///
370    /// Returns `None` if no such data is attached to the event.  Unlike
371    /// resetting the data through [`event_mut`](Self::event_mut) this
372    /// detaches it, so the data is not captured with the event by the sinks
373    /// it's passed on to (such as the ones of a
374    /// [`Recording`](crate::de::Recording)).  This is what types which
375    /// consume event data (like a wrapper which captures a tag) use.
376    ///
377    /// ```
378    /// # use deser::State;
379    /// #[derive(Debug, Default, Clone)]
380    /// struct Tag(String);
381    ///
382    /// fn take_tag(state: &mut State) -> Option<String> {
383    ///     state.take_event::<Tag>().map(|tag| tag.0)
384    /// }
385    /// ```
386    pub fn take_event<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self) -> Option<T> {
387        self.extensions.take_event()
388    }
389
390    /// Captures the data attached to the current event.
391    ///
392    /// The captured data can be attached to another event later with
393    /// [`attach_event_data`](Self::attach_event_data).  This allows types
394    /// which hold values outside of a serialization or deserialization to
395    /// retain data like tags (see [`EventData`]).
396    pub fn capture_event_data(&self) -> EventData {
397        self.extensions.capture_event_data()
398    }
399
400    /// Attaches captured data to the current event.
401    ///
402    /// Data of the same types that is already attached to the event is
403    /// replaced, other data is retained.  See
404    /// [`event`](Self::event) for when event data is attached and detached.
405    pub fn attach_event_data(&mut self, data: &EventData) {
406        self.extensions.attach_event_data(data);
407    }
408
409    /// Detaches all data from the current event.
410    ///
411    /// The drivers call this after every event.
412    #[inline(always)]
413    pub(crate) fn clear_event_data(&mut self) {
414        self.extensions.clear_event_data();
415    }
416
417    /// Returns the current recursion depth.
418    ///
419    /// This is the number of containers (maps and sequences) that are
420    /// currently open.
421    pub fn depth(&self) -> usize {
422        self.depth
423    }
424
425    /// Returns the shape of the container that is started.
426    ///
427    /// During deserialization this is the shape of the
428    /// [`MapStart`](crate::Event::MapStart) or
429    /// [`SeqStart`](crate::Event::SeqStart) event and is intended to be
430    /// called from [`Sink::map`](crate::de::Sink::map) and
431    /// [`Sink::seq`](crate::de::Sink::seq).  At other times it's the shape of
432    /// the container that was started last.
433    pub fn container_shape(&self) -> ContainerShape {
434        self.container_shape
435    }
436
437    /// Returns `true` if the value currently being processed is a map key.
438    ///
439    /// Formats which can only represent string keys (such as JSON) emit
440    /// them as [`Atom::Lexical`](crate::Atom::Lexical), which the sinks of
441    /// the keys parse, so sinks rarely need this.
442    ///
443    /// During serialization this is `true` while a map key (including the
444    /// keys of structs) is serialized and emitted.
445    pub fn is_map_key(&self) -> bool {
446        self.is_map_key
447    }
448
449    /// Returns `true` if the innermost open container is a multimap.
450    ///
451    /// A multimap is a map whose keys can be given more than once (see
452    /// [`ContainerShape::with_multimap`]).  This is the case while its
453    /// keys and values are deserialized and while its sink is finished
454    /// (in [`Sink::finish`](crate::de::Sink::finish)), which includes the
455    /// keys and values that flattened fields take.  Within a nested map or
456    /// sequence it's the flag of that container.
457    ///
458    /// Sinks that collect the values of repeated keys (derived structs and
459    /// maps) check this.
460    #[inline]
461    pub fn is_multimap(&self) -> bool {
462        self.is_multimap
463    }
464
465    /// Returns the byte range in the input of the current event.
466    ///
467    /// This is only available if the format provides it (see
468    /// [`set_input_range`](Self::set_input_range)).  The range refers to
469    /// the [`Source`](crate::Source) and can be resolved into lines and columns for
470    /// instance with the `deser-location` crate.
471    #[inline]
472    pub fn input_range(&self) -> Option<core::ops::Range<usize>> {
473        let (start, end) = self.input_range;
474        if start == NO_RANGE.0 {
475            None
476        } else {
477            Some(start..end)
478        }
479    }
480
481    /// Sets the byte range in the input of the next event.
482    ///
483    /// Formats call this before they emit an event into a
484    /// [`DeserializeDriver`](crate::de::DeserializeDriver).  Like event
485    /// data, the range is only attached to the next event: the driver
486    /// detaches it after the event was delivered.
487    ///
488    /// ```
489    /// use deser::de::DeserializeDriver;
490    ///
491    /// let mut out = None::<bool>;
492    /// let mut driver = DeserializeDriver::new(&mut out);
493    /// driver.state_mut().set_input_range(0, 4);
494    /// driver.emit(true).unwrap();
495    /// assert_eq!(driver.state().input_range(), None);
496    /// ```
497    #[inline(always)]
498    pub fn set_input_range(&mut self, start: usize, end: usize) {
499        self.input_range = (start, end);
500    }
501
502    /// Detaches the input range and the event data from the current event.
503    #[inline(always)]
504    pub(crate) fn clear_event(&mut self) {
505        self.input_range.0 = NO_RANGE.0;
506        self.extensions.clear_event_data();
507    }
508
509    /// Registers a type that adds context to errors.
510    ///
511    /// When an event fails (for instance because a sink rejects a value)
512    /// the drivers invoke [`ErrorContext::add_context`] of the registered
513    /// types in the order they were registered with the error and the
514    /// state as it was when the error happened.  This means that the
515    /// context is also correct for errors in values which are replayed from
516    /// a [`Recording`](crate::de::Recording).  The drivers only do this
517    /// once for an error: the outer containers which the error passes
518    /// through do not add their context.
519    ///
520    /// Registering the same type again has no effect, so this can be
521    /// called for every event.
522    ///
523    /// ```
524    /// use deser::de::DeserializeDriver;
525    /// use deser::{Error, ErrorAttachment, ErrorContext, Event, State};
526    ///
527    /// #[derive(Debug)]
528    /// struct Depth(usize);
529    ///
530    /// impl ErrorAttachment for Depth {}
531    ///
532    /// impl ErrorContext for Depth {
533    ///     fn add_context(err: Error, state: &State) -> Error {
534    ///         match err.attachment::<Depth>() {
535    ///             Some(_) => err,
536    ///             None => err.with_attachment(Depth(state.depth())),
537    ///         }
538    ///     }
539    /// }
540    ///
541    /// let mut out = None::<Vec<Vec<u32>>>;
542    /// let mut driver = DeserializeDriver::new(&mut out);
543    /// driver.state_mut().add_error_context::<Depth>();
544    /// driver.emit(Event::seq_start()).unwrap();
545    /// driver.emit(Event::seq_start()).unwrap();
546    /// let err = driver.emit(true).unwrap_err();
547    /// assert_eq!(err.attachment::<Depth>().unwrap().0, 2);
548    /// ```
549    pub fn add_error_context<T: ErrorContext>(&mut self) {
550        let key = TypeId::of::<T>();
551        if !self.error_context.iter().any(|&(other, _)| other == key) {
552            self.error_context.push((key, T::add_context));
553        }
554    }
555
556    /// Attaches the context of the current event to an error.
557    ///
558    /// The drivers do this for the errors of the events that fail (see
559    /// [`add_error_context`](Self::add_error_context)): the start of the
560    /// input range of the event is attached as offset (unless the error
561    /// has one) and the registered types add their context.  Errors that
562    /// already have the context of an event attached are returned
563    /// unchanged.  This is for sinks that handle the errors of their values
564    /// themselves instead of returning them, so that they have the same
565    /// context as the errors the driver sees.
566    #[cold]
567    #[inline(never)]
568    pub fn attach_error_context(&self, mut err: Error) -> Error {
569        if err.has_context() {
570            return err;
571        }
572        err.set_has_context();
573        if err.offset().is_none()
574            && let Some(range) = self.input_range()
575        {
576            err = err.with_offset(range.start);
577        }
578        for (_, f) in self.error_context.iter() {
579            err = f(err, self);
580        }
581        err
582    }
583}
584
585// the state must never prevent an ongoing serialization or deserialization
586// from moving between threads.
587const _: () = {
588    const fn assert_send_sync<T: Send + Sync>() {}
589    assert_send_sync::<State>();
590};
591
592impl fmt::Debug for State {
593    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594        f.debug_struct("State")
595            .field("extensions", &self.extensions)
596            .field("depth", &self.depth)
597            .field("is_map_key", &self.is_map_key)
598            .field("is_multimap", &self.is_multimap)
599            .field("input_range", &self.input_range())
600            .finish()
601    }
602}