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