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