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