]> git.lizzy.rs Git - rust.git/blob - library/std/src/error.rs
Rollup merge of #84320 - jsha:details-implementors, r=Manishearth,Nemo157,GuillaumeGomez
[rust.git] / library / std / src / error.rs
1 //! Traits for working with Errors.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 // A note about crates and the facade:
6 //
7 // Originally, the `Error` trait was defined in libcore, and the impls
8 // were scattered about. However, coherence objected to this
9 // arrangement, because to create the blanket impls for `Box` required
10 // knowing that `&str: !Error`, and we have no means to deal with that
11 // sort of conflict just now. Therefore, for the time being, we have
12 // moved the `Error` trait into libstd. As we evolve a sol'n to the
13 // coherence challenge (e.g., specialization, neg impls, etc) we can
14 // reconsider what crate these items belong in.
15
16 #[cfg(test)]
17 mod tests;
18
19 use core::array;
20 use core::convert::Infallible;
21
22 use crate::alloc::{AllocError, LayoutError};
23 use crate::any::TypeId;
24 use crate::backtrace::Backtrace;
25 use crate::borrow::Cow;
26 use crate::cell;
27 use crate::char;
28 use crate::fmt::{self, Debug, Display};
29 use crate::mem::transmute;
30 use crate::num;
31 use crate::str;
32 use crate::string;
33 use crate::sync::Arc;
34
35 /// `Error` is a trait representing the basic expectations for error values,
36 /// i.e., values of type `E` in [`Result<T, E>`].
37 ///
38 /// Errors must describe themselves through the [`Display`] and [`Debug`]
39 /// traits. Error messages are typically concise lowercase sentences without
40 /// trailing punctuation:
41 ///
42 /// ```
43 /// let err = "NaN".parse::<u32>().unwrap_err();
44 /// assert_eq!(err.to_string(), "invalid digit found in string");
45 /// ```
46 ///
47 /// Errors may provide cause chain information. [`Error::source()`] is generally
48 /// used when errors cross "abstraction boundaries". If one module must report
49 /// an error that is caused by an error from a lower-level module, it can allow
50 /// accessing that error via [`Error::source()`]. This makes it possible for the
51 /// high-level module to provide its own errors while also revealing some of the
52 /// implementation for debugging via `source` chains.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub trait Error: Debug + Display {
55     /// The lower-level source of this error, if any.
56     ///
57     /// # Examples
58     ///
59     /// ```
60     /// use std::error::Error;
61     /// use std::fmt;
62     ///
63     /// #[derive(Debug)]
64     /// struct SuperError {
65     ///     side: SuperErrorSideKick,
66     /// }
67     ///
68     /// impl fmt::Display for SuperError {
69     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70     ///         write!(f, "SuperError is here!")
71     ///     }
72     /// }
73     ///
74     /// impl Error for SuperError {
75     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
76     ///         Some(&self.side)
77     ///     }
78     /// }
79     ///
80     /// #[derive(Debug)]
81     /// struct SuperErrorSideKick;
82     ///
83     /// impl fmt::Display for SuperErrorSideKick {
84     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85     ///         write!(f, "SuperErrorSideKick is here!")
86     ///     }
87     /// }
88     ///
89     /// impl Error for SuperErrorSideKick {}
90     ///
91     /// fn get_super_error() -> Result<(), SuperError> {
92     ///     Err(SuperError { side: SuperErrorSideKick })
93     /// }
94     ///
95     /// fn main() {
96     ///     match get_super_error() {
97     ///         Err(e) => {
98     ///             println!("Error: {}", e);
99     ///             println!("Caused by: {}", e.source().unwrap());
100     ///         }
101     ///         _ => println!("No error"),
102     ///     }
103     /// }
104     /// ```
105     #[stable(feature = "error_source", since = "1.30.0")]
106     fn source(&self) -> Option<&(dyn Error + 'static)> {
107         None
108     }
109
110     /// Gets the `TypeId` of `self`.
111     #[doc(hidden)]
112     #[unstable(
113         feature = "error_type_id",
114         reason = "this is memory-unsafe to override in user code",
115         issue = "60784"
116     )]
117     fn type_id(&self, _: private::Internal) -> TypeId
118     where
119         Self: 'static,
120     {
121         TypeId::of::<Self>()
122     }
123
124     /// Returns a stack backtrace, if available, of where this error occurred.
125     ///
126     /// This function allows inspecting the location, in code, of where an error
127     /// happened. The returned `Backtrace` contains information about the stack
128     /// trace of the OS thread of execution of where the error originated from.
129     ///
130     /// Note that not all errors contain a `Backtrace`. Also note that a
131     /// `Backtrace` may actually be empty. For more information consult the
132     /// `Backtrace` type itself.
133     #[unstable(feature = "backtrace", issue = "53487")]
134     fn backtrace(&self) -> Option<&Backtrace> {
135         None
136     }
137
138     /// ```
139     /// if let Err(e) = "xc".parse::<u32>() {
140     ///     // Print `e` itself, no need for description().
141     ///     eprintln!("Error: {}", e);
142     /// }
143     /// ```
144     #[stable(feature = "rust1", since = "1.0.0")]
145     #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
146     fn description(&self) -> &str {
147         "description() is deprecated; use Display"
148     }
149
150     #[stable(feature = "rust1", since = "1.0.0")]
151     #[rustc_deprecated(
152         since = "1.33.0",
153         reason = "replaced by Error::source, which can support downcasting"
154     )]
155     #[allow(missing_docs)]
156     fn cause(&self) -> Option<&dyn Error> {
157         self.source()
158     }
159 }
160
161 mod private {
162     // This is a hack to prevent `type_id` from being overridden by `Error`
163     // implementations, since that can enable unsound downcasting.
164     #[unstable(feature = "error_type_id", issue = "60784")]
165     #[derive(Debug)]
166     pub struct Internal;
167 }
168
169 #[stable(feature = "rust1", since = "1.0.0")]
170 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
171     /// Converts a type of [`Error`] into a box of dyn [`Error`].
172     ///
173     /// # Examples
174     ///
175     /// ```
176     /// use std::error::Error;
177     /// use std::fmt;
178     /// use std::mem;
179     ///
180     /// #[derive(Debug)]
181     /// struct AnError;
182     ///
183     /// impl fmt::Display for AnError {
184     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185     ///         write!(f , "An error")
186     ///     }
187     /// }
188     ///
189     /// impl Error for AnError {}
190     ///
191     /// let an_error = AnError;
192     /// assert!(0 == mem::size_of_val(&an_error));
193     /// let a_boxed_error = Box::<dyn Error>::from(an_error);
194     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
195     /// ```
196     fn from(err: E) -> Box<dyn Error + 'a> {
197         Box::new(err)
198     }
199 }
200
201 #[stable(feature = "rust1", since = "1.0.0")]
202 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
203     /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
204     /// dyn [`Error`] + [`Send`] + [`Sync`].
205     ///
206     /// # Examples
207     ///
208     /// ```
209     /// use std::error::Error;
210     /// use std::fmt;
211     /// use std::mem;
212     ///
213     /// #[derive(Debug)]
214     /// struct AnError;
215     ///
216     /// impl fmt::Display for AnError {
217     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218     ///         write!(f , "An error")
219     ///     }
220     /// }
221     ///
222     /// impl Error for AnError {}
223     ///
224     /// unsafe impl Send for AnError {}
225     ///
226     /// unsafe impl Sync for AnError {}
227     ///
228     /// let an_error = AnError;
229     /// assert!(0 == mem::size_of_val(&an_error));
230     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
231     /// assert!(
232     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
233     /// ```
234     fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
235         Box::new(err)
236     }
237 }
238
239 #[stable(feature = "rust1", since = "1.0.0")]
240 impl From<String> for Box<dyn Error + Send + Sync> {
241     /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
242     ///
243     /// # Examples
244     ///
245     /// ```
246     /// use std::error::Error;
247     /// use std::mem;
248     ///
249     /// let a_string_error = "a string error".to_string();
250     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
251     /// assert!(
252     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
253     /// ```
254     #[inline]
255     fn from(err: String) -> Box<dyn Error + Send + Sync> {
256         struct StringError(String);
257
258         impl Error for StringError {
259             #[allow(deprecated)]
260             fn description(&self) -> &str {
261                 &self.0
262             }
263         }
264
265         impl Display for StringError {
266             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267                 Display::fmt(&self.0, f)
268             }
269         }
270
271         // Purposefully skip printing "StringError(..)"
272         impl Debug for StringError {
273             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274                 Debug::fmt(&self.0, f)
275             }
276         }
277
278         Box::new(StringError(err))
279     }
280 }
281
282 #[stable(feature = "string_box_error", since = "1.6.0")]
283 impl From<String> for Box<dyn Error> {
284     /// Converts a [`String`] into a box of dyn [`Error`].
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// use std::error::Error;
290     /// use std::mem;
291     ///
292     /// let a_string_error = "a string error".to_string();
293     /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
294     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
295     /// ```
296     fn from(str_err: String) -> Box<dyn Error> {
297         let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
298         let err2: Box<dyn Error> = err1;
299         err2
300     }
301 }
302
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
305     /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
306     ///
307     /// [`str`]: prim@str
308     ///
309     /// # Examples
310     ///
311     /// ```
312     /// use std::error::Error;
313     /// use std::mem;
314     ///
315     /// let a_str_error = "a str error";
316     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
317     /// assert!(
318     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
319     /// ```
320     #[inline]
321     fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
322         From::from(String::from(err))
323     }
324 }
325
326 #[stable(feature = "string_box_error", since = "1.6.0")]
327 impl From<&str> for Box<dyn Error> {
328     /// Converts a [`str`] into a box of dyn [`Error`].
329     ///
330     /// [`str`]: prim@str
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// use std::error::Error;
336     /// use std::mem;
337     ///
338     /// let a_str_error = "a str error";
339     /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
340     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
341     /// ```
342     fn from(err: &str) -> Box<dyn Error> {
343         From::from(String::from(err))
344     }
345 }
346
347 #[stable(feature = "cow_box_error", since = "1.22.0")]
348 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
349     /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
350     ///
351     /// # Examples
352     ///
353     /// ```
354     /// use std::error::Error;
355     /// use std::mem;
356     /// use std::borrow::Cow;
357     ///
358     /// let a_cow_str_error = Cow::from("a str error");
359     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
360     /// assert!(
361     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
362     /// ```
363     fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
364         From::from(String::from(err))
365     }
366 }
367
368 #[stable(feature = "cow_box_error", since = "1.22.0")]
369 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
370     /// Converts a [`Cow`] into a box of dyn [`Error`].
371     ///
372     /// # Examples
373     ///
374     /// ```
375     /// use std::error::Error;
376     /// use std::mem;
377     /// use std::borrow::Cow;
378     ///
379     /// let a_cow_str_error = Cow::from("a str error");
380     /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
381     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
382     /// ```
383     fn from(err: Cow<'a, str>) -> Box<dyn Error> {
384         From::from(String::from(err))
385     }
386 }
387
388 #[unstable(feature = "never_type", issue = "35121")]
389 impl Error for ! {}
390
391 #[unstable(
392     feature = "allocator_api",
393     reason = "the precise API and guarantees it provides may be tweaked.",
394     issue = "32838"
395 )]
396 impl Error for AllocError {}
397
398 #[stable(feature = "alloc_layout", since = "1.28.0")]
399 impl Error for LayoutError {}
400
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl Error for str::ParseBoolError {
403     #[allow(deprecated)]
404     fn description(&self) -> &str {
405         "failed to parse bool"
406     }
407 }
408
409 #[stable(feature = "rust1", since = "1.0.0")]
410 impl Error for str::Utf8Error {
411     #[allow(deprecated)]
412     fn description(&self) -> &str {
413         "invalid utf-8: corrupt contents"
414     }
415 }
416
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl Error for num::ParseIntError {
419     #[allow(deprecated)]
420     fn description(&self) -> &str {
421         self.__description()
422     }
423 }
424
425 #[stable(feature = "try_from", since = "1.34.0")]
426 impl Error for num::TryFromIntError {
427     #[allow(deprecated)]
428     fn description(&self) -> &str {
429         self.__description()
430     }
431 }
432
433 #[stable(feature = "try_from", since = "1.34.0")]
434 impl Error for array::TryFromSliceError {
435     #[allow(deprecated)]
436     fn description(&self) -> &str {
437         self.__description()
438     }
439 }
440
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl Error for num::ParseFloatError {
443     #[allow(deprecated)]
444     fn description(&self) -> &str {
445         self.__description()
446     }
447 }
448
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl Error for string::FromUtf8Error {
451     #[allow(deprecated)]
452     fn description(&self) -> &str {
453         "invalid utf-8"
454     }
455 }
456
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl Error for string::FromUtf16Error {
459     #[allow(deprecated)]
460     fn description(&self) -> &str {
461         "invalid utf-16"
462     }
463 }
464
465 #[stable(feature = "str_parse_error2", since = "1.8.0")]
466 impl Error for Infallible {
467     fn description(&self) -> &str {
468         match *self {}
469     }
470 }
471
472 #[stable(feature = "decode_utf16", since = "1.9.0")]
473 impl Error for char::DecodeUtf16Error {
474     #[allow(deprecated)]
475     fn description(&self) -> &str {
476         "unpaired surrogate found"
477     }
478 }
479
480 #[unstable(feature = "map_try_insert", issue = "82766")]
481 impl<'a, K: Debug + Ord, V: Debug> Error
482     for crate::collections::btree_map::OccupiedError<'a, K, V>
483 {
484     #[allow(deprecated)]
485     fn description(&self) -> &str {
486         "key already exists"
487     }
488 }
489
490 #[unstable(feature = "map_try_insert", issue = "82766")]
491 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
492     #[allow(deprecated)]
493     fn description(&self) -> &str {
494         "key already exists"
495     }
496 }
497
498 #[stable(feature = "box_error", since = "1.8.0")]
499 impl<T: Error> Error for Box<T> {
500     #[allow(deprecated, deprecated_in_future)]
501     fn description(&self) -> &str {
502         Error::description(&**self)
503     }
504
505     #[allow(deprecated)]
506     fn cause(&self) -> Option<&dyn Error> {
507         Error::cause(&**self)
508     }
509
510     fn source(&self) -> Option<&(dyn Error + 'static)> {
511         Error::source(&**self)
512     }
513 }
514
515 #[stable(feature = "error_by_ref", since = "1.51.0")]
516 impl<'a, T: Error + ?Sized> Error for &'a T {
517     #[allow(deprecated, deprecated_in_future)]
518     fn description(&self) -> &str {
519         Error::description(&**self)
520     }
521
522     #[allow(deprecated)]
523     fn cause(&self) -> Option<&dyn Error> {
524         Error::cause(&**self)
525     }
526
527     fn source(&self) -> Option<&(dyn Error + 'static)> {
528         Error::source(&**self)
529     }
530
531     fn backtrace(&self) -> Option<&Backtrace> {
532         Error::backtrace(&**self)
533     }
534 }
535
536 #[stable(feature = "arc_error", since = "1.52.0")]
537 impl<T: Error + ?Sized> Error for Arc<T> {
538     #[allow(deprecated, deprecated_in_future)]
539     fn description(&self) -> &str {
540         Error::description(&**self)
541     }
542
543     #[allow(deprecated)]
544     fn cause(&self) -> Option<&dyn Error> {
545         Error::cause(&**self)
546     }
547
548     fn source(&self) -> Option<&(dyn Error + 'static)> {
549         Error::source(&**self)
550     }
551
552     fn backtrace(&self) -> Option<&Backtrace> {
553         Error::backtrace(&**self)
554     }
555 }
556
557 #[stable(feature = "fmt_error", since = "1.11.0")]
558 impl Error for fmt::Error {
559     #[allow(deprecated)]
560     fn description(&self) -> &str {
561         "an error occurred when formatting an argument"
562     }
563 }
564
565 #[stable(feature = "try_borrow", since = "1.13.0")]
566 impl Error for cell::BorrowError {
567     #[allow(deprecated)]
568     fn description(&self) -> &str {
569         "already mutably borrowed"
570     }
571 }
572
573 #[stable(feature = "try_borrow", since = "1.13.0")]
574 impl Error for cell::BorrowMutError {
575     #[allow(deprecated)]
576     fn description(&self) -> &str {
577         "already borrowed"
578     }
579 }
580
581 #[stable(feature = "try_from", since = "1.34.0")]
582 impl Error for char::CharTryFromError {
583     #[allow(deprecated)]
584     fn description(&self) -> &str {
585         "converted integer out of range for `char`"
586     }
587 }
588
589 #[stable(feature = "char_from_str", since = "1.20.0")]
590 impl Error for char::ParseCharError {
591     #[allow(deprecated)]
592     fn description(&self) -> &str {
593         self.__description()
594     }
595 }
596
597 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
598 impl Error for alloc::collections::TryReserveError {}
599
600 // Copied from `any.rs`.
601 impl dyn Error + 'static {
602     /// Returns `true` if the boxed type is the same as `T`
603     #[stable(feature = "error_downcast", since = "1.3.0")]
604     #[inline]
605     pub fn is<T: Error + 'static>(&self) -> bool {
606         // Get `TypeId` of the type this function is instantiated with.
607         let t = TypeId::of::<T>();
608
609         // Get `TypeId` of the type in the trait object.
610         let boxed = self.type_id(private::Internal);
611
612         // Compare both `TypeId`s on equality.
613         t == boxed
614     }
615
616     /// Returns some reference to the boxed value if it is of type `T`, or
617     /// `None` if it isn't.
618     #[stable(feature = "error_downcast", since = "1.3.0")]
619     #[inline]
620     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
621         if self.is::<T>() {
622             unsafe { Some(&*(self as *const dyn Error as *const T)) }
623         } else {
624             None
625         }
626     }
627
628     /// Returns some mutable reference to the boxed value if it is of type `T`, or
629     /// `None` if it isn't.
630     #[stable(feature = "error_downcast", since = "1.3.0")]
631     #[inline]
632     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
633         if self.is::<T>() {
634             unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
635         } else {
636             None
637         }
638     }
639 }
640
641 impl dyn Error + 'static + Send {
642     /// Forwards to the method defined on the type `dyn Error`.
643     #[stable(feature = "error_downcast", since = "1.3.0")]
644     #[inline]
645     pub fn is<T: Error + 'static>(&self) -> bool {
646         <dyn Error + 'static>::is::<T>(self)
647     }
648
649     /// Forwards to the method defined on the type `dyn Error`.
650     #[stable(feature = "error_downcast", since = "1.3.0")]
651     #[inline]
652     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
653         <dyn Error + 'static>::downcast_ref::<T>(self)
654     }
655
656     /// Forwards to the method defined on the type `dyn Error`.
657     #[stable(feature = "error_downcast", since = "1.3.0")]
658     #[inline]
659     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
660         <dyn Error + 'static>::downcast_mut::<T>(self)
661     }
662 }
663
664 impl dyn Error + 'static + Send + Sync {
665     /// Forwards to the method defined on the type `dyn Error`.
666     #[stable(feature = "error_downcast", since = "1.3.0")]
667     #[inline]
668     pub fn is<T: Error + 'static>(&self) -> bool {
669         <dyn Error + 'static>::is::<T>(self)
670     }
671
672     /// Forwards to the method defined on the type `dyn Error`.
673     #[stable(feature = "error_downcast", since = "1.3.0")]
674     #[inline]
675     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
676         <dyn Error + 'static>::downcast_ref::<T>(self)
677     }
678
679     /// Forwards to the method defined on the type `dyn Error`.
680     #[stable(feature = "error_downcast", since = "1.3.0")]
681     #[inline]
682     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
683         <dyn Error + 'static>::downcast_mut::<T>(self)
684     }
685 }
686
687 impl dyn Error {
688     #[inline]
689     #[stable(feature = "error_downcast", since = "1.3.0")]
690     /// Attempts to downcast the box to a concrete type.
691     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
692         if self.is::<T>() {
693             unsafe {
694                 let raw: *mut dyn Error = Box::into_raw(self);
695                 Ok(Box::from_raw(raw as *mut T))
696             }
697         } else {
698             Err(self)
699         }
700     }
701
702     /// Returns an iterator starting with the current error and continuing with
703     /// recursively calling [`Error::source`].
704     ///
705     /// If you want to omit the current error and only use its sources,
706     /// use `skip(1)`.
707     ///
708     /// # Examples
709     ///
710     /// ```
711     /// #![feature(error_iter)]
712     /// use std::error::Error;
713     /// use std::fmt;
714     ///
715     /// #[derive(Debug)]
716     /// struct A;
717     ///
718     /// #[derive(Debug)]
719     /// struct B(Option<Box<dyn Error + 'static>>);
720     ///
721     /// impl fmt::Display for A {
722     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723     ///         write!(f, "A")
724     ///     }
725     /// }
726     ///
727     /// impl fmt::Display for B {
728     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
729     ///         write!(f, "B")
730     ///     }
731     /// }
732     ///
733     /// impl Error for A {}
734     ///
735     /// impl Error for B {
736     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
737     ///         self.0.as_ref().map(|e| e.as_ref())
738     ///     }
739     /// }
740     ///
741     /// let b = B(Some(Box::new(A)));
742     ///
743     /// // let err : Box<Error> = b.into(); // or
744     /// let err = &b as &(dyn Error);
745     ///
746     /// let mut iter = err.chain();
747     ///
748     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
749     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
750     /// assert!(iter.next().is_none());
751     /// assert!(iter.next().is_none());
752     /// ```
753     #[unstable(feature = "error_iter", issue = "58520")]
754     #[inline]
755     pub fn chain(&self) -> Chain<'_> {
756         Chain { current: Some(self) }
757     }
758 }
759
760 /// An iterator over an [`Error`] and its sources.
761 ///
762 /// If you want to omit the initial error and only process
763 /// its sources, use `skip(1)`.
764 #[unstable(feature = "error_iter", issue = "58520")]
765 #[derive(Clone, Debug)]
766 pub struct Chain<'a> {
767     current: Option<&'a (dyn Error + 'static)>,
768 }
769
770 #[unstable(feature = "error_iter", issue = "58520")]
771 impl<'a> Iterator for Chain<'a> {
772     type Item = &'a (dyn Error + 'static);
773
774     fn next(&mut self) -> Option<Self::Item> {
775         let current = self.current;
776         self.current = self.current.and_then(Error::source);
777         current
778     }
779 }
780
781 impl dyn Error + Send {
782     #[inline]
783     #[stable(feature = "error_downcast", since = "1.3.0")]
784     /// Attempts to downcast the box to a concrete type.
785     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
786         let err: Box<dyn Error> = self;
787         <dyn Error>::downcast(err).map_err(|s| unsafe {
788             // Reapply the `Send` marker.
789             transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
790         })
791     }
792 }
793
794 impl dyn Error + Send + Sync {
795     #[inline]
796     #[stable(feature = "error_downcast", since = "1.3.0")]
797     /// Attempts to downcast the box to a concrete type.
798     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
799         let err: Box<dyn Error> = self;
800         <dyn Error>::downcast(err).map_err(|s| unsafe {
801             // Reapply the `Send + Sync` marker.
802             transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
803         })
804     }
805 }