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