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