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