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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! Error interface.
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::any::{Any, TypeId};
use core::fmt;
use core::mem::ManuallyDrop;
use core::ops::{Deref, DerefMut};

use crate::{Position, State};

/// Describes the kind of error.
///
/// The kind determines the [`ErrorCategory`] of an error (see
/// [`Error::category`]): the formats fail with [`Syntax`](Self::Syntax),
/// [`EndOfFile`](Self::EndOfFile) and [`LimitExceeded`](Self::LimitExceeded)
/// if the input is not well-formed, the values with the kinds of the
/// [`Data`](ErrorCategory::Data) category if it is well-formed but does
/// not fit them.
///
/// More kinds may be added in the future.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The input is not well-formed.
    ///
    /// This covers what the grammar of the format rejects (including data
    /// after the end of the input and input that is not validly encoded)
    /// and documents that are invalid in the format (like an unknown
    /// alias in YAML or rows of different lengths in CSV).
    Syntax,
    /// The input ended before the value was complete or is empty.
    EndOfFile,
    /// A limit was exceeded (see [`Limits`](crate::de::Limits)), like the
    /// depth of nesting or the length of the input.
    LimitExceeded,
    /// A value has a type that is not expected (like a string where a
    /// number is expected).
    InvalidType,
    /// A value has the type that is expected but is invalid (like text
    /// that is not a number where a number is expected, or a value that a
    /// validator rejects).
    InvalidValue,
    /// A number is out of the range of the type it's converted to.
    OutOfRange,
    /// A sequence or bytes have a length that is not expected.
    WrongLength,
    /// A field (or the tag of an enum) is missing.
    MissingField,
    /// A field is not known (see `#[deser(deny_unknown_fields)]`).
    UnknownField,
    /// A variant of an enum is not known, or no variant of an untagged
    /// enum matches.
    UnknownVariant,
    /// A key is given more than once (see
    /// [`DuplicateKeys`](crate::de::DuplicateKeys)).
    DuplicateKey,
    /// A type or value cannot be represented: the format does not support
    /// it, or the type cannot be deserialized from what the format
    /// provides (like a `&str` from a string that is not borrowed).
    UnsupportedType,
    /// An API is used in a way that is not supported, for instance a
    /// stream that failed is used again or a serializer receives events
    /// that do not form a value.
    InvalidState,
    /// deser is set up wrongly, for instance the variants of an open enum
    /// are not registered or two of them have the same name.  These are
    /// bugs in the program, not problems of the input.
    Configuration,
    /// Reading or writing failed (see `deser::io`).  The IO error is
    /// the [`source`](core::error::Error::source) of the error.
    Io,
    /// An error which has none of the other kinds.
    ///
    /// The category of these errors depends on where they come from (see
    /// [`Error::category`]).
    Custom,
}

impl ErrorKind {
    /// Returns `true` if a value rejects what it's given.
    ///
    /// The fallbacks which try another representation of a value if it's
    /// rejected (like the text of a number) check this.  These are the
    /// kinds of the errors of values, apart from numbers that are out of
    /// range and missing fields.
    #[inline]
    pub(crate) fn is_rejection(self) -> bool {
        matches!(
            self,
            ErrorKind::InvalidType
                | ErrorKind::InvalidValue
                | ErrorKind::UnknownField
                | ErrorKind::UnknownVariant
                | ErrorKind::DuplicateKey
                | ErrorKind::Custom
        )
    }
}

/// Describes the category of an error, see [`Error::category`].
///
/// The categories tell apart whether the input was not well-formed or did
/// not fit the values it was deserialized into.  For instance an HTTP
/// server would answer requests that fail with errors of the
/// [`Syntax`](Self::Syntax) and [`Eof`](Self::Eof) categories with
/// `400 Bad Request` and the ones of the [`Data`](Self::Data) category
/// with `422 Unprocessable Entity`.
///
/// More categories may be added in the future.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[non_exhaustive]
pub enum ErrorCategory {
    /// The input is not well-formed ([`ErrorKind::Syntax`]).
    Syntax,
    /// The input ended early ([`ErrorKind::EndOfFile`]).
    Eof,
    /// The input is well-formed but does not fit the values, or a value
    /// cannot be serialized.
    Data,
    /// A limit was exceeded ([`ErrorKind::LimitExceeded`]).
    Limit,
    /// A type or value cannot be represented
    /// ([`ErrorKind::UnsupportedType`]).
    Unsupported,
    /// An API was used in a way that is not supported
    /// ([`ErrorKind::InvalidState`]) or deser is set up wrongly
    /// ([`ErrorKind::Configuration`]).
    Usage,
    /// Reading or writing failed ([`ErrorKind::Io`]).
    Io,
}

/// Additional information attached to an [`Error`].
///
/// Besides the location in the input, which is built into errors, layers
/// and other code can attach typed values to errors with
/// [`Error::set_attachment`] and retrieve them with
/// [`Error::attachment`].  An error holds at most one attachment per type.
/// For instance the `deser-path` crate attaches the path of the value an
/// error refers to.
///
/// Attachments can contribute to the [`Display`](fmt::Display) output of
/// the error with [`fmt_context`](Self::fmt_context).
///
/// ```
/// use std::fmt;
/// use deser::{Error, ErrorAttachment, ErrorKind};
///
/// #[derive(Debug)]
/// struct FileName(String);
///
/// impl ErrorAttachment for FileName {
///     fn fmt_context(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, " in {}", self.0)
///     }
/// }
///
/// let mut err = Error::with_position(ErrorKind::InvalidType, "unexpected string", 12, 2, 5);
/// err.set_attachment(FileName("config.json".into()));
/// assert_eq!(err.attachment::<FileName>().unwrap().0, "config.json");
/// assert_eq!(
///     err.to_string(),
///     "InvalidType: unexpected string at line 2 column 5 in config.json"
/// );
/// ```
pub trait ErrorAttachment: Any + fmt::Debug + Send + Sync {
    /// Writes the attachment as part of the error message.
    ///
    /// The output is appended to the message and the location of the
    /// error, so it typically starts with a space.  By default attachments
    /// are not shown.
    fn fmt_context(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let _ = f;
        Ok(())
    }
}

/// Adds context to errors, see [`State::add_error_context`](crate::State::add_error_context).
///
/// This is typically implemented by the extension type which holds the
/// information that is attached to errors.
pub trait ErrorContext: 'static {
    /// Adds context to an error.
    ///
    /// This is invoked with the state as it was when the error happened.
    /// Context that is already attached to the error should not be
    /// replaced.
    fn add_context(err: &mut Error, state: &State);
}

/// The message of the result that requests a raw value, identified by its
/// address (see `Error::raw_request`).
static RAW_REQUEST: &str = "raw value requested outside of a deserialization";

/// An error for deser.
///
/// Besides a kind and a message an error can carry context: the location
/// in the input it refers to (see [`offset`](Self::offset),
/// [`line`](Self::line) and [`column`](Self::column)) and typed
/// attachments (see [`ErrorAttachment`]).  The context is part of the
/// [`Display`](fmt::Display) output:
///
/// ```
/// use deser::{Error, ErrorKind};
///
/// let err = Error::with_position(ErrorKind::InvalidType, "unexpected string", 12, 2, 5);
/// assert_eq!(
///     err.to_string(),
///     "InvalidType: unexpected string at line 2 column 5"
/// );
/// ```
///
/// Errors raised while deserializing a value (for instance by a
/// [`Sink`](crate::de::Sink)) get the context attached by the
/// [`DeserializeDriver`](crate::de::DeserializeDriver): the start of the
/// input range of the event (see [`State::input_range`](crate::State::input_range))
/// and the context of the types registered with
/// [`State::add_error_context`](crate::State::add_error_context).  Formats
/// resolve the offsets into lines and columns.
///
/// # Multiple Errors
///
/// An error can hold multiple errors, for instance if deserialization
/// continued after an error to report all problems of the input at once
/// (see [`State::set_collect_errors`](crate::State::set_collect_errors)).
/// The accessors ([`kind`](Self::kind), [`message`](Self::message), the
/// location and the attachments) refer to the first of them, all of them
/// are iterated with [`errors`](Self::errors).  The
/// [`Display`](fmt::Display) output mentions how many more errors there
/// are, with the alternate flag (`{:#}`) it lists all of them, one per
/// line:
///
/// ```
/// use deser::{Error, ErrorKind};
///
/// let mut err = Error::from_errors([
///     Error::with_offset(ErrorKind::MissingField, "missing field `a`", 0),
///     Error::with_offset(ErrorKind::InvalidType, "unexpected string", 9),
/// ])
/// .unwrap();
/// err.resolve_position(b"{\n  \"b\": \"x\"}");
/// assert_eq!(err.errors().count(), 2);
/// assert_eq!(err.kind(), ErrorKind::MissingField);
/// assert_eq!(
///     err.to_string(),
///     "MissingField: missing field `a` at line 1 column 1 \
///      (and 1 more error)"
/// );
/// assert_eq!(
///     format!("{:#}", err),
///     "MissingField: missing field `a` at line 1 column 1\n\
///      InvalidType: unexpected string at line 2 column 8"
/// );
/// ```
pub struct Error {
    // boxed so that results stay small.  Errors are rare but results are
    // passed around for every single value.
    inner: ErrorBox,
}

/// The box of an error which is dropped out of line.
///
/// The drop glue of the box (the messages, sources, attachments and
/// nested errors) used to be inlined everywhere an `Error` or a
/// `Result<_, Error>` is dropped, in release builds there were a dozen
/// copies of it.  Now dropping an error is a call.
struct ErrorBox(ManuallyDrop<Box<ErrorInner>>);

impl ErrorBox {
    #[inline(always)]
    fn new(inner: ErrorInner) -> ErrorBox {
        ErrorBox(ManuallyDrop::new(Box::new(inner)))
    }

    /// Moves the error out of the box.
    #[inline(always)]
    fn into_inner(self) -> ErrorInner {
        let mut this = ManuallyDrop::new(self);
        // SAFETY: `this` is never dropped, so the box is taken exactly once
        // and not dropped again by `ErrorBox::drop`.
        *unsafe { ManuallyDrop::take(&mut this.0) }
    }
}

impl Drop for ErrorBox {
    #[inline(never)]
    fn drop(&mut self) {
        // SAFETY: the box is not used after this.  `into_inner`, the only
        // other place that takes it, does not drop the `ErrorBox`.
        unsafe { ManuallyDrop::drop(&mut self.0) }
    }
}

impl Deref for ErrorBox {
    type Target = ErrorInner;

    #[inline(always)]
    fn deref(&self) -> &ErrorInner {
        &self.0
    }
}

impl DerefMut for ErrorBox {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut ErrorInner {
        &mut self.0
    }
}

enum ErrorInner {
    Single(ErrorData),
    // at least two errors, all of them are single errors.  The first one
    // is the error the accessors refer to.
    Multiple(Vec<Error>),
}

#[derive(Debug)]
struct ErrorData {
    kind: ErrorKind,
    msg: Cow<'static, str>,
    source: Option<Box<dyn core::error::Error + Send + Sync>>,
    offset: Option<usize>,
    // line and column (1-based)
    line_column: Option<(usize, usize)>,
    // in the order they were attached, at most one per type
    attachments: Vec<Attachment>,
    // `true` once the driver attached the context of the current event.
    has_context: bool,
    // `true` once the error was collected (see `CollectedErrors`)
    collected: bool,
}

#[derive(Debug)]
struct Attachment {
    // Invariant: the type of the value
    type_id: TypeId,
    value: Box<dyn ErrorAttachment>,
}

impl Error {
    /// Creates a new error.
    #[cold]
    pub fn new<M: Into<Cow<'static, str>>>(kind: ErrorKind, msg: M) -> Error {
        Error {
            inner: ErrorBox::new(ErrorInner::Single(ErrorData {
                kind,
                msg: msg.into(),
                source: None,
                offset: None,
                line_column: None,
                attachments: Vec::new(),
                has_context: false,
                collected: false,
            })),
        }
    }

    /// Creates a new error at a byte offset in the input (see
    /// [`set_offset`](Self::set_offset)).
    #[cold]
    pub fn with_offset<M: Into<Cow<'static, str>>>(
        kind: ErrorKind,
        msg: M,
        offset: usize,
    ) -> Error {
        let mut err = Error::new(kind, msg);
        err.set_offset(offset);
        err
    }

    /// Creates a new error at a byte offset with its line and column (see
    /// [`set_position`](Self::set_position)).
    #[cold]
    pub fn with_position<M: Into<Cow<'static, str>>>(
        kind: ErrorKind,
        msg: M,
        offset: usize,
        line: usize,
        column: usize,
    ) -> Error {
        let mut err = Error::new(kind, msg);
        err.set_position(offset, line, column);
        err
    }

    /// Combines errors into one.
    ///
    /// Errors that hold multiple errors are flattened: errors do not nest
    /// (see [`errors`](Self::errors)).  Returns `None` if there are no
    /// errors.
    pub fn from_errors<I: IntoIterator<Item = Error>>(errors: I) -> Option<Error> {
        let mut errors = errors.into_iter();
        let mut rv = errors.next()?;
        for err in errors {
            rv.push_error(err);
        }
        Some(rv)
    }

    /// Creates the error for a value that is serialized while another one
    /// is only partially written.
    ///
    /// Stream serializers return this once they are
    /// [in progress](crate::ser::StreamSerializer::in_progress) and are asked
    /// to serialize another value.
    #[cold]
    pub fn in_progress() -> Error {
        Error::new(
            ErrorKind::InvalidState,
            "a value was only partially written, the stream cannot continue",
        )
    }

    /// Adds an error to this error.
    ///
    /// If the error that is added holds multiple errors, they are added
    /// individually: errors do not nest (see [`errors`](Self::errors)).
    pub(crate) fn push_error(&mut self, err: Error) {
        let errors = self.make_multiple();
        if matches!(*err.inner, ErrorInner::Single(_)) {
            errors.push(err);
        } else if let ErrorInner::Multiple(others) = err.inner.into_inner() {
            errors.extend(others);
        }
    }

    /// Turns the error into one that holds multiple errors.
    fn make_multiple(&mut self) -> &mut Vec<Error> {
        if let ErrorInner::Single(_) = *self.inner {
            let first = core::mem::replace(&mut *self.inner, ErrorInner::Multiple(Vec::new()));
            if let ErrorInner::Multiple(ref mut errors) = *self.inner {
                errors.push(Error {
                    inner: ErrorBox::new(first),
                });
            }
        }
        match *self.inner {
            ErrorInner::Multiple(ref mut errors) => errors,
            ErrorInner::Single(_) => unreachable!(),
        }
    }

    /// Iterates over the errors this error holds.
    ///
    /// For an error that holds a single error, this is the error itself.
    /// The errors that are returned hold a single error each.
    pub fn errors(&self) -> impl Iterator<Item = &Error> {
        match *self.inner {
            ErrorInner::Single(_) => core::slice::from_ref(self).iter(),
            ErrorInner::Multiple(ref errors) => errors.iter(),
        }
    }

    /// Returns the data of the (first) error.
    fn data(&self) -> &ErrorData {
        match *self.inner {
            ErrorInner::Single(ref data) => data,
            ErrorInner::Multiple(ref errors) => errors[0].data(),
        }
    }

    /// Returns the data of the (first) error mutably.
    fn data_mut(&mut self) -> &mut ErrorData {
        match *self.inner {
            ErrorInner::Single(ref mut data) => data,
            ErrorInner::Multiple(ref mut errors) => errors[0].data_mut(),
        }
    }

    /// Applies a function to every error this error holds.
    /// Changes every error (see [`errors`](Self::errors)).
    pub(crate) fn for_each_mut(&mut self, mut f: impl FnMut(&mut Error)) {
        if let ErrorInner::Multiple(ref mut errors) = *self.inner {
            errors.iter_mut().for_each(f);
        } else {
            f(self)
        }
    }

    pub(crate) fn map_each(mut self, mut f: impl FnMut(Error) -> Error) -> Error {
        if let ErrorInner::Multiple(ref mut errors) = *self.inner {
            for err in errors.iter_mut() {
                let taken = core::mem::replace(err, Error::new(ErrorKind::Custom, ""));
                *err = f(taken);
            }
            self
        } else {
            f(self)
        }
    }

    /// Returns the number of errors this error holds that were not
    /// collected yet.
    pub(crate) fn uncollected_count(&self) -> usize {
        self.errors().filter(|err| !err.data().collected).count()
    }

    /// Marks all errors this error holds as collected.
    pub(crate) fn mark_collected(mut self) -> Error {
        self = self.map_each(|mut err| {
            err.data_mut().collected = true;
            err
        });
        self
    }

    /// Attaches another error as source to this error.
    pub fn set_source<E: core::error::Error + Send + Sync + 'static>(&mut self, source: E) {
        self.data_mut().source = Some(Box::new(source));
    }

    /// Creates the result of an event that requests the next value as raw
    /// value (see [`is_raw_request`](Self::is_raw_request)).
    #[cold]
    pub(crate) fn raw_request() -> Error {
        Error::new(ErrorKind::InvalidState, RAW_REQUEST)
    }

    /// Returns `true` if this requests the next value as raw value.
    ///
    /// This is not an error: sinks return it from the event before a value
    /// that deserializes into a [`Raw`](crate::ext::Raw) value of the format
    /// that is parsed (see [`State::declare_raw_format`](crate::State::declare_raw_format)).
    /// Deserializers of formats with raw values check the errors of events
    /// with this.  If it's `true`, the event was accepted and the format
    /// passes on the input of the next value as
    /// [`RawInput`](crate::ext::RawInput) rather than its events.  Other
    /// formats never see it.
    pub fn is_raw_request(&self) -> bool {
        match *self.inner {
            ErrorInner::Single(ErrorData {
                msg: Cow::Borrowed(msg),
                ..
            }) => core::ptr::eq(msg, RAW_REQUEST),
            _ => false,
        }
    }

    /// Returns the kind of the error.
    pub fn kind(&self) -> ErrorKind {
        self.data().kind
    }

    /// Returns the category of the error.
    ///
    /// The category follows from the [`kind`](Self::kind).  The exception
    /// are errors of the kind [`Custom`](ErrorKind::Custom): they are in
    /// the [`Data`](ErrorCategory::Data) category if a value failed with them
    /// while it was deserialized or serialized (the driver attached the
    /// context of the event to them, see [`Error`]), and in the
    /// [`Syntax`](ErrorCategory::Syntax) category otherwise (the format
    /// failed with them).
    ///
    /// For an error that holds multiple errors this is the category of
    /// the first one.
    ///
    /// ```
    /// use deser::{Error, ErrorCategory, ErrorKind};
    ///
    /// let err = Error::new(ErrorKind::Syntax, "expected a comma");
    /// assert_eq!(err.category(), ErrorCategory::Syntax);
    /// let err = Error::new(ErrorKind::InvalidType, "unexpected string");
    /// assert_eq!(err.category(), ErrorCategory::Data);
    /// ```
    pub fn category(&self) -> ErrorCategory {
        let data = self.data();
        match data.kind {
            ErrorKind::Syntax => ErrorCategory::Syntax,
            ErrorKind::EndOfFile => ErrorCategory::Eof,
            ErrorKind::LimitExceeded => ErrorCategory::Limit,
            ErrorKind::InvalidType
            | ErrorKind::InvalidValue
            | ErrorKind::OutOfRange
            | ErrorKind::WrongLength
            | ErrorKind::MissingField
            | ErrorKind::UnknownField
            | ErrorKind::UnknownVariant
            | ErrorKind::DuplicateKey => ErrorCategory::Data,
            ErrorKind::UnsupportedType => ErrorCategory::Unsupported,
            ErrorKind::InvalidState | ErrorKind::Configuration => ErrorCategory::Usage,
            ErrorKind::Io => ErrorCategory::Io,
            ErrorKind::Custom => {
                if data.has_context {
                    ErrorCategory::Data
                } else {
                    ErrorCategory::Syntax
                }
            }
        }
    }

    /// Returns the message of the error (without context).
    pub fn message(&self) -> &str {
        &self.data().msg
    }

    /// Sets the byte offset in the input the error refers to.
    ///
    /// A previously set line and column are discarded.
    pub fn set_offset(&mut self, offset: usize) {
        let data = self.data_mut();
        data.offset = Some(offset);
        data.line_column = None;
    }

    /// Sets the byte offset together with its line and column (1-based).
    pub fn set_position(&mut self, offset: usize, line: usize, column: usize) {
        let data = self.data_mut();
        data.offset = Some(offset);
        data.line_column = Some((line, column));
    }

    /// Resolves the offset into line and column.
    ///
    /// The source is the input the offset refers to.  Columns are counted
    /// in characters (bytes that are not UTF-8 continuation bytes).  If the
    /// error has no offset or already has a line and column, it's returned
    /// unchanged.  Text formats call this for the errors they return.
    ///
    /// ```
    /// use deser::{Error, ErrorKind};
    ///
    /// let mut err = Error::with_offset(ErrorKind::InvalidValue, "bad value", 7);
    /// err.resolve_position(b"[1,\n  x]");
    /// assert_eq!((err.line(), err.column()), (Some(2), Some(4)));
    /// ```
    ///
    /// The positions of further errors (see [`errors`](Self::errors)) are
    /// resolved as well.
    pub fn resolve_position(&mut self, source: &[u8]) {
        self.for_each_mut(|err| {
            let data = err.data_mut();
            if let (Some(offset), None) = (data.offset, data.line_column) {
                let pos = Position::of(source, offset);
                data.line_column = Some((pos.line, pos.column));
            }
        });
    }

    /// Moves the position of the error by the position of the input it
    /// refers to.
    ///
    /// This is used for errors of inputs which are part of a larger input,
    /// the base is the position of the start of the part.
    pub(crate) fn shift_position(self, base: Position) -> Self {
        self.map_each(|mut err| {
            let data = err.data_mut();
            if let Some(ref mut error_offset) = data.offset {
                *error_offset += base.offset;
            }
            if let Some((ref mut error_line, ref mut error_column)) = data.line_column {
                if *error_line == 1 {
                    *error_column += base.column - 1;
                }
                *error_line += base.line - 1;
            }
            err
        })
    }

    /// Returns the byte offset in the input the error refers to.
    pub fn offset(&self) -> Option<usize> {
        self.data().offset
    }

    /// Returns the line (1-based) the error refers to.
    pub fn line(&self) -> Option<usize> {
        self.data().line_column.map(|x| x.0)
    }

    /// Returns the column (1-based, in characters) the error refers to.
    pub fn column(&self) -> Option<usize> {
        self.data().line_column.map(|x| x.1)
    }

    /// Attaches a value to the error.
    ///
    /// An attachment of the same type is replaced but keeps its position
    /// in the [`Display`](fmt::Display) output.  See [`ErrorAttachment`].
    pub fn set_attachment<T: ErrorAttachment>(&mut self, value: T) {
        let type_id = TypeId::of::<T>();
        let value = Box::new(value);
        let attachments = &mut self.data_mut().attachments;
        match attachments.iter_mut().find(|x| x.type_id == type_id) {
            Some(attachment) => attachment.value = value,
            None => attachments.push(Attachment { type_id, value }),
        }
    }

    /// Returns the attachment of the given type.
    pub fn attachment<T: ErrorAttachment>(&self) -> Option<&T> {
        let type_id = TypeId::of::<T>();
        let attachment = self
            .data()
            .attachments
            .iter()
            .find(|x| x.type_id == type_id)?;
        (&*attachment.value as &dyn Any).downcast_ref()
    }

    /// Returns the attachment of the given type mutably.
    pub fn attachment_mut<T: ErrorAttachment>(&mut self) -> Option<&mut T> {
        let type_id = TypeId::of::<T>();
        let attachment = self
            .data_mut()
            .attachments
            .iter_mut()
            .find(|x| x.type_id == type_id)?;
        (&mut *attachment.value as &mut dyn Any).downcast_mut()
    }

    /// Iterates over the attachments in the order they were attached.
    pub fn attachments(&self) -> impl Iterator<Item = &dyn ErrorAttachment> {
        self.data().attachments.iter().map(|x| &*x.value)
    }

    /// Returns `true` if the context of an event was attached.
    pub(crate) fn has_context(&self) -> bool {
        self.data().has_context
    }

    /// Marks the context of an event as attached.
    pub(crate) fn set_has_context(&mut self) {
        self.data_mut().has_context = true;
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let data = match *self.inner {
            ErrorInner::Single(ref data) => data,
            ErrorInner::Multiple(ref errors) => {
                return f.debug_tuple("Errors").field(errors).finish();
            }
        };
        let mut s = f.debug_struct("Error");
        s.field("kind", &data.kind).field("msg", &data.msg);
        if let Some(offset) = data.offset {
            s.field("offset", &offset);
        }
        if let Some((line, column)) = data.line_column {
            s.field("line", &line).field("column", &column);
        }
        if !data.attachments.is_empty() {
            s.field("attachments", &DebugAttachments(&data.attachments));
        }
        s.field("source", &data.source).finish()
    }
}

impl ErrorData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}: {}", self.kind, self.msg)?;
        match (self.line_column, self.offset) {
            (Some((line, column)), _) => write!(f, " at line {} column {}", line, column)?,
            (None, Some(offset)) => write!(f, " at offset {}", offset)?,
            (None, None) => {}
        }
        for attachment in self.attachments.iter() {
            attachment.value.fmt_context(f)?;
        }
        Ok(())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let errors = match *self.inner {
            ErrorInner::Single(ref data) => return data.fmt(f),
            ErrorInner::Multiple(ref errors) => errors,
        };
        errors[0].data().fmt(f)?;
        if f.alternate() {
            for err in &errors[1..] {
                writeln!(f)?;
                err.data().fmt(f)?;
            }
        } else if errors.len() == 2 {
            write!(f, " (and 1 more error)")?;
        } else {
            write!(f, " (and {} more errors)", errors.len() - 1)?;
        }
        Ok(())
    }
}

struct DebugAttachments<'a>(&'a [Attachment]);

impl fmt::Debug for DebugAttachments<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.0.iter().map(|x| &x.value))
            .finish()
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        let mut rv = Error::new(ErrorKind::Io, err.to_string());
        rv.set_source(err);
        rv
    }
}

impl core::error::Error for Error {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        self.data().source.as_ref().map(|err| err.as_ref() as _)
    }
}

/// Creates an error that is thrown away.
///
/// While errors are discarded (see `State::discard_errors`) the common
/// errors are created with this instead of building a message nobody reads.
#[cold]
#[inline(never)]
pub(crate) fn discarded_error(kind: ErrorKind) -> Error {
    Error::new(kind, "discarded error")
}

/// Creates the error for a value that failed to convert or validate.
#[cold]
pub(crate) fn conversion_error<E: fmt::Display>(err: E) -> Error {
    Error::new(ErrorKind::InvalidValue, format!("invalid value: {}", err))
}

/// Creates the error for an unknown variant.
///
/// `tag` is the name that was given (if it can be a name), `type_name` the
/// name of the enum and `names` are the names of the variants.
#[cold]
pub fn unknown_variant(tag: Option<&str>, type_name: &str, names: &[&str]) -> Error {
    let mut msg = String::from("unknown variant");
    if let Some(tag) = tag {
        msg.push_str(" `");
        msg.push_str(tag);
        msg.push('`');
    }
    msg.push_str(" of ");
    msg.push_str(type_name);
    push_expected(&mut msg, names, "variants");
    Error::new(ErrorKind::UnknownVariant, msg)
}

/// Appends the expected names to an error message.
///
/// `what` is what the names are, for the message if there are none.
pub(crate) fn push_expected(msg: &mut String, names: &[&str], what: &str) {
    match names {
        [] => {
            msg.push_str(", there are no ");
            msg.push_str(what);
        }
        [name] => {
            msg.push_str(", expected `");
            msg.push_str(name);
            msg.push('`');
        }
        [first, second] => {
            msg.push_str(", expected `");
            msg.push_str(first);
            msg.push_str("` or `");
            msg.push_str(second);
            msg.push('`');
        }
        names => {
            msg.push_str(", expected one of ");
            for (idx, name) in names.iter().enumerate() {
                if idx > 0 {
                    msg.push_str(", ");
                }
                msg.push('`');
                msg.push_str(name);
                msg.push('`');
            }
        }
    }
}