]> git.lizzy.rs Git - rust.git/blob - src/libstd/error.rs
Rollup merge of #60130 - khuey:efficient_last, r=sfackler
[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     #[doc(hidden)]
201     #[unstable(feature = "error_type_id",
202                reason = "this is memory unsafe to override in user code",
203                issue = "60784")]
204     fn type_id(&self) -> TypeId where Self: 'static {
205         TypeId::of::<Self>()
206     }
207 }
208
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
211     /// Converts a type of [`Error`] into a box of dyn [`Error`].
212     ///
213     /// # Examples
214     ///
215     /// ```
216     /// use std::error::Error;
217     /// use std::fmt;
218     /// use std::mem;
219     ///
220     /// #[derive(Debug)]
221     /// struct AnError;
222     ///
223     /// impl fmt::Display for AnError {
224     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225     ///         write!(f , "An error")
226     ///     }
227     /// }
228     ///
229     /// impl Error for AnError {
230     ///     fn description(&self) -> &str {
231     ///         "Description of an error"
232     ///     }
233     /// }
234     ///
235     /// let an_error = AnError;
236     /// assert!(0 == mem::size_of_val(&an_error));
237     /// let a_boxed_error = Box::<Error>::from(an_error);
238     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
239     /// ```
240     fn from(err: E) -> Box<dyn Error + 'a> {
241         Box::new(err)
242     }
243 }
244
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
247     /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
248     /// [`Send`] + [`Sync`].
249     ///
250     /// # Examples
251     ///
252     /// ```
253     /// use std::error::Error;
254     /// use std::fmt;
255     /// use std::mem;
256     ///
257     /// #[derive(Debug)]
258     /// struct AnError;
259     ///
260     /// impl fmt::Display for AnError {
261     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262     ///         write!(f , "An error")
263     ///     }
264     /// }
265     ///
266     /// impl Error for AnError {
267     ///     fn description(&self) -> &str {
268     ///         "Description of an error"
269     ///     }
270     /// }
271     ///
272     /// unsafe impl Send for AnError {}
273     ///
274     /// unsafe impl Sync for AnError {}
275     ///
276     /// let an_error = AnError;
277     /// assert!(0 == mem::size_of_val(&an_error));
278     /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
279     /// assert!(
280     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
281     /// ```
282     fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
283         Box::new(err)
284     }
285 }
286
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl From<String> for Box<dyn Error + Send + Sync> {
289     /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
290     ///
291     /// # Examples
292     ///
293     /// ```
294     /// use std::error::Error;
295     /// use std::mem;
296     ///
297     /// let a_string_error = "a string error".to_string();
298     /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
299     /// assert!(
300     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
301     /// ```
302     fn from(err: String) -> Box<dyn Error + Send + Sync> {
303         #[derive(Debug)]
304         struct StringError(String);
305
306         impl Error for StringError {
307             fn description(&self) -> &str { &self.0 }
308         }
309
310         impl Display for StringError {
311             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312                 Display::fmt(&self.0, f)
313             }
314         }
315
316         Box::new(StringError(err))
317     }
318 }
319
320 #[stable(feature = "string_box_error", since = "1.6.0")]
321 impl From<String> for Box<dyn Error> {
322     /// Converts a [`String`] into a box of dyn [`Error`].
323     ///
324     /// # Examples
325     ///
326     /// ```
327     /// use std::error::Error;
328     /// use std::mem;
329     ///
330     /// let a_string_error = "a string error".to_string();
331     /// let a_boxed_error = Box::<Error>::from(a_string_error);
332     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
333     /// ```
334     fn from(str_err: String) -> Box<dyn Error> {
335         let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
336         let err2: Box<dyn Error> = err1;
337         err2
338     }
339 }
340
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
343     /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
344     ///
345     /// # Examples
346     ///
347     /// ```
348     /// use std::error::Error;
349     /// use std::mem;
350     ///
351     /// let a_str_error = "a str error";
352     /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
353     /// assert!(
354     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
355     /// ```
356     fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
357         From::from(String::from(err))
358     }
359 }
360
361 #[stable(feature = "string_box_error", since = "1.6.0")]
362 impl From<&str> for Box<dyn Error> {
363     /// Converts a [`str`] into a box of dyn [`Error`].
364     ///
365     /// # Examples
366     ///
367     /// ```
368     /// use std::error::Error;
369     /// use std::mem;
370     ///
371     /// let a_str_error = "a str error";
372     /// let a_boxed_error = Box::<Error>::from(a_str_error);
373     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
374     /// ```
375     fn from(err: &str) -> Box<dyn Error> {
376         From::from(String::from(err))
377     }
378 }
379
380 #[stable(feature = "cow_box_error", since = "1.22.0")]
381 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
382     /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
383     ///
384     /// # Examples
385     ///
386     /// ```
387     /// use std::error::Error;
388     /// use std::mem;
389     /// use std::borrow::Cow;
390     ///
391     /// let a_cow_str_error = Cow::from("a str error");
392     /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
393     /// assert!(
394     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
395     /// ```
396     fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
397         From::from(String::from(err))
398     }
399 }
400
401 #[stable(feature = "cow_box_error", since = "1.22.0")]
402 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
403     /// Converts a [`Cow`] into a box of dyn [`Error`].
404     ///
405     /// # Examples
406     ///
407     /// ```
408     /// use std::error::Error;
409     /// use std::mem;
410     /// use std::borrow::Cow;
411     ///
412     /// let a_cow_str_error = Cow::from("a str error");
413     /// let a_boxed_error = Box::<Error>::from(a_cow_str_error);
414     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
415     /// ```
416     fn from(err: Cow<'a, str>) -> Box<dyn Error> {
417         From::from(String::from(err))
418     }
419 }
420
421 #[unstable(feature = "never_type", issue = "35121")]
422 impl Error for ! {
423     fn description(&self) -> &str { *self }
424 }
425
426 #[unstable(feature = "allocator_api",
427            reason = "the precise API and guarantees it provides may be tweaked.",
428            issue = "32838")]
429 impl Error for AllocErr {
430     fn description(&self) -> &str {
431         "memory allocation failed"
432     }
433 }
434
435 #[unstable(feature = "allocator_api",
436            reason = "the precise API and guarantees it provides may be tweaked.",
437            issue = "32838")]
438 impl Error for LayoutErr {
439     fn description(&self) -> &str {
440         "invalid parameters to Layout::from_size_align"
441     }
442 }
443
444 #[unstable(feature = "allocator_api",
445            reason = "the precise API and guarantees it provides may be tweaked.",
446            issue = "32838")]
447 impl Error for CannotReallocInPlace {
448     fn description(&self) -> &str {
449         CannotReallocInPlace::description(self)
450     }
451 }
452
453 #[stable(feature = "rust1", since = "1.0.0")]
454 impl Error for str::ParseBoolError {
455     fn description(&self) -> &str { "failed to parse bool" }
456 }
457
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl Error for str::Utf8Error {
460     fn description(&self) -> &str {
461         "invalid utf-8: corrupt contents"
462     }
463 }
464
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl Error for num::ParseIntError {
467     fn description(&self) -> &str {
468         self.__description()
469     }
470 }
471
472 #[stable(feature = "try_from", since = "1.34.0")]
473 impl Error for num::TryFromIntError {
474     fn description(&self) -> &str {
475         self.__description()
476     }
477 }
478
479 #[stable(feature = "try_from", since = "1.34.0")]
480 impl Error for array::TryFromSliceError {
481     fn description(&self) -> &str {
482         self.__description()
483     }
484 }
485
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl Error for num::ParseFloatError {
488     fn description(&self) -> &str {
489         self.__description()
490     }
491 }
492
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl Error for string::FromUtf8Error {
495     fn description(&self) -> &str {
496         "invalid utf-8"
497     }
498 }
499
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl Error for string::FromUtf16Error {
502     fn description(&self) -> &str {
503         "invalid utf-16"
504     }
505 }
506
507 #[stable(feature = "str_parse_error2", since = "1.8.0")]
508 impl Error for string::ParseError {
509     fn description(&self) -> &str {
510         match *self {}
511     }
512 }
513
514 #[stable(feature = "decode_utf16", since = "1.9.0")]
515 impl Error for char::DecodeUtf16Error {
516     fn description(&self) -> &str {
517         "unpaired surrogate found"
518     }
519 }
520
521 #[stable(feature = "box_error", since = "1.8.0")]
522 impl<T: Error> Error for Box<T> {
523     fn description(&self) -> &str {
524         Error::description(&**self)
525     }
526
527     #[allow(deprecated)]
528     fn cause(&self) -> Option<&dyn Error> {
529         Error::cause(&**self)
530     }
531 }
532
533 #[stable(feature = "fmt_error", since = "1.11.0")]
534 impl Error for fmt::Error {
535     fn description(&self) -> &str {
536         "an error occurred when formatting an argument"
537     }
538 }
539
540 #[stable(feature = "try_borrow", since = "1.13.0")]
541 impl Error for cell::BorrowError {
542     fn description(&self) -> &str {
543         "already mutably borrowed"
544     }
545 }
546
547 #[stable(feature = "try_borrow", since = "1.13.0")]
548 impl Error for cell::BorrowMutError {
549     fn description(&self) -> &str {
550         "already borrowed"
551     }
552 }
553
554 #[stable(feature = "try_from", since = "1.34.0")]
555 impl Error for char::CharTryFromError {
556     fn description(&self) -> &str {
557         "converted integer out of range for `char`"
558     }
559 }
560
561 #[stable(feature = "char_from_str", since = "1.20.0")]
562 impl Error for char::ParseCharError {
563     fn description(&self) -> &str {
564         self.__description()
565     }
566 }
567
568 // copied from any.rs
569 impl dyn Error + 'static {
570     /// Returns `true` if the boxed type is the same as `T`
571     #[stable(feature = "error_downcast", since = "1.3.0")]
572     #[inline]
573     pub fn is<T: Error + 'static>(&self) -> bool {
574         // Get TypeId of the type this function is instantiated with
575         let t = TypeId::of::<T>();
576
577         // Get TypeId of the type in the trait object
578         let boxed = self.type_id();
579
580         // Compare both TypeIds on equality
581         t == boxed
582     }
583
584     /// Returns some reference to the boxed value if it is of type `T`, or
585     /// `None` if it isn't.
586     #[stable(feature = "error_downcast", since = "1.3.0")]
587     #[inline]
588     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
589         if self.is::<T>() {
590             unsafe {
591                 Some(&*(self as *const dyn Error as *const T))
592             }
593         } else {
594             None
595         }
596     }
597
598     /// Returns some mutable reference to the boxed value if it is of type `T`, or
599     /// `None` if it isn't.
600     #[stable(feature = "error_downcast", since = "1.3.0")]
601     #[inline]
602     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
603         if self.is::<T>() {
604             unsafe {
605                 Some(&mut *(self as *mut dyn Error as *mut T))
606             }
607         } else {
608             None
609         }
610     }
611 }
612
613 impl dyn Error + 'static + Send {
614     /// Forwards to the method defined on the type `Any`.
615     #[stable(feature = "error_downcast", since = "1.3.0")]
616     #[inline]
617     pub fn is<T: Error + 'static>(&self) -> bool {
618         <dyn Error + 'static>::is::<T>(self)
619     }
620
621     /// Forwards to the method defined on the type `Any`.
622     #[stable(feature = "error_downcast", since = "1.3.0")]
623     #[inline]
624     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
625         <dyn Error + 'static>::downcast_ref::<T>(self)
626     }
627
628     /// Forwards to the method defined on the type `Any`.
629     #[stable(feature = "error_downcast", since = "1.3.0")]
630     #[inline]
631     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
632         <dyn Error + 'static>::downcast_mut::<T>(self)
633     }
634 }
635
636 impl dyn Error + 'static + Send + Sync {
637     /// Forwards to the method defined on the type `Any`.
638     #[stable(feature = "error_downcast", since = "1.3.0")]
639     #[inline]
640     pub fn is<T: Error + 'static>(&self) -> bool {
641         <dyn Error + 'static>::is::<T>(self)
642     }
643
644     /// Forwards to the method defined on the type `Any`.
645     #[stable(feature = "error_downcast", since = "1.3.0")]
646     #[inline]
647     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
648         <dyn Error + 'static>::downcast_ref::<T>(self)
649     }
650
651     /// Forwards to the method defined on the type `Any`.
652     #[stable(feature = "error_downcast", since = "1.3.0")]
653     #[inline]
654     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
655         <dyn Error + 'static>::downcast_mut::<T>(self)
656     }
657 }
658
659 impl dyn Error {
660     #[inline]
661     #[stable(feature = "error_downcast", since = "1.3.0")]
662     /// Attempt to downcast the box to a concrete type.
663     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
664         if self.is::<T>() {
665             unsafe {
666                 let raw: *mut dyn Error = Box::into_raw(self);
667                 Ok(Box::from_raw(raw as *mut T))
668             }
669         } else {
670             Err(self)
671         }
672     }
673
674     /// Returns an iterator starting with the current error and continuing with
675     /// recursively calling [`source`].
676     ///
677     /// # Examples
678     ///
679     /// ```
680     /// #![feature(error_iter)]
681     /// use std::error::Error;
682     /// use std::fmt;
683     ///
684     /// #[derive(Debug)]
685     /// struct A;
686     ///
687     /// #[derive(Debug)]
688     /// struct B(Option<Box<dyn Error + 'static>>);
689     ///
690     /// impl fmt::Display for A {
691     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692     ///         write!(f, "A")
693     ///     }
694     /// }
695     ///
696     /// impl fmt::Display for B {
697     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698     ///         write!(f, "B")
699     ///     }
700     /// }
701     ///
702     /// impl Error for A {}
703     ///
704     /// impl Error for B {
705     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
706     ///         self.0.as_ref().map(|e| e.as_ref())
707     ///     }
708     /// }
709     ///
710     /// let b = B(Some(Box::new(A)));
711     ///
712     /// // let err : Box<Error> = b.into(); // or
713     /// let err = &b as &(dyn Error);
714     ///
715     /// let mut iter = err.iter_chain();
716     ///
717     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
718     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
719     /// assert!(iter.next().is_none());
720     /// assert!(iter.next().is_none());
721     /// ```
722     ///
723     /// [`source`]: trait.Error.html#method.source
724     #[unstable(feature = "error_iter", issue = "58520")]
725     #[inline]
726     pub fn iter_chain(&self) -> ErrorIter<'_> {
727         ErrorIter {
728             current: Some(self),
729         }
730     }
731
732     /// Returns an iterator starting with the [`source`] of this error
733     /// and continuing with recursively calling [`source`].
734     ///
735     /// # Examples
736     ///
737     /// ```
738     /// #![feature(error_iter)]
739     /// use std::error::Error;
740     /// use std::fmt;
741     ///
742     /// #[derive(Debug)]
743     /// struct A;
744     ///
745     /// #[derive(Debug)]
746     /// struct B(Option<Box<dyn Error + 'static>>);
747     ///
748     /// #[derive(Debug)]
749     /// struct C(Option<Box<dyn Error + 'static>>);
750     ///
751     /// impl fmt::Display for A {
752     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753     ///         write!(f, "A")
754     ///     }
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 fmt::Display for C {
764     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765     ///         write!(f, "C")
766     ///     }
767     /// }
768     ///
769     /// impl Error for A {}
770     ///
771     /// impl Error for B {
772     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
773     ///         self.0.as_ref().map(|e| e.as_ref())
774     ///     }
775     /// }
776     ///
777     /// impl Error for C {
778     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
779     ///         self.0.as_ref().map(|e| e.as_ref())
780     ///     }
781     /// }
782     ///
783     /// let b = B(Some(Box::new(A)));
784     /// let c = C(Some(Box::new(b)));
785     ///
786     /// // let err : Box<Error> = c.into(); // or
787     /// let err = &c as &(dyn Error);
788     ///
789     /// let mut iter = err.iter_sources();
790     ///
791     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
792     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
793     /// assert!(iter.next().is_none());
794     /// assert!(iter.next().is_none());
795     /// ```
796     ///
797     /// [`source`]: trait.Error.html#method.source
798     #[inline]
799     #[unstable(feature = "error_iter", issue = "58520")]
800     pub fn iter_sources(&self) -> ErrorIter<'_> {
801         ErrorIter {
802             current: self.source(),
803         }
804     }
805 }
806
807 /// An iterator over [`Error`]
808 ///
809 /// [`Error`]: trait.Error.html
810 #[unstable(feature = "error_iter", issue = "58520")]
811 #[derive(Copy, Clone, Debug)]
812 pub struct ErrorIter<'a> {
813     current: Option<&'a (dyn Error + 'static)>,
814 }
815
816 #[unstable(feature = "error_iter", issue = "58520")]
817 impl<'a> Iterator for ErrorIter<'a> {
818     type Item = &'a (dyn Error + 'static);
819
820     fn next(&mut self) -> Option<Self::Item> {
821         let current = self.current;
822         self.current = self.current.and_then(Error::source);
823         current
824     }
825 }
826
827 impl dyn Error + Send {
828     #[inline]
829     #[stable(feature = "error_downcast", since = "1.3.0")]
830     /// Attempt to downcast the box to a concrete type.
831     pub fn downcast<T: Error + 'static>(self: Box<Self>)
832                                         -> Result<Box<T>, Box<dyn Error + Send>> {
833         let err: Box<dyn Error> = self;
834         <dyn Error>::downcast(err).map_err(|s| unsafe {
835             // reapply the Send marker
836             transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
837         })
838     }
839 }
840
841 impl dyn Error + Send + Sync {
842     #[inline]
843     #[stable(feature = "error_downcast", since = "1.3.0")]
844     /// Attempt to downcast the box to a concrete type.
845     pub fn downcast<T: Error + 'static>(self: Box<Self>)
846                                         -> Result<Box<T>, Box<Self>> {
847         let err: Box<dyn Error> = self;
848         <dyn Error>::downcast(err).map_err(|s| unsafe {
849             // reapply the Send+Sync marker
850             transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
851         })
852     }
853 }
854
855 #[cfg(test)]
856 mod tests {
857     use super::Error;
858     use crate::fmt;
859
860     #[derive(Debug, PartialEq)]
861     struct A;
862     #[derive(Debug, PartialEq)]
863     struct B;
864
865     impl fmt::Display for A {
866         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867             write!(f, "A")
868         }
869     }
870     impl fmt::Display for B {
871         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872             write!(f, "B")
873         }
874     }
875
876     impl Error for A {
877         fn description(&self) -> &str { "A-desc" }
878     }
879     impl Error for B {
880         fn description(&self) -> &str { "A-desc" }
881     }
882
883     #[test]
884     fn downcasting() {
885         let mut a = A;
886         let a = &mut a as &mut (dyn Error + 'static);
887         assert_eq!(a.downcast_ref::<A>(), Some(&A));
888         assert_eq!(a.downcast_ref::<B>(), None);
889         assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
890         assert_eq!(a.downcast_mut::<B>(), None);
891
892         let a: Box<dyn Error> = Box::new(A);
893         match a.downcast::<B>() {
894             Ok(..) => panic!("expected error"),
895             Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),
896         }
897     }
898 }