]> git.lizzy.rs Git - rust.git/blob - src/libstd/error.rs
Rollup merge of #61382 - OptimisticPeach:patch-1, r=Centril
[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`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
258     /// [`Send`] + [`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`] + [`Send`] + [`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`] + [`Send`] + [`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`] + [`Send`] + [`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
565 #[stable(feature = "fmt_error", since = "1.11.0")]
566 impl Error for fmt::Error {
567     fn description(&self) -> &str {
568         "an error occurred when formatting an argument"
569     }
570 }
571
572 #[stable(feature = "try_borrow", since = "1.13.0")]
573 impl Error for cell::BorrowError {
574     fn description(&self) -> &str {
575         "already mutably borrowed"
576     }
577 }
578
579 #[stable(feature = "try_borrow", since = "1.13.0")]
580 impl Error for cell::BorrowMutError {
581     fn description(&self) -> &str {
582         "already borrowed"
583     }
584 }
585
586 #[stable(feature = "try_from", since = "1.34.0")]
587 impl Error for char::CharTryFromError {
588     fn description(&self) -> &str {
589         "converted integer out of range for `char`"
590     }
591 }
592
593 #[stable(feature = "char_from_str", since = "1.20.0")]
594 impl Error for char::ParseCharError {
595     fn description(&self) -> &str {
596         self.__description()
597     }
598 }
599
600 // copied from any.rs
601 impl dyn Error + 'static {
602     /// Returns `true` if the boxed type is the same as `T`
603     #[stable(feature = "error_downcast", since = "1.3.0")]
604     #[inline]
605     pub fn is<T: Error + 'static>(&self) -> bool {
606         // Get TypeId of the type this function is instantiated with
607         let t = TypeId::of::<T>();
608
609         // Get TypeId of the type in the trait object
610         let boxed = self.type_id(private::Internal);
611
612         // Compare both TypeIds on equality
613         t == boxed
614     }
615
616     /// Returns some reference to the boxed value if it is of type `T`, or
617     /// `None` if it isn't.
618     #[stable(feature = "error_downcast", since = "1.3.0")]
619     #[inline]
620     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
621         if self.is::<T>() {
622             unsafe {
623                 Some(&*(self as *const dyn Error as *const T))
624             }
625         } else {
626             None
627         }
628     }
629
630     /// Returns some mutable reference to the boxed value if it is of type `T`, or
631     /// `None` if it isn't.
632     #[stable(feature = "error_downcast", since = "1.3.0")]
633     #[inline]
634     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
635         if self.is::<T>() {
636             unsafe {
637                 Some(&mut *(self as *mut dyn Error as *mut T))
638             }
639         } else {
640             None
641         }
642     }
643 }
644
645 impl dyn Error + 'static + Send {
646     /// Forwards to the method defined on the type `Any`.
647     #[stable(feature = "error_downcast", since = "1.3.0")]
648     #[inline]
649     pub fn is<T: Error + 'static>(&self) -> bool {
650         <dyn Error + 'static>::is::<T>(self)
651     }
652
653     /// Forwards to the method defined on the type `Any`.
654     #[stable(feature = "error_downcast", since = "1.3.0")]
655     #[inline]
656     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
657         <dyn Error + 'static>::downcast_ref::<T>(self)
658     }
659
660     /// Forwards to the method defined on the type `Any`.
661     #[stable(feature = "error_downcast", since = "1.3.0")]
662     #[inline]
663     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
664         <dyn Error + 'static>::downcast_mut::<T>(self)
665     }
666 }
667
668 impl dyn Error + 'static + Send + Sync {
669     /// Forwards to the method defined on the type `Any`.
670     #[stable(feature = "error_downcast", since = "1.3.0")]
671     #[inline]
672     pub fn is<T: Error + 'static>(&self) -> bool {
673         <dyn Error + 'static>::is::<T>(self)
674     }
675
676     /// Forwards to the method defined on the type `Any`.
677     #[stable(feature = "error_downcast", since = "1.3.0")]
678     #[inline]
679     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
680         <dyn Error + 'static>::downcast_ref::<T>(self)
681     }
682
683     /// Forwards to the method defined on the type `Any`.
684     #[stable(feature = "error_downcast", since = "1.3.0")]
685     #[inline]
686     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
687         <dyn Error + 'static>::downcast_mut::<T>(self)
688     }
689 }
690
691 impl dyn Error {
692     #[inline]
693     #[stable(feature = "error_downcast", since = "1.3.0")]
694     /// Attempt to downcast the box to a concrete type.
695     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
696         if self.is::<T>() {
697             unsafe {
698                 let raw: *mut dyn Error = Box::into_raw(self);
699                 Ok(Box::from_raw(raw as *mut T))
700             }
701         } else {
702             Err(self)
703         }
704     }
705
706     /// Returns an iterator starting with the current error and continuing with
707     /// recursively calling [`source`].
708     ///
709     /// # Examples
710     ///
711     /// ```
712     /// #![feature(error_iter)]
713     /// use std::error::Error;
714     /// use std::fmt;
715     ///
716     /// #[derive(Debug)]
717     /// struct A;
718     ///
719     /// #[derive(Debug)]
720     /// struct B(Option<Box<dyn Error + 'static>>);
721     ///
722     /// impl fmt::Display for A {
723     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724     ///         write!(f, "A")
725     ///     }
726     /// }
727     ///
728     /// impl fmt::Display for B {
729     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730     ///         write!(f, "B")
731     ///     }
732     /// }
733     ///
734     /// impl Error for A {}
735     ///
736     /// impl Error for B {
737     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
738     ///         self.0.as_ref().map(|e| e.as_ref())
739     ///     }
740     /// }
741     ///
742     /// let b = B(Some(Box::new(A)));
743     ///
744     /// // let err : Box<Error> = b.into(); // or
745     /// let err = &b as &(dyn Error);
746     ///
747     /// let mut iter = err.iter_chain();
748     ///
749     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
750     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
751     /// assert!(iter.next().is_none());
752     /// assert!(iter.next().is_none());
753     /// ```
754     ///
755     /// [`source`]: trait.Error.html#method.source
756     #[unstable(feature = "error_iter", issue = "58520")]
757     #[inline]
758     pub fn iter_chain(&self) -> ErrorIter<'_> {
759         ErrorIter {
760             current: Some(self),
761         }
762     }
763
764     /// Returns an iterator starting with the [`source`] of this error
765     /// and continuing with recursively calling [`source`].
766     ///
767     /// # Examples
768     ///
769     /// ```
770     /// #![feature(error_iter)]
771     /// use std::error::Error;
772     /// use std::fmt;
773     ///
774     /// #[derive(Debug)]
775     /// struct A;
776     ///
777     /// #[derive(Debug)]
778     /// struct B(Option<Box<dyn Error + 'static>>);
779     ///
780     /// #[derive(Debug)]
781     /// struct C(Option<Box<dyn Error + 'static>>);
782     ///
783     /// impl fmt::Display for A {
784     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785     ///         write!(f, "A")
786     ///     }
787     /// }
788     ///
789     /// impl fmt::Display for B {
790     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791     ///         write!(f, "B")
792     ///     }
793     /// }
794     ///
795     /// impl fmt::Display for C {
796     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
797     ///         write!(f, "C")
798     ///     }
799     /// }
800     ///
801     /// impl Error for A {}
802     ///
803     /// impl Error for B {
804     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
805     ///         self.0.as_ref().map(|e| e.as_ref())
806     ///     }
807     /// }
808     ///
809     /// impl Error for C {
810     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
811     ///         self.0.as_ref().map(|e| e.as_ref())
812     ///     }
813     /// }
814     ///
815     /// let b = B(Some(Box::new(A)));
816     /// let c = C(Some(Box::new(b)));
817     ///
818     /// // let err : Box<Error> = c.into(); // or
819     /// let err = &c as &(dyn Error);
820     ///
821     /// let mut iter = err.iter_sources();
822     ///
823     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
824     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
825     /// assert!(iter.next().is_none());
826     /// assert!(iter.next().is_none());
827     /// ```
828     ///
829     /// [`source`]: trait.Error.html#method.source
830     #[inline]
831     #[unstable(feature = "error_iter", issue = "58520")]
832     pub fn iter_sources(&self) -> ErrorIter<'_> {
833         ErrorIter {
834             current: self.source(),
835         }
836     }
837 }
838
839 /// An iterator over [`Error`]
840 ///
841 /// [`Error`]: trait.Error.html
842 #[unstable(feature = "error_iter", issue = "58520")]
843 #[derive(Copy, Clone, Debug)]
844 pub struct ErrorIter<'a> {
845     current: Option<&'a (dyn Error + 'static)>,
846 }
847
848 #[unstable(feature = "error_iter", issue = "58520")]
849 impl<'a> Iterator for ErrorIter<'a> {
850     type Item = &'a (dyn Error + 'static);
851
852     fn next(&mut self) -> Option<Self::Item> {
853         let current = self.current;
854         self.current = self.current.and_then(Error::source);
855         current
856     }
857 }
858
859 impl dyn Error + Send {
860     #[inline]
861     #[stable(feature = "error_downcast", since = "1.3.0")]
862     /// Attempt to downcast the box to a concrete type.
863     pub fn downcast<T: Error + 'static>(self: Box<Self>)
864                                         -> Result<Box<T>, Box<dyn Error + Send>> {
865         let err: Box<dyn Error> = self;
866         <dyn Error>::downcast(err).map_err(|s| unsafe {
867             // reapply the Send marker
868             transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
869         })
870     }
871 }
872
873 impl dyn Error + Send + Sync {
874     #[inline]
875     #[stable(feature = "error_downcast", since = "1.3.0")]
876     /// Attempt to downcast the box to a concrete type.
877     pub fn downcast<T: Error + 'static>(self: Box<Self>)
878                                         -> Result<Box<T>, Box<Self>> {
879         let err: Box<dyn Error> = self;
880         <dyn Error>::downcast(err).map_err(|s| unsafe {
881             // reapply the Send+Sync marker
882             transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
883         })
884     }
885 }
886
887 #[cfg(test)]
888 mod tests {
889     use super::Error;
890     use crate::fmt;
891
892     #[derive(Debug, PartialEq)]
893     struct A;
894     #[derive(Debug, PartialEq)]
895     struct B;
896
897     impl fmt::Display for A {
898         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899             write!(f, "A")
900         }
901     }
902     impl fmt::Display for B {
903         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904             write!(f, "B")
905         }
906     }
907
908     impl Error for A {
909         fn description(&self) -> &str { "A-desc" }
910     }
911     impl Error for B {
912         fn description(&self) -> &str { "A-desc" }
913     }
914
915     #[test]
916     fn downcasting() {
917         let mut a = A;
918         let a = &mut a as &mut (dyn Error + 'static);
919         assert_eq!(a.downcast_ref::<A>(), Some(&A));
920         assert_eq!(a.downcast_ref::<B>(), None);
921         assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
922         assert_eq!(a.downcast_mut::<B>(), None);
923
924         let a: Box<dyn Error> = Box::new(A);
925         match a.downcast::<B>() {
926             Ok(..) => panic!("expected error"),
927             Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),
928         }
929     }
930 }