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