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