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