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    #[inline]
328    pub fn take_raw_request(&mut self) -> Option<&'static RawFormatInfo> {
329        self.raw_requested.take()
330    }
331
332    /// Requests the next value as raw value of a format.
333    ///
334    /// Sinks call this while they handle the event before the value that
335    /// deserializes into a [`Raw`](crate::ext::Raw) value (for instance the
336    /// key of the field) and return the result from the event.  If the
337    /// format passes on the input of values of the format (see
338    /// [`declare_raw_format`](Self::declare_raw_format)), the result is the request
339    /// (see [`Error::is_raw_request`]), otherwise the value is deserialized
340    /// from its events.  The drivers pass the request on to the format,
341    /// which emits the next value as [`RawInput`](crate::ext::RawInput).
342    /// Sequences request their first item when they start and every next
343    /// one after an item.  As the request is the result of an event,
344    /// formats do not check for it for every value.
345    ///
346    /// Internal protocol, not public API yet (see `lib.rs`).
347    #[doc(hidden)]
348    #[inline]
349    pub fn __private_request_raw(&mut self, format: &'static RawFormatInfo) -> Result<(), Error> {
350        match self.raw_format {
351            Some(own) if core::ptr::eq(own, format.id()) => {
352                self.raw_requested = Some(format);
353                Err(Error::raw_request())
354            }
355            _ => Ok(()),
356        }
357    }
358
359    /// Returns `true` if the serializer writes raw values of the format as
360    /// they are (see [`declare_raw_format`](Self::declare_raw_format)).
361    #[inline]
362    pub(crate) fn accepts_raw(&self, format: &'static RawFormatInfo) -> bool {
363        self.raw_format
364            .is_some_and(|own| core::ptr::eq(own, format.id()))
365    }
366
367    /// Takes the state out, leaving an empty state that does not allocate.
368    pub(crate) fn take(&mut self) -> State {
369        core::mem::replace(self, State::new())
370    }
371
372    #[inline]
373    pub(crate) fn extensions(&self) -> &Extensions {
374        &self.extensions
375    }
376
377    #[inline]
378    pub(crate) fn extensions_mut(&mut self) -> &mut Extensions {
379        &mut self.extensions
380    }
381
382    /// Returns an extension value.
383    ///
384    /// This is the value set in the state or, if there is none, the value
385    /// of the [context](Self::context).  Returns `None` if neither has a
386    /// value of the type.
387    #[inline]
388    pub fn get<T: fmt::Debug + Send + Sync + 'static>(&self) -> Option<&T> {
389        match self.extensions.get() {
390            Some(value) => Some(value),
391            None => self.context.get(),
392        }
393    }
394
395    /// Sets an extension value unless the state or the context has one.
396    ///
397    /// Formats use this for their defaults of values that are configured
398    /// in the context, for instance query strings use the last of repeated
399    /// keys unless the context has a [`DuplicateKeys`](crate::de::DuplicateKeys)
400    /// policy.
401    pub fn set_default<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self, value: T) {
402        if self.get::<T>().is_none() {
403            *self.get_mut::<T>() = value;
404        }
405    }
406
407    /// Returns the context of the serialization or deserialization.
408    ///
409    /// The context holds the configuration given from the outside, its
410    /// values are the defaults of the extension values (see
411    /// [`get`](Self::get)).
412    #[inline]
413    pub fn context(&self) -> &Context {
414        &self.context
415    }
416
417    /// Sets the context of the serialization or deserialization.
418    ///
419    /// This replaces the context.  The context is usually given to the
420    /// drivers (see
421    /// [`DeserializeDriver::set_context`](crate::de::DeserializeDriver::set_context)
422    /// and [`SerializeDriver::set_context`](crate::ser::SerializeDriver::set_context)),
423    /// which is typically done before the first event.  Only the
424    /// [`DeserializeDriver`](crate::de::DeserializeDriver) enforces the
425    /// [`Limits`](crate::de::Limits) of a context.
426    pub fn set_context(&mut self, context: Context) {
427        if let Some(collect) = context.get::<CollectErrors>() {
428            self.collect_errors = true;
429            self.remaining_errors = collect.max.unwrap_or(usize::MAX);
430            self.error_limit_reached = false;
431        }
432        self.context = context;
433    }
434
435    /// Returns a mutable extension value.
436    ///
437    /// If the value was never set in the state, it's initialized with the
438    /// default value of the type (not the value of the context, which is
439    /// hidden by the value of the state from then on).
440    #[inline]
441    pub fn get_mut<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self) -> &mut T {
442        self.extensions.get_mut()
443    }
444
445    /// Marks an extension type as replayable.
446    ///
447    /// When a value is internally buffered during deserialization (for
448    /// instance for internally tagged enums, see
449    /// [`Recording`](crate::de::Recording)) the values of replayable
450    /// extensions are captured for every event and restored when the event is
451    /// replayed.  This is used for information that changes from event to
452    /// event but remains in the state, such as the current path.  Event data
453    /// is always captured, it does not need to be marked.
454    pub fn set_replayable<T: Clone + Default + fmt::Debug + Send + Sync + 'static>(&mut self) {
455        self.extensions.set_replayable::<T>();
456    }
457
458    /// Returns the data of a type attached to the current event.
459    ///
460    /// Returns `None` if no such data is attached to the event.
461    ///
462    /// Event data is attached to the next event and detached by the driver
463    /// after that event was delivered:
464    ///
465    /// * During deserialization, formats attach data with
466    ///   [`event_mut`](Self::event_mut) before they emit the event with the
467    ///   [`DeserializeDriver`](crate::de::DeserializeDriver).  The sinks
468    ///   that receive the event (including the
469    ///   [`finish`](crate::de::Sink::finish) of a container on its end event)
470    ///   can access it.
471    /// * During serialization, [`Serialize`](crate::ser::Serialize)
472    ///   implementations and emitters attach data while they produce a
473    ///   value.  The format receives it together with the first event of the
474    ///   value from the [`SerializeDriver`](crate::ser::SerializeDriver).
475    ///
476    /// Event data is captured by a [`Recording`](crate::de::Recording) and
477    /// restored when the events are replayed.
478    #[inline(always)]
479    pub fn event<T: fmt::Debug + Send + Sync + 'static>(&self) -> Option<&T> {
480        self.extensions.event()
481    }
482
483    /// Returns the data of a type attached to the current event mutably.
484    ///
485    /// If no data of this type is attached to the current event yet, the
486    /// default value is attached.  See [`event`](Self::event) for more
487    /// information.
488    ///
489    /// Event data has to be [`Send`] and [`Sync`] so that it can be captured
490    /// (see [`capture_event_data`](Self::capture_event_data)) without
491    /// preventing the captured data from being shared between threads.
492    ///
493    /// Detached values are retained and reused for later events.  They are
494    /// reset with [`clone_from`](Clone::clone_from) from the default value,
495    /// which means that types which forward `clone_from` to their fields
496    /// (unlike derived implementations of [`Clone`]) reuse the memory of
497    /// collections such as [`Vec`].
498    ///
499    /// ```
500    /// # use deser::State;
501    /// #[derive(Debug, Default, Clone)]
502    /// struct Tags(Vec<u64>);
503    ///
504    /// fn push_tag(state: &mut State, tag: u64) {
505    ///     state.event_mut::<Tags>().0.push(tag);
506    /// }
507    /// ```
508    #[inline]
509    pub fn event_mut<T: Default + Clone + fmt::Debug + Send + Sync + 'static>(&mut self) -> &mut T {
510        self.extensions.event_mut()
511    }
512
513    /// Takes the data of a type from the current event.
514    ///
515    /// Returns `None` if no such data is attached to the event.  Unlike
516    /// resetting the data through [`event_mut`](Self::event_mut) this
517    /// detaches it, so the data is not captured with the event by the sinks
518    /// it's passed on to (such as the ones of a
519    /// [`Recording`](crate::de::Recording)).  This is what types which
520    /// consume event data (like a wrapper which captures a tag) use.
521    ///
522    /// ```
523    /// # use deser::State;
524    /// #[derive(Debug, Default, Clone)]
525    /// struct Tag(String);
526    ///
527    /// fn take_tag(state: &mut State) -> Option<String> {
528    ///     state.take_event::<Tag>().map(|tag| tag.0)
529    /// }
530    /// ```
531    pub fn take_event<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self) -> Option<T> {
532        self.extensions.take_event()
533    }
534
535    /// Captures the data attached to the current event.
536    ///
537    /// The captured data can be attached to another event later with
538    /// [`attach_event_data`](Self::attach_event_data).  This allows types
539    /// which hold values outside of a serialization or deserialization to
540    /// retain data like tags (see [`EventData`]).
541    pub fn capture_event_data(&self) -> EventData {
542        self.extensions.capture_event_data()
543    }
544
545    /// Attaches captured data to the current event.
546    ///
547    /// Data of the same types that is already attached to the event is
548    /// replaced, other data is retained.  See
549    /// [`event`](Self::event) for when event data is attached and detached.
550    pub fn attach_event_data(&mut self, data: &EventData) {
551        self.extensions.attach_event_data(data);
552    }
553
554    /// Detaches all data from the current event.
555    ///
556    /// The drivers call this after every event.
557    #[inline(always)]
558    pub(crate) fn clear_event_data(&mut self) {
559        self.extensions.clear_event_data();
560    }
561
562    /// Returns the current recursion depth.
563    ///
564    /// This is the number of containers (maps and sequences) that are
565    /// currently open.
566    pub fn depth(&self) -> usize {
567        self.depth
568    }
569
570    /// Returns the shape of the container that is started.
571    ///
572    /// During deserialization this is the shape of the
573    /// [`MapStart`](crate::Event::MapStart) or
574    /// [`SeqStart`](crate::Event::SeqStart) event and is intended to be
575    /// called from [`Sink::map`](crate::de::Sink::map) and
576    /// [`Sink::seq`](crate::de::Sink::seq).  At other times it's the shape of
577    /// the container that was started last.
578    pub fn container_shape(&self) -> ContainerShape {
579        self.container_shape
580    }
581
582    /// Returns `true` if the value currently being processed is a map key.
583    ///
584    /// Formats which can only represent string keys (such as JSON) emit
585    /// them as [`Atom::Lexical`](crate::Atom::Lexical), which the sinks of
586    /// the keys parse, so sinks rarely need this.
587    ///
588    /// During serialization this is `true` while a map key (including the
589    /// keys of structs) is serialized and emitted.
590    pub fn is_map_key(&self) -> bool {
591        self.is_map_key
592    }
593
594    /// Returns `true` if the innermost open container is a multimap.
595    ///
596    /// A multimap is a map whose keys can be given more than once (see
597    /// [`ContainerShape::set_multimap`]).  This is the case while its
598    /// keys and values are deserialized and while its sink is finished
599    /// (in [`Sink::finish`](crate::de::Sink::finish)), which includes the
600    /// keys and values that flattened fields take.  Within a nested map or
601    /// sequence it's the flag of that container.
602    ///
603    /// Sinks that collect the values of repeated keys (derived structs and
604    /// maps) check this.
605    #[inline]
606    pub fn is_multimap(&self) -> bool {
607        self.is_multimap
608    }
609
610    /// Returns the byte range in the input of the current event.
611    ///
612    /// This is only available if the format provides it (see
613    /// [`set_input_range`](Self::set_input_range)).  The range refers to
614    /// the [`Source`](crate::Source) and can be resolved into lines and columns for
615    /// instance with the `deser-location` crate.
616    #[inline]
617    pub fn input_range(&self) -> Option<core::ops::Range<usize>> {
618        let (start, end) = self.input_range;
619        if start == NO_RANGE.0 {
620            None
621        } else {
622            Some(start..end)
623        }
624    }
625
626    /// Sets the byte range in the input of the next event.
627    ///
628    /// Formats call this before they emit an event into a
629    /// [`DeserializeDriver`](crate::de::DeserializeDriver).  Like event
630    /// data, the range is only attached to the next event: the driver
631    /// detaches it after the event was delivered.
632    ///
633    /// ```
634    /// use deser::de::DeserializeDriver;
635    ///
636    /// let mut out = None::<bool>;
637    /// let mut driver = DeserializeDriver::new(&mut out);
638    /// driver.state_mut().set_input_range(0, 4);
639    /// driver.emit(true).unwrap();
640    /// assert_eq!(driver.state().input_range(), None);
641    /// ```
642    #[inline(always)]
643    pub fn set_input_range(&mut self, start: usize, end: usize) {
644        self.input_range = (start, end);
645    }
646
647    /// Detaches the input range and the event data from the current event.
648    #[inline(always)]
649    pub(crate) fn clear_event(&mut self) {
650        self.input_range.0 = NO_RANGE.0;
651        self.extensions.clear_event_data();
652    }
653
654    /// Registers a type that adds context to errors.
655    ///
656    /// When an event fails (for instance because a sink rejects a value)
657    /// the drivers invoke [`ErrorContext::add_context`] of the registered
658    /// types in the order they were registered with the error and the
659    /// state as it was when the error happened.  This means that the
660    /// context is also correct for errors in values which are replayed from
661    /// a [`Recording`](crate::de::Recording).  The drivers only do this
662    /// once for an error: the outer containers which the error passes
663    /// through do not add their context.
664    ///
665    /// Registering the same type again has no effect, so this can be
666    /// called for every event.
667    ///
668    /// ```
669    /// use deser::de::DeserializeDriver;
670    /// use deser::{Error, ErrorAttachment, ErrorContext, Event, State};
671    ///
672    /// #[derive(Debug)]
673    /// struct Depth(usize);
674    ///
675    /// impl ErrorAttachment for Depth {}
676    ///
677    /// impl ErrorContext for Depth {
678    ///     fn add_context(err: &mut Error, state: &State) {
679    ///         if err.attachment::<Depth>().is_none() {
680    ///             err.set_attachment(Depth(state.depth()));
681    ///         }
682    ///     }
683    /// }
684    ///
685    /// let mut out = None::<Vec<Vec<u32>>>;
686    /// let mut driver = DeserializeDriver::new(&mut out);
687    /// driver.state_mut().add_error_context::<Depth>();
688    /// driver.emit(Event::seq_start()).unwrap();
689    /// driver.emit(Event::seq_start()).unwrap();
690    /// let err = driver.emit(true).unwrap_err();
691    /// assert_eq!(err.attachment::<Depth>().unwrap().0, 2);
692    /// ```
693    pub fn add_error_context<T: ErrorContext>(&mut self) {
694        let key = TypeId::of::<T>();
695        if !self.error_context.iter().any(|&(other, _)| other == key) {
696            self.error_context.push((key, T::add_context));
697        }
698    }
699
700    /// Attaches the context of the current event to an error.
701    ///
702    /// The drivers do this for the errors of the events that fail (see
703    /// [`add_error_context`](Self::add_error_context)): the start of the
704    /// input range of the event is attached as offset (unless the error
705    /// has one) and the registered types add their context.  Errors that
706    /// already have the context of an event attached are not changed.
707    /// This is for sinks that handle the errors of their values
708    /// themselves instead of returning them, so that they have the same
709    /// context as the errors the driver sees.
710    #[inline]
711    pub fn attach_error_context(&self, err: &mut Error) {
712        self.attach_error_context_impl(err)
713    }
714
715    /// Returns an error with the context of the current event attached (see
716    /// [`attach_error_context`](Self::attach_error_context)).
717    #[inline]
718    pub(crate) fn error_in_context(&self, mut err: Error) -> Error {
719        self.attach_error_context_impl(&mut err);
720        err
721    }
722
723    #[cold]
724    #[inline(never)]
725    fn attach_error_context_impl(&self, err: &mut Error) {
726        if err.has_context() {
727            return;
728        }
729        err.set_has_context();
730        if err.offset().is_none()
731            && let Some(range) = self.input_range()
732        {
733            err.set_offset(range.start);
734        }
735        for (_, f) in self.error_context.iter() {
736            f(err, self);
737        }
738    }
739}
740
741// the state must never prevent an ongoing serialization or deserialization
742// from moving between threads.
743const _: () = {
744    const fn assert_send_sync<T: Send + Sync>() {}
745    assert_send_sync::<State>();
746};
747
748impl fmt::Debug for State {
749    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
750        f.debug_struct("State")
751            .field("extensions", &self.extensions)
752            .field("depth", &self.depth)
753            .field("is_map_key", &self.is_map_key)
754            .field("is_multimap", &self.is_multimap)
755            .field("input_range", &self.input_range())
756            .finish()
757    }
758}