1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
use super::typeinfo::TypeInfo;
use core::any::{Any, TypeId};
use core::fmt::{Debug, Display};

#[cfg(feature = "alloc")]
use alloc::boxed::Box;

/// `Error` is a trait representing the basic expectations for error values,
/// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
/// themselves through the [`Display`] and [`Debug`] traits, and may provide
/// cause chain information:
///
/// The [`source`] method is generally used when errors cross "abstraction
/// boundaries". If one module must report an error that is caused by an error
/// from a lower-level module, it can allow access to that error via the
/// [`source`] method. This makes it possible for the high-level module to
/// provide its own errors while also revealing some of the implementation for
/// debugging via [`source`] chains.
///
/// [`Result<T, E>`]: ../result/enum.Result.html
/// [`Display`]: ../fmt/trait.Display.html
/// [`Debug`]: ../fmt/trait.Debug.html
/// [`source`]: trait.Error.html#method.source
pub trait Error: Debug + Display + TypeInfo {
    fn source(&self) -> Option<&(Error + 'static)> {
        None
    }
}

// Gated on 1.7.0 because on 1.6.0, Any requires Sized, causing the following
// code to not compile (`self.type_id()` fails because Error + 'static is not
// Sized).
impl Error + 'static {
    /// Returns `true` if the boxed type is the same as `T`
    pub fn is<T: Error + Any>(&self) -> bool {
        TypeId::of::<T>() == self.type_id()
    }

    /// Returns some reference to the boxed value if it is of type `T`, or
    /// `None` if it isn't.
    pub fn downcast_ref<T: Error + Any>(&self) -> Option<&T> {
        if self.is::<T>() {
            unsafe { Some(&*(self as *const Error as *const T)) }
        } else {
            None
        }
    }

    /// Returns some mutable reference to the boxed value if it is of type `T`,
    /// or `None` if it isn't.
    pub fn downcast_mut<T: Error + Any>(&mut self) -> Option<&mut T> {
        if self.is::<T>() {
            unsafe { Some(&mut *(self as *mut Error as *mut T)) }
        } else {
            None
        }
    }
}

impl Error + 'static + Send {
    /// Returns `true` if the boxed type is the same as `T`
    pub fn is<T: Error + Any>(&self) -> bool {
        TypeId::of::<T>() == self.type_id()
    }

    /// Returns some reference to the boxed value if it is of type `T`, or
    /// `None` if it isn't.
    pub fn downcast_ref<T: Error + Any>(&self) -> Option<&T> {
        if self.is::<T>() {
            unsafe { Some(&*(self as *const Error as *const T)) }
        } else {
            None
        }
    }

    /// Returns some mutable reference to the boxed value if it is of type `T`,
    /// or `None` if it isn't.
    pub fn downcast_mut<T: Error + Any>(&mut self) -> Option<&mut T> {
        if self.is::<T>() {
            unsafe { Some(&mut *(self as *mut Error as *mut T)) }
        } else {
            None
        }
    }
}

impl Error + 'static + Send + Sync {
    /// Returns `true` if the boxed type is the same as `T`
    pub fn is<T: Error + Any>(&self) -> bool {
        TypeId::of::<T>() == self.type_id()
    }

    /// Returns some reference to the boxed value if it is of type `T`, or
    /// `None` if it isn't.
    pub fn downcast_ref<T: Error + Any>(&self) -> Option<&T> {
        if self.is::<T>() {
            unsafe { Some(&*(self as *const Error as *const T)) }
        } else {
            None
        }
    }

    /// Returns some mutable reference to the boxed value if it is of type `T`,
    /// or `None` if it isn't.
    pub fn downcast_mut<T: Error + Any>(&mut self) -> Option<&mut T> {
        if self.is::<T>() {
            unsafe { Some(&mut *(self as *mut Error as *mut T)) }
        } else {
            None
        }
    }
}

#[cfg(feature = "alloc")]
impl Error {
    /// Attempt to downcast the box to a concrete type.
    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error>> {
        if self.is::<T>() {
            unsafe {
                let raw: *mut Error = Box::into_raw(self);
                Ok(Box::from_raw(raw as *mut T))
            }
        } else {
            Err(self)
        }
    }
}

#[cfg(feature = "alloc")]
impl Error + Send {
    /// Attempt to downcast the box to a concrete type.
    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error>> {
        if self.is::<T>() {
            unsafe {
                let raw: *mut Error = Box::into_raw(self);
                Ok(Box::from_raw(raw as *mut T))
            }
        } else {
            Err(self)
        }
    }
}

#[cfg(feature = "alloc")]
impl Error + Send + Sync {
    /// Attempt to downcast the box to a concrete type.
    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error>> {
        if self.is::<T>() {
            unsafe {
                let raw: *mut Error = Box::into_raw(self);
                Ok(Box::from_raw(raw as *mut T))
            }
        } else {
            Err(self)
        }
    }
}

macro_rules! impl_error {
    ($( #[$version:meta] $ty:path,)*) => {
        $(
            #[$version]
            impl Error for $ty { }
        )*
    };
}

impl_error! {
    #[cfg(rustc_1_0_0)]   ::core::str::ParseBoolError,
    #[cfg(rustc_1_0_0)]   ::core::str::Utf8Error,
    #[cfg(rustc_1_0_0)]   ::core::num::ParseIntError,
    #[cfg(rustc_1_0_0)]   ::core::num::ParseFloatError,
    #[cfg(rustc_1_11_0)]  ::core::fmt::Error,
    #[cfg(rustc_1_13_0)]  ::core::cell::BorrowMutError,
    #[cfg(rustc_1_13_0)]  ::core::cell::BorrowError,
    #[cfg(rustc_1_20_0)]  ::core::char::ParseCharError,
    // Added in 1.27.0 in libcore. Added in 1.9.0 in libstd.
    // Rust is full of lies.
    #[cfg(rustc_1_27_0)]  ::core::char::DecodeUtf16Error,
    #[cfg(rustc_1_28_0)]  ::core::alloc::LayoutErr,
    #[cfg(rustc_1_34_0)]  ::core::num::TryFromIntError,
    #[cfg(rustc_1_34_0)]  ::core::array::TryFromSliceError,
    #[cfg(rustc_1_34_0)]  ::core::char::CharTryFromError,

    // This implementation is actually ParseError in disguise. ParseError is a
    // type alias to Infallible. In order to avoid having the alloc feature
    // toggling the error impl on Infallible (which would be confusing), we will
    // just unconditionally impl it here.
    #[cfg(rustc_1_34_0)]  ::core::convert::Infallible,
}

#[cfg(feature = "alloc")]
impl_error! {
    #[cfg(rustc_1_36_0)] ::alloc::string::FromUtf16Error,
    #[cfg(rustc_1_36_0)] ::alloc::string::FromUtf8Error,
}

#[cfg(feature = "alloc")]
impl<T: Error> Error for Box<T> {
    fn source(&self) -> Option<&(Error + 'static)> {
        Error::source(&**self)
    }
}

#[cfg(test)]
mod test {
    // Ensure that ParseError implements Error
    #[cfg(all(rustc_1_36_0, feature = "alloc"))]
    const _ASSERT_PARSE_ERROR_IMPLS_ERROR: fn() = || {
        fn assert_impl<T: ?Sized + super::Error>() {}
        assert_impl::<::alloc::string::ParseError>();
    };
}