deser-core 0.10.1

Core traits and types of deser, use the deser crate instead
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! The state shared between data formats and the types they process.
use alloc::vec::Vec;
use core::any::TypeId;
use core::fmt;

use crate::Context;
use crate::arena::{Arena, Buffer};
use crate::de::CollectErrors;
use crate::error::{Error, ErrorContext};
use crate::event::ContainerShape;
use crate::ext::{RawFormatId, RawFormatInfo};
use crate::extensions::{EventData, Extensions};

/// The input range of events without one.
pub(crate) const NO_RANGE: (usize, usize) = (usize::MAX, 0);

/// Gives access to the state of an ongoing serialization or deserialization.
///
/// The state acts as a communication channel between the data format and
/// the types that are serialized or deserialized.  It is used in both
/// directions: [`Deserialize`](crate::de::Deserialize) implementations and
/// [`Sink`](crate::de::Sink)s receive it during deserialization and
/// [`Serialize`](crate::ser::Serialize) implementations and emitters
/// receive it during serialization.  Formats get mutable access to it through
/// the drivers.  The state also holds the arena the sinks and emitters are
/// allocated in (see [`SinkHandle::arena`](crate::de::SinkHandle::arena)
/// and [`Emit::seq`](crate::ser::Emit::seq)).
///
/// Besides some information about the current position (such as the
/// [`depth`](Self::depth)) it holds typed values that can be used by formats
/// and types to exchange information that is not part of the data model:
///
/// * Extension values ([`get`](Self::get) and [`get_mut`](Self::get_mut))
///   remain in the state until they are changed.  They are used for
///   information that spans many events such as the current path.
/// * Event data ([`event`](Self::event) and [`event_mut`](Self::event_mut))
///   is attached to a single event and detached by the drivers after the
///   event was delivered.  It is used for information about an individual
///   value, such as a tag.
///
/// Some extension values are well-known: the policy for keys that are
/// given more than once ([`DuplicateKeys`](crate::de::DuplicateKeys)),
/// the policy for keys that no field of a struct takes
/// ([`UnknownFields`](crate::de::UnknownFields)), how bytes are decoded
/// from strings ([`BytesFormat`](crate::BytesFormat)) and the source the
/// input ranges refer to ([`Source`](crate::Source)).  They are read and
/// set with their `of` and `set` functions.
///
/// Additionally formats can publish the byte range in the input of every
/// event (see [`input_range`](Self::input_range)) and extensions can
/// register types that add context to errors (see
/// [`add_error_context`](Self::add_error_context)).
///
/// The extension values default to the values of the [`Context`] of the
/// serialization or deserialization (see [`set_context`](Self::set_context)):
/// the context is the configuration given from the outside, the state holds
/// what changes while values are processed.
///
/// Extension values have to be [`Send`] and [`Sync`] so that the state is
/// too.  This means that the state never prevents an ongoing serialization
/// or deserialization from moving between threads.  They are `Sync` as
/// event data is recorded (see [`Recording`](crate::de::Recording)) and
/// recordings can be serialized.
pub struct State {
    extensions: Extensions,
    // the defaults of the extension values
    context: Context,
    // the number of open containers
    pub(crate) depth: usize,
    // the shape of the container that is currently started
    pub(crate) container_shape: ContainerShape,
    pub(crate) is_map_key: bool,
    // `true` if the innermost open container is a multimap
    pub(crate) is_multimap: bool,
    // the key of the content of maps, empty if there is none (see
    // `ContentKey`)
    pub(crate) content_key: &'static str,
    // the byte range of the current event, `NO_RANGE` if there is none.
    // This is not an option so that it can be cleared with a single store.
    pub(crate) input_range: (usize, usize),
    // keyed by type as function pointers cannot be compared reliably
    error_context: Vec<(TypeId, AddContextFn)>,
    // `true` while errors are thrown away, see `discard_errors`.
    pub(crate) discards_errors: bool,
    // `true` if containers collect the errors of their items, see
    // `set_collect_errors`.
    collect_errors: bool,
    // the number of errors that can still be collected
    remaining_errors: usize,
    // `true` once an error was not collected because of the limit
    error_limit_reached: bool,
    // the arena the sinks of the deserialization are allocated in
    pub(crate) arena: Arena,
    // the format of the raw values that pass through as they are (see
    // `declare_raw_format`)
    pub(crate) raw_format: Option<&'static RawFormatId>,
    // deserialization: the next value (or the top-level value) is wanted
    // as raw value of the format (see `declare_raw_format` and
    // `take_raw_request`)
    pub(crate) raw_requested: Option<&'static RawFormatInfo>,
}

/// The function of an [`ErrorContext`].
type AddContextFn = fn(&mut Error, &State);

impl State {
    /// Creates an empty state.
    ///
    /// Drivers create their state, this is useful for code that processes
    /// events without a driver.
    #[allow(clippy::new_without_default)]
    pub fn new() -> State {
        State {
            extensions: Extensions::default(),
            context: Context::new(),
            depth: 0,
            container_shape: ContainerShape::new(),
            is_map_key: false,
            is_multimap: false,
            content_key: "",
            input_range: NO_RANGE,
            error_context: Vec::new(),
            discards_errors: false,
            collect_errors: false,
            remaining_errors: usize::MAX,
            error_limit_reached: false,
            arena: Arena::new(),
            raw_format: None,
            raw_requested: None,
        }
    }

    /// Sets if maps and sequences collect the errors of their items.
    ///
    /// By default the first error ends the deserialization.  If errors are
    /// collected, the sinks of the containers that support it (derived
    /// structs and the standard collections) recover from the errors of
    /// their items (see [`Sink::recover`](crate::de::Sink::recover)) and
    /// deserialization continues to find the other errors.  The container
    /// fails once it's complete with all errors it collected (see
    /// [`Error::errors`]), including the fields that are missing.  This
    /// makes it possible to report all problems of the input at once:
    ///
    /// ```
    /// use deser::de::Deserializer;
    /// use deser::Deserialize;
    ///
    /// #[derive(Deserialize, Debug)]
    /// struct Server {
    ///     host: String,
    ///     port: u16,
    /// }
    ///
    /// let input = r#"[
    ///     {"host": 42, "port": 80},
    ///     {"host": "b", "port": "http"},
    ///     {}
    /// ]"#;
    /// let err = deser_json::Deserializer::from_str(input)
    ///     .deserialize_with::<Vec<Server>, _>(|driver| {
    ///         driver.state_mut().set_collect_errors(true)
    ///     })
    ///     .unwrap_err();
    /// let errors: Vec<_> = err.errors().map(|err| err.message()).collect();
    /// assert_eq!(
    ///     errors,
    ///     [
    ///         "unexpected unsigned integer, expected string",
    ///         "unexpected string, expected u16",
    ///         "missing field `host`",
    ///         "missing field `port`",
    ///     ]
    /// );
    /// ```
    ///
    /// Errors can also be collected for a whole deserialization by placing
    /// [`CollectErrors`] in the [context](Self::set_context), which is how
    /// this is usually configured from the outside.
    ///
    /// Types can change this for the values in them, for instance to
    /// collect the errors of a part of the input (and restore the previous
    /// setting, see [`collect_errors`](Self::collect_errors), afterwards).  While errors are thrown away (for instance while an
    /// untagged enum tries its variants) they are never collected.  See
    /// [`set_max_errors`](Self::set_max_errors) to limit the number of
    /// errors that are collected.
    pub fn set_collect_errors(&mut self, yes: bool) {
        self.collect_errors = yes;
    }

    /// Returns `true` if maps and sequences are set to collect the errors
    /// of their items (see [`set_collect_errors`](Self::set_collect_errors)).
    ///
    /// This is the setting, see [`collects_errors`](Self::collects_errors)
    /// for whether errors are collected at the moment.
    pub fn collect_errors(&self) -> bool {
        self.collect_errors
    }

    /// Returns `true` if the errors of items are collected.
    ///
    /// See [`set_collect_errors`](Self::set_collect_errors).
    pub fn collects_errors(&self) -> bool {
        self.collect_errors && !self.discards_errors
    }

    /// Limits the number of errors that are collected.
    ///
    /// Once the limit is reached, the next error ends the deserialization
    /// (together with the errors collected so far).  By default there is no
    /// limit.  This counts from the current number of collected errors.
    pub fn set_max_errors(&mut self, max: usize) {
        self.remaining_errors = max;
        self.error_limit_reached = false;
    }

    /// Returns `true` once the limit of errors was reached.
    ///
    /// The error that exceeded the limit (see
    /// [`set_max_errors`](Self::set_max_errors)) ends the deserialization.
    /// Sinks that keep the errors of their values instead of returning
    /// them should return errors once this is set.
    pub fn error_limit_reached(&self) -> bool {
        self.error_limit_reached
    }

    /// Takes a number of the errors that can still be collected.
    ///
    /// Returns `false` if errors are not collected or the limit is reached.
    pub(crate) fn take_error_slots(&mut self, count: usize) -> bool {
        if !self.collects_errors() {
            false
        } else if self.remaining_errors >= count {
            self.remaining_errors -= count;
            true
        } else {
            self.error_limit_reached = true;
            false
        }
    }

    /// Returns `true` while errors are thrown away.
    ///
    /// While an untagged enum tries its variants only whether a variant
    /// accepts the value matters.  The errors are created without a message
    /// then, and the driver does not attach context to them.  Sinks that
    /// keep the errors of their values (instead of returning them) should
    /// return them while this is set.
    pub fn discards_errors(&self) -> bool {
        self.discards_errors
    }

    /// Runs a function during which errors are thrown away.
    ///
    /// This is used while an untagged enum tries its variants: only whether
    /// a variant accepts the value matters, so the errors that are returned
    /// are created without a message (see
    /// [`discarded_error`](crate::error::discarded_error)) and the driver
    /// does not attach context to them.  Errors that are kept rather than
    /// returned (for instance collected unknown fields) are unaffected.
    pub(crate) fn discard_errors<R>(&mut self, f: impl FnOnce(&mut State) -> R) -> R {
        let outer = core::mem::replace(&mut self.discards_errors, true);
        let rv = f(self);
        self.discards_errors = outer;
        rv
    }

    /// Takes the scratch space of a format that was kept from the last
    /// deserialization (see
    /// [`__private_put_scratch`](Self::__private_put_scratch)).
    ///
    /// Internal fast path, not public API (see `lib.rs`).
    #[doc(hidden)]
    #[inline]
    pub fn __private_take_scratch(&mut self) -> Vec<u8> {
        self.arena.take_vec(Buffer::Scratch).unwrap_or_default()
    }

    /// Keeps the scratch space of a format for the next deserialization.
    ///
    /// Formats that unescape strings into a buffer would otherwise grow it
    /// again for every document.  The buffer is cleared.
    ///
    /// Internal fast path, not public API (see `lib.rs`).
    #[doc(hidden)]
    #[inline]
    pub fn __private_put_scratch(&mut self, buffer: Vec<u8>) {
        self.arena.put_vec(Buffer::Scratch, buffer);
    }

    /// Declares the format of the raw values that pass through as they are.
    ///
    /// Formats with raw values (see [`Raw`](crate::ext::Raw)) call this with
    /// the identity of their format:
    ///
    /// * Deserializers call it before they emit the first event.  Sinks
    ///   then request values that deserialize into raw values of the format
    ///   (see [`Error::is_raw_request`]) and the format passes on their
    ///   input as [`RawInput`](crate::ext::RawInput) rather than their
    ///   events.  The top-level value is requested before the
    ///   deserialization starts: if it's wanted as raw value, this returns
    ///   the description of the format the raw value wants, which the
    ///   input is emitted with.  Only the first call can return it.
    /// * Serializers call it before the first value and ignore the result.
    ///   Raw values of the format are then emitted as
    ///   [`RawInput`](crate::ext::RawInput), which the serializer writes as
    ///   it is.  Raw values of other formats are serialized as the values
    ///   they hold.
    #[inline(always)]
    pub fn declare_raw_format(
        &mut self,
        format: &'static RawFormatId,
    ) -> Option<&'static RawFormatInfo> {
        self.raw_format = Some(format);
        self.raw_requested
            .take()
            .filter(|requested| core::ptr::eq(requested.id(), format))
    }

    /// Takes the description of the format of the raw value that the
    /// result of an event requested (see [`Error::is_raw_request`]).
    ///
    /// Formats emit the input of the value with it (see
    /// [`RawInput::new`](crate::ext::RawInput::new)): it's the description
    /// of their own format, but as it comes from the raw value the
    /// functions of the format are only in programs that use its raw
    /// values.
    ///
    /// The description is not guaranteed to be the one of the caller's
    /// format: what is declared with
    /// [`declare_raw_format`](Self::declare_raw_format) can be changed by
    /// everything that has access to the state, and descriptions can be
    /// created with the identity of any format.  Formats check its
    /// [`id`](crate::ext::RawFormatInfo::id) before they emit their input
    /// with it.
    #[inline]
    pub fn take_raw_request(&mut self) -> Option<&'static RawFormatInfo> {
        self.raw_requested.take()
    }

    /// Requests the next value as raw value of a format.
    ///
    /// Sinks call this while they handle the event before the value that
    /// deserializes into a [`Raw`](crate::ext::Raw) value (for instance the
    /// key of the field) and return the result from the event.  If the
    /// format passes on the input of values of the format (see
    /// [`declare_raw_format`](Self::declare_raw_format)), the result is the request
    /// (see [`Error::is_raw_request`]), otherwise the value is deserialized
    /// from its events.  The drivers pass the request on to the format,
    /// which emits the next value as [`RawInput`](crate::ext::RawInput).
    /// Sequences request their first item when they start and every next
    /// one after an item.  As the request is the result of an event,
    /// formats do not check for it for every value.
    ///
    /// Internal protocol, not public API yet (see `lib.rs`).
    #[doc(hidden)]
    #[inline]
    pub fn __private_request_raw(&mut self, format: &'static RawFormatInfo) -> Result<(), Error> {
        match self.raw_format {
            Some(own) if core::ptr::eq(own, format.id()) => {
                self.raw_requested = Some(format);
                Err(Error::raw_request())
            }
            _ => Ok(()),
        }
    }

    /// Returns `true` if the serializer writes raw values of the format as
    /// they are (see [`declare_raw_format`](Self::declare_raw_format)).
    #[inline]
    pub(crate) fn accepts_raw(&self, format: &'static RawFormatInfo) -> bool {
        self.raw_format
            .is_some_and(|own| core::ptr::eq(own, format.id()))
    }

    /// Takes the state out, leaving an empty state that does not allocate.
    pub(crate) fn take(&mut self) -> State {
        core::mem::replace(self, State::new())
    }

    #[inline]
    pub(crate) fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    #[inline]
    pub(crate) fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }

    /// Returns an extension value.
    ///
    /// This is the value set in the state or, if there is none, the value
    /// of the [context](Self::context).  Returns `None` if neither has a
    /// value of the type.
    #[inline]
    pub fn get<T: fmt::Debug + Send + Sync + 'static>(&self) -> Option<&T> {
        match self.extensions.get() {
            Some(value) => Some(value),
            None => self.context.get(),
        }
    }

    /// Sets an extension value unless the state or the context has one.
    ///
    /// Formats use this for their defaults of values that are configured
    /// in the context, for instance query strings use the last of repeated
    /// keys unless the context has a [`DuplicateKeys`](crate::de::DuplicateKeys)
    /// policy.
    pub fn set_default<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self, value: T) {
        if self.get::<T>().is_none() {
            *self.get_mut::<T>() = value;
        }
    }

    /// Returns the context of the serialization or deserialization.
    ///
    /// The context holds the configuration given from the outside, its
    /// values are the defaults of the extension values (see
    /// [`get`](Self::get)).
    #[inline]
    pub fn context(&self) -> &Context {
        &self.context
    }

    /// Sets the context of the serialization or deserialization.
    ///
    /// This replaces the context.  The context is usually given to the
    /// drivers (see
    /// [`DeserializeDriver::set_context`](crate::de::DeserializeDriver::set_context)
    /// and [`SerializeDriver::set_context`](crate::ser::SerializeDriver::set_context)),
    /// which is typically done before the first event.  Only the
    /// [`DeserializeDriver`](crate::de::DeserializeDriver) enforces the
    /// [`Limits`](crate::de::Limits) of a context.
    pub fn set_context(&mut self, context: Context) {
        if let Some(collect) = context.get::<CollectErrors>() {
            self.collect_errors = true;
            self.remaining_errors = collect.max.unwrap_or(usize::MAX);
            self.error_limit_reached = false;
        }
        self.context = context;
    }

    /// Returns a mutable extension value.
    ///
    /// If the value was never set in the state, it's initialized with the
    /// default value of the type (not the value of the context, which is
    /// hidden by the value of the state from then on).
    #[inline]
    pub fn get_mut<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self) -> &mut T {
        self.extensions.get_mut()
    }

    /// Marks an extension type as replayable.
    ///
    /// When a value is internally buffered during deserialization (for
    /// instance for internally tagged enums, see
    /// [`Recording`](crate::de::Recording)) the values of replayable
    /// extensions are captured for every event and restored when the event is
    /// replayed.  This is used for information that changes from event to
    /// event but remains in the state, such as the current path.  Event data
    /// is always captured, it does not need to be marked.
    pub fn set_replayable<T: Clone + Default + fmt::Debug + Send + Sync + 'static>(&mut self) {
        self.extensions.set_replayable::<T>();
    }

    /// Returns the data of a type attached to the current event.
    ///
    /// Returns `None` if no such data is attached to the event.
    ///
    /// Event data is attached to the next event and detached by the driver
    /// after that event was delivered:
    ///
    /// * During deserialization, formats attach data with
    ///   [`event_mut`](Self::event_mut) before they emit the event with the
    ///   [`DeserializeDriver`](crate::de::DeserializeDriver).  The sinks
    ///   that receive the event (including the
    ///   [`finish`](crate::de::Sink::finish) of a container on its end event)
    ///   can access it.
    /// * During serialization, [`Serialize`](crate::ser::Serialize)
    ///   implementations and emitters attach data while they produce a
    ///   value.  The format receives it together with the first event of the
    ///   value from the [`SerializeDriver`](crate::ser::SerializeDriver).
    ///
    /// Event data is captured by a [`Recording`](crate::de::Recording) and
    /// restored when the events are replayed.
    #[inline(always)]
    pub fn event<T: fmt::Debug + Send + Sync + 'static>(&self) -> Option<&T> {
        self.extensions.event()
    }

    /// Returns the data of a type attached to the current event mutably.
    ///
    /// If no data of this type is attached to the current event yet, the
    /// default value is attached.  See [`event`](Self::event) for more
    /// information.
    ///
    /// Event data has to be [`Send`] and [`Sync`] so that it can be captured
    /// (see [`capture_event_data`](Self::capture_event_data)) without
    /// preventing the captured data from being shared between threads.
    ///
    /// Detached values are retained and reused for later events.  They are
    /// reset with [`clone_from`](Clone::clone_from) from the default value,
    /// which means that types which forward `clone_from` to their fields
    /// (unlike derived implementations of [`Clone`]) reuse the memory of
    /// collections such as [`Vec`].
    ///
    /// ```
    /// # use deser::State;
    /// #[derive(Debug, Default, Clone)]
    /// struct Tags(Vec<u64>);
    ///
    /// fn push_tag(state: &mut State, tag: u64) {
    ///     state.event_mut::<Tags>().0.push(tag);
    /// }
    /// ```
    #[inline]
    pub fn event_mut<T: Default + Clone + fmt::Debug + Send + Sync + 'static>(&mut self) -> &mut T {
        self.extensions.event_mut()
    }

    /// Takes the data of a type from the current event.
    ///
    /// Returns `None` if no such data is attached to the event.  Unlike
    /// resetting the data through [`event_mut`](Self::event_mut) this
    /// detaches it, so the data is not captured with the event by the sinks
    /// it's passed on to (such as the ones of a
    /// [`Recording`](crate::de::Recording)).  This is what types which
    /// consume event data (like a wrapper which captures a tag) use.
    ///
    /// ```
    /// # use deser::State;
    /// #[derive(Debug, Default, Clone)]
    /// struct Tag(String);
    ///
    /// fn take_tag(state: &mut State) -> Option<String> {
    ///     state.take_event::<Tag>().map(|tag| tag.0)
    /// }
    /// ```
    pub fn take_event<T: Default + fmt::Debug + Send + Sync + 'static>(&mut self) -> Option<T> {
        self.extensions.take_event()
    }

    /// Captures the data attached to the current event.
    ///
    /// The captured data can be attached to another event later with
    /// [`attach_event_data`](Self::attach_event_data).  This allows types
    /// which hold values outside of a serialization or deserialization to
    /// retain data like tags (see [`EventData`]).
    pub fn capture_event_data(&self) -> EventData {
        self.extensions.capture_event_data()
    }

    /// Attaches captured data to the current event.
    ///
    /// Data of the same types that is already attached to the event is
    /// replaced, other data is retained.  See
    /// [`event`](Self::event) for when event data is attached and detached.
    pub fn attach_event_data(&mut self, data: &EventData) {
        self.extensions.attach_event_data(data);
    }

    /// Detaches all data from the current event.
    ///
    /// The drivers call this after every event.
    #[inline(always)]
    pub(crate) fn clear_event_data(&mut self) {
        self.extensions.clear_event_data();
    }

    /// Returns the current recursion depth.
    ///
    /// This is the number of containers (maps and sequences) that are
    /// currently open.
    pub fn depth(&self) -> usize {
        self.depth
    }

    /// Returns the shape of the container that is started.
    ///
    /// During deserialization this is the shape of the
    /// [`MapStart`](crate::Event::MapStart) or
    /// [`SeqStart`](crate::Event::SeqStart) event and is intended to be
    /// called from [`Sink::map`](crate::de::Sink::map) and
    /// [`Sink::seq`](crate::de::Sink::seq).  At other times it's the shape of
    /// the container that was started last.
    pub fn container_shape(&self) -> ContainerShape {
        self.container_shape
    }

    /// Returns `true` if the value currently being processed is a map key.
    ///
    /// Formats which can only represent string keys (such as JSON) emit
    /// them as [`Atom::Lexical`](crate::Atom::Lexical), which the sinks of
    /// the keys parse, so sinks rarely need this.
    ///
    /// During serialization this is `true` while a map key (including the
    /// keys of structs) is serialized and emitted.
    pub fn is_map_key(&self) -> bool {
        self.is_map_key
    }

    /// Returns `true` if the innermost open container is a multimap.
    ///
    /// A multimap is a map whose keys can be given more than once (see
    /// [`ContainerShape::set_multimap`]).  This is the case while its
    /// keys and values are deserialized and while its sink is finished
    /// (in [`Sink::finish`](crate::de::Sink::finish)), which includes the
    /// keys and values that flattened fields take.  Within a nested map or
    /// sequence it's the flag of that container.
    ///
    /// Sinks that collect the values of repeated keys (derived structs and
    /// maps) check this.
    #[inline]
    pub fn is_multimap(&self) -> bool {
        self.is_multimap
    }

    /// Returns the byte range in the input of the current event.
    ///
    /// This is only available if the format provides it (see
    /// [`set_input_range`](Self::set_input_range)).  The range refers to
    /// the [`Source`](crate::Source) and can be resolved into lines and columns for
    /// instance with the `deser-location` crate.
    #[inline]
    pub fn input_range(&self) -> Option<core::ops::Range<usize>> {
        let (start, end) = self.input_range;
        if start == NO_RANGE.0 {
            None
        } else {
            Some(start..end)
        }
    }

    /// Sets the byte range in the input of the next event.
    ///
    /// Formats call this before they emit an event into a
    /// [`DeserializeDriver`](crate::de::DeserializeDriver).  Like event
    /// data, the range is only attached to the next event: the driver
    /// detaches it after the event was delivered.
    ///
    /// ```
    /// use deser::de::DeserializeDriver;
    ///
    /// let mut out = None::<bool>;
    /// let mut driver = DeserializeDriver::new(&mut out);
    /// driver.state_mut().set_input_range(0, 4);
    /// driver.emit(true).unwrap();
    /// assert_eq!(driver.state().input_range(), None);
    /// ```
    #[inline(always)]
    pub fn set_input_range(&mut self, start: usize, end: usize) {
        self.input_range = (start, end);
    }

    /// Detaches the input range and the event data from the current event.
    #[inline(always)]
    pub(crate) fn clear_event(&mut self) {
        self.input_range.0 = NO_RANGE.0;
        self.extensions.clear_event_data();
    }

    /// Registers a type that adds context to errors.
    ///
    /// When an event fails (for instance because a sink rejects a value)
    /// the drivers invoke [`ErrorContext::add_context`] of the registered
    /// types in the order they were registered with the error and the
    /// state as it was when the error happened.  This means that the
    /// context is also correct for errors in values which are replayed from
    /// a [`Recording`](crate::de::Recording).  The drivers only do this
    /// once for an error: the outer containers which the error passes
    /// through do not add their context.
    ///
    /// Registering the same type again has no effect, so this can be
    /// called for every event.
    ///
    /// ```
    /// use deser::de::DeserializeDriver;
    /// use deser::{Error, ErrorAttachment, ErrorContext, Event, State};
    ///
    /// #[derive(Debug)]
    /// struct Depth(usize);
    ///
    /// impl ErrorAttachment for Depth {}
    ///
    /// impl ErrorContext for Depth {
    ///     fn add_context(err: &mut Error, state: &State) {
    ///         if err.attachment::<Depth>().is_none() {
    ///             err.set_attachment(Depth(state.depth()));
    ///         }
    ///     }
    /// }
    ///
    /// let mut out = None::<Vec<Vec<u32>>>;
    /// let mut driver = DeserializeDriver::new(&mut out);
    /// driver.state_mut().add_error_context::<Depth>();
    /// driver.emit(Event::seq_start()).unwrap();
    /// driver.emit(Event::seq_start()).unwrap();
    /// let err = driver.emit(true).unwrap_err();
    /// assert_eq!(err.attachment::<Depth>().unwrap().0, 2);
    /// ```
    pub fn add_error_context<T: ErrorContext>(&mut self) {
        let key = TypeId::of::<T>();
        if !self.error_context.iter().any(|&(other, _)| other == key) {
            self.error_context.push((key, T::add_context));
        }
    }

    /// Attaches the context of the current event to an error.
    ///
    /// The drivers do this for the errors of the events that fail (see
    /// [`add_error_context`](Self::add_error_context)): the start of the
    /// input range of the event is attached as offset (unless the error
    /// has one) and the registered types add their context.  Errors that
    /// already have the context of an event attached are not changed.
    /// This is for sinks that handle the errors of their values
    /// themselves instead of returning them, so that they have the same
    /// context as the errors the driver sees.
    #[inline]
    pub fn attach_error_context(&self, err: &mut Error) {
        self.attach_error_context_impl(err)
    }

    /// Returns an error with the context of the current event attached (see
    /// [`attach_error_context`](Self::attach_error_context)).
    #[inline]
    pub(crate) fn error_in_context(&self, mut err: Error) -> Error {
        self.attach_error_context_impl(&mut err);
        err
    }

    #[cold]
    #[inline(never)]
    fn attach_error_context_impl(&self, err: &mut Error) {
        if err.has_context() {
            return;
        }
        err.set_has_context();
        if err.offset().is_none()
            && let Some(range) = self.input_range()
        {
            err.set_offset(range.start);
        }
        for (_, f) in self.error_context.iter() {
            f(err, self);
        }
    }
}

// the state must never prevent an ongoing serialization or deserialization
// from moving between threads.
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<State>();
};

impl fmt::Debug for State {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("State")
            .field("extensions", &self.extensions)
            .field("depth", &self.depth)
            .field("is_map_key", &self.is_map_key)
            .field("is_multimap", &self.is_multimap)
            .field("input_range", &self.input_range())
            .finish()
    }
}