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