Skip to content
Myr

error.rs

This file

Path

src/error.rs

801 lines · 27.0 KiB · Rust

Last changed by

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

History of this file

Take it

1use crate::alloc::Box;2use crate::backtrace::Backtrace;3use crate::chain::Chain;4use crate::{Error, StdError};5use core::any::TypeId;6use core::fmt::{self, Debug, Display};7use core::mem::{self, ManuallyDrop};8use core::ptr::{self, NonNull};910#[cfg(feature = "std")]11use core::ops::{Deref, DerefMut};1213impl Error {14    /// Create a new error object from any error type.15    ///16    /// The error type must be threadsafe and `'static`, so that the `Error`17    /// will be as well.18    ///19    /// If the error type does not provide a backtrace, a backtrace will be20    /// created here to ensure that a backtrace exists.21    #[cfg(feature = "std")]22    pub fn new<E>(error: E) -> Self23    where24        E: StdError + Send + Sync + 'static,25    {26        let backtrace = backtrace_if_absent!(error);27        Error::from_std(error, backtrace)28    }2930    /// Create a new error object from a printable error message.31    ///32    /// If the argument implements std::error::Error, prefer `Error::new`33    /// instead which preserves the underlying error's cause chain and34    /// backtrace. If the argument may or may not implement std::error::Error35    /// now or in the future, use `anyhow!(err)` which handles either way36    /// correctly.37    ///38    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally39    /// convenient in places where a function is preferable over a macro, such40    /// as iterator or stream combinators:41    ///42    /// ```43    /// # mod ffi {44    /// #     pub struct Input;45    /// #     pub struct Output;46    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {47    /// #         unimplemented!()48    /// #     }49    /// # }50    /// #51    /// # use ffi::{Input, Output};52    /// #53    /// use anyhow::{Error, Result};54    /// use futures::stream::{Stream, StreamExt, TryStreamExt};55    ///56    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>57    /// where58    ///     S: Stream<Item = Input>,59    /// {60    ///     stream61    ///         .then(ffi::do_some_work) // returns Result<Output, &str>62    ///         .map_err(Error::msg)63    ///         .try_collect()64    ///         .await65    /// }66    /// ```67    pub fn msg<M>(message: M) -> Self68    where69        M: Display + Debug + Send + Sync + 'static,70    {71        Error::from_adhoc(message, backtrace!())72    }7374    #[cfg(feature = "std")]75    pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self76    where77        E: StdError + Send + Sync + 'static,78    {79        let vtable = &ErrorVTable {80            object_drop: object_drop::<E>,81            object_ref: object_ref::<E>,82            #[cfg(feature = "std")]83            object_mut: object_mut::<E>,84            object_boxed: object_boxed::<E>,85            object_downcast: object_downcast::<E>,86            object_drop_rest: object_drop_front::<E>,87        };8889        // Safety: passing vtable that operates on the right type E.90        unsafe { Error::construct(error, vtable, backtrace) }91    }9293    pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self94    where95        M: Display + Debug + Send + Sync + 'static,96    {97        use crate::wrapper::MessageError;98        let error: MessageError<M> = MessageError(message);99        let vtable = &ErrorVTable {100            object_drop: object_drop::<MessageError<M>>,101            object_ref: object_ref::<MessageError<M>>,102            #[cfg(feature = "std")]103            object_mut: object_mut::<MessageError<M>>,104            object_boxed: object_boxed::<MessageError<M>>,105            object_downcast: object_downcast::<M>,106            object_drop_rest: object_drop_front::<M>,107        };108109        // Safety: MessageError is repr(transparent) so it is okay for the110        // vtable to allow casting the MessageError<M> to M.111        unsafe { Error::construct(error, vtable, backtrace) }112    }113114    pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self115    where116        M: Display + Send + Sync + 'static,117    {118        use crate::wrapper::DisplayError;119        let error: DisplayError<M> = DisplayError(message);120        let vtable = &ErrorVTable {121            object_drop: object_drop::<DisplayError<M>>,122            object_ref: object_ref::<DisplayError<M>>,123            #[cfg(feature = "std")]124            object_mut: object_mut::<DisplayError<M>>,125            object_boxed: object_boxed::<DisplayError<M>>,126            object_downcast: object_downcast::<M>,127            object_drop_rest: object_drop_front::<M>,128        };129130        // Safety: DisplayError is repr(transparent) so it is okay for the131        // vtable to allow casting the DisplayError<M> to M.132        unsafe { Error::construct(error, vtable, backtrace) }133    }134135    #[cfg(feature = "std")]136    pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self137    where138        C: Display + Send + Sync + 'static,139        E: StdError + Send + Sync + 'static,140    {141        let error: ContextError<C, E> = ContextError { context, error };142143        let vtable = &ErrorVTable {144            object_drop: object_drop::<ContextError<C, E>>,145            object_ref: object_ref::<ContextError<C, E>>,146            #[cfg(feature = "std")]147            object_mut: object_mut::<ContextError<C, E>>,148            object_boxed: object_boxed::<ContextError<C, E>>,149            object_downcast: context_downcast::<C, E>,150            object_drop_rest: context_drop_rest::<C, E>,151        };152153        // Safety: passing vtable that operates on the right type.154        unsafe { Error::construct(error, vtable, backtrace) }155    }156157    #[cfg(feature = "std")]158    pub(crate) fn from_boxed(159        error: Box<dyn StdError + Send + Sync>,160        backtrace: Option<Backtrace>,161    ) -> Self {162        use crate::wrapper::BoxedError;163        let error = BoxedError(error);164        let vtable = &ErrorVTable {165            object_drop: object_drop::<BoxedError>,166            object_ref: object_ref::<BoxedError>,167            #[cfg(feature = "std")]168            object_mut: object_mut::<BoxedError>,169            object_boxed: object_boxed::<BoxedError>,170            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,171            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,172        };173174        // Safety: BoxedError is repr(transparent) so it is okay for the vtable175        // to allow casting to Box<dyn StdError + Send + Sync>.176        unsafe { Error::construct(error, vtable, backtrace) }177    }178179    // Takes backtrace as argument rather than capturing it here so that the180    // user sees one fewer layer of wrapping noise in the backtrace.181    //182    // Unsafe because the given vtable must have sensible behavior on the error183    // value of type E.184    unsafe fn construct<E>(185        error: E,186        vtable: &'static ErrorVTable,187        backtrace: Option<Backtrace>,188    ) -> Self189    where190        E: StdError + Send + Sync + 'static,191    {192        let inner = Box::new(ErrorImpl {193            vtable,194            backtrace,195            _object: error,196        });197        // Erase the concrete type of E from the compile-time type system. This198        // is equivalent to the safe unsize coersion from Box<ErrorImpl<E>> to199        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the200        // result is a thin pointer. The necessary behavior for manipulating the201        // underlying ErrorImpl<E> is preserved in the vtable provided by the202        // caller rather than a builtin fat pointer vtable.203        let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);204        let inner = ManuallyDrop::new(erased);205        Error { inner }206    }207208    /// Wrap the error value with additional context.209    ///210    /// For attaching context to a `Result` as it is propagated, the211    /// [`Context`][crate::Context] extension trait may be more convenient than212    /// this function.213    ///214    /// The primary reason to use `error.context(...)` instead of215    /// `result.context(...)` via the `Context` trait would be if the context216    /// needs to depend on some data held by the underlying error:217    ///218    /// ```219    /// # use std::fmt::{self, Debug, Display};220    /// #221    /// # type T = ();222    /// #223    /// # impl std::error::Error for ParseError {}224    /// # impl Debug for ParseError {225    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {226    /// #         unimplemented!()227    /// #     }228    /// # }229    /// # impl Display for ParseError {230    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {231    /// #         unimplemented!()232    /// #     }233    /// # }234    /// #235    /// use anyhow::Result;236    /// use std::fs::File;237    /// use std::path::Path;238    ///239    /// struct ParseError {240    ///     line: usize,241    ///     column: usize,242    /// }243    ///244    /// fn parse_impl(file: File) -> Result<T, ParseError> {245    ///     # const IGNORE: &str = stringify! {246    ///     ...247    ///     # };248    ///     # unimplemented!()249    /// }250    ///251    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {252    ///     let file = File::open(&path)?;253    ///     parse_impl(file).map_err(|error| {254    ///         let context = format!(255    ///             "only the first {} lines of {} are valid",256    ///             error.line, path.as_ref().display(),257    ///         );258    ///         anyhow::Error::new(error).context(context)259    ///     })260    /// }261    /// ```262    pub fn context<C>(self, context: C) -> Self263    where264        C: Display + Send + Sync + 'static,265    {266        let error: ContextError<C, Error> = ContextError {267            context,268            error: self,269        };270271        let vtable = &ErrorVTable {272            object_drop: object_drop::<ContextError<C, Error>>,273            object_ref: object_ref::<ContextError<C, Error>>,274            #[cfg(feature = "std")]275            object_mut: object_mut::<ContextError<C, Error>>,276            object_boxed: object_boxed::<ContextError<C, Error>>,277            object_downcast: context_chain_downcast::<C>,278            object_drop_rest: context_chain_drop_rest::<C>,279        };280281        // As the cause is anyhow::Error, we already have a backtrace for it.282        let backtrace = None;283284        // Safety: passing vtable that operates on the right type.285        unsafe { Error::construct(error, vtable, backtrace) }286    }287288    /// Get the backtrace for this Error.289    ///290    /// Backtraces are only available on the nightly channel. Tracking issue:291    /// [rust-lang/rust#53487][tracking].292    ///293    /// In order for the backtrace to be meaningful, one of the two environment294    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined295    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat296    /// expensive to capture in Rust, so we don't necessarily want to be297    /// capturing them all over the place all the time.298    ///299    /// - If you want panics and errors to both have backtraces, set300    ///   `RUST_BACKTRACE=1`;301    /// - If you want only errors to have backtraces, set302    ///   `RUST_LIB_BACKTRACE=1`;303    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and304    ///   `RUST_LIB_BACKTRACE=0`.305    ///306    /// [tracking]: https://github.com/rust-lang/rust/issues/53487307    #[cfg(backtrace)]308    pub fn backtrace(&self) -> &Backtrace {309        self.inner.backtrace()310    }311312    /// An iterator of the chain of source errors contained by this Error.313    ///314    /// This iterator will visit every error in the cause chain of this error315    /// object, beginning with the error that this error object was created316    /// from.317    ///318    /// # Example319    ///320    /// ```321    /// use anyhow::Error;322    /// use std::io;323    ///324    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {325    ///     for cause in error.chain() {326    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {327    ///             return Some(io_error.kind());328    ///         }329    ///     }330    ///     None331    /// }332    /// ```333    #[cfg(feature = "std")]334    pub fn chain(&self) -> Chain {335        self.inner.chain()336    }337338    /// The lowest level cause of this error &mdash; this error's cause's339    /// cause's cause etc.340    ///341    /// The root cause is the last error in the iterator produced by342    /// [`chain()`][Error::chain].343    #[cfg(feature = "std")]344    pub fn root_cause(&self) -> &(dyn StdError + 'static) {345        let mut chain = self.chain();346        let mut root_cause = chain.next().unwrap();347        for cause in chain {348            root_cause = cause;349        }350        root_cause351    }352353    /// Returns true if `E` is the type held by this error object.354    ///355    /// For errors with context, this method returns true if `E` matches the356    /// type of the context `C` **or** the type of the error on which the357    /// context has been attached. For details about the interaction between358    /// context and downcasting, [see here].359    ///360    /// [see here]: trait.Context.html#effect-on-downcasting361    pub fn is<E>(&self) -> bool362    where363        E: Display + Debug + Send + Sync + 'static,364    {365        self.downcast_ref::<E>().is_some()366    }367368    /// Attempt to downcast the error object to a concrete type.369    pub fn downcast<E>(self) -> Result<E, Self>370    where371        E: Display + Debug + Send + Sync + 'static,372    {373        let target = TypeId::of::<E>();374        unsafe {375            // Use vtable to find NonNull<()> which points to a value of type E376            // somewhere inside the data structure.377            let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {378                Some(addr) => addr,379                None => return Err(self),380            };381382            // Prepare to read E out of the data structure. We'll drop the rest383            // of the data structure separately so that E is not dropped.384            let outer = ManuallyDrop::new(self);385386            // Read E from where the vtable found it.387            let error = ptr::read(addr.cast::<E>().as_ptr());388389            // Read Box<ErrorImpl<()>> from self. Can't move it out because390            // Error has a Drop impl which we want to not run.391            let inner = ptr::read(&outer.inner);392            let erased = ManuallyDrop::into_inner(inner);393394            // Drop rest of the data structure outside of E.395            (erased.vtable.object_drop_rest)(erased, target);396397            Ok(error)398        }399    }400401    /// Downcast this error object by reference.402    ///403    /// # Example404    ///405    /// ```406    /// # use anyhow::anyhow;407    /// # use std::fmt::{self, Display};408    /// # use std::task::Poll;409    /// #410    /// # #[derive(Debug)]411    /// # enum DataStoreError {412    /// #     Censored(()),413    /// # }414    /// #415    /// # impl Display for DataStoreError {416    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {417    /// #         unimplemented!()418    /// #     }419    /// # }420    /// #421    /// # impl std::error::Error for DataStoreError {}422    /// #423    /// # const REDACTED_CONTENT: () = ();424    /// #425    /// # let error = anyhow!("...");426    /// # let root_cause = &error;427    /// #428    /// # let ret =429    /// // If the error was caused by redaction, then return a tombstone instead430    /// // of the content.431    /// match root_cause.downcast_ref::<DataStoreError>() {432    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),433    ///     None => Err(error),434    /// }435    /// # ;436    /// ```437    pub fn downcast_ref<E>(&self) -> Option<&E>438    where439        E: Display + Debug + Send + Sync + 'static,440    {441        let target = TypeId::of::<E>();442        unsafe {443            // Use vtable to find NonNull<()> which points to a value of type E444            // somewhere inside the data structure.445            let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;446            Some(&*addr.cast::<E>().as_ptr())447        }448    }449450    /// Downcast this error object by mutable reference.451    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>452    where453        E: Display + Debug + Send + Sync + 'static,454    {455        let target = TypeId::of::<E>();456        unsafe {457            // Use vtable to find NonNull<()> which points to a value of type E458            // somewhere inside the data structure.459            let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;460            Some(&mut *addr.cast::<E>().as_ptr())461        }462    }463}464465#[cfg(feature = "std")]466impl<E> From<E> for Error467where468    E: StdError + Send + Sync + 'static,469{470    fn from(error: E) -> Self {471        let backtrace = backtrace_if_absent!(error);472        Error::from_std(error, backtrace)473    }474}475476#[cfg(feature = "std")]477impl Deref for Error {478    type Target = dyn StdError + Send + Sync + 'static;479480    fn deref(&self) -> &Self::Target {481        self.inner.error()482    }483}484485#[cfg(feature = "std")]486impl DerefMut for Error {487    fn deref_mut(&mut self) -> &mut Self::Target {488        self.inner.error_mut()489    }490}491492impl Display for Error {493    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {494        self.inner.display(formatter)495    }496}497498impl Debug for Error {499    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {500        self.inner.debug(formatter)501    }502}503504impl Drop for Error {505    fn drop(&mut self) {506        unsafe {507            // Read Box<ErrorImpl<()>> from self.508            let inner = ptr::read(&self.inner);509            let erased = ManuallyDrop::into_inner(inner);510511            // Invoke the vtable's drop behavior.512            (erased.vtable.object_drop)(erased);513        }514    }515}516517struct ErrorVTable {518    object_drop: unsafe fn(Box<ErrorImpl<()>>),519    object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),520    #[cfg(feature = "std")]521    object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),522    object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,523    object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,524    object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),525}526527// Safety: requires layout of *e to match ErrorImpl<E>.528unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {529    // Cast back to ErrorImpl<E> so that the allocator receives the correct530    // Layout to deallocate the Box's memory.531    let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);532    drop(unerased);533}534535// Safety: requires layout of *e to match ErrorImpl<E>.536unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {537    // Drop the fields of ErrorImpl other than E as well as the Box allocation,538    // without dropping E itself. This is used by downcast after doing a539    // ptr::read to take ownership of the E.540    let _ = target;541    let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);542    drop(unerased);543}544545// Safety: requires layout of *e to match ErrorImpl<E>.546unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)547where548    E: StdError + Send + Sync + 'static,549{550    // Attach E's native StdError vtable onto a pointer to self._object.551    &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object552}553554// Safety: requires layout of *e to match ErrorImpl<E>.555#[cfg(feature = "std")]556unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)557where558    E: StdError + Send + Sync + 'static,559{560    // Attach E's native StdError vtable onto a pointer to self._object.561    &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object562}563564// Safety: requires layout of *e to match ErrorImpl<E>.565unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>566where567    E: StdError + Send + Sync + 'static,568{569    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.570    mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)571}572573// Safety: requires layout of *e to match ErrorImpl<E>.574unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>575where576    E: 'static,577{578    if TypeId::of::<E>() == target {579        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a580        // pointer to its E field.581        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;582        let addr = &(*unerased)._object as *const E as *mut ();583        Some(NonNull::new_unchecked(addr))584    } else {585        None586    }587}588589// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.590#[cfg(feature = "std")]591unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>592where593    C: 'static,594    E: 'static,595{596    if TypeId::of::<C>() == target {597        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;598        let addr = &(*unerased)._object.context as *const C as *mut ();599        Some(NonNull::new_unchecked(addr))600    } else if TypeId::of::<E>() == target {601        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;602        let addr = &(*unerased)._object.error as *const E as *mut ();603        Some(NonNull::new_unchecked(addr))604    } else {605        None606    }607}608609// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.610#[cfg(feature = "std")]611unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)612where613    C: 'static,614    E: 'static,615{616    // Called after downcasting by value to either the C or the E and doing a617    // ptr::read to take ownership of that value.618    if TypeId::of::<C>() == target {619        let unerased = mem::transmute::<620            Box<ErrorImpl<()>>,621            Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,622        >(e);623        drop(unerased);624    } else {625        let unerased = mem::transmute::<626            Box<ErrorImpl<()>>,627            Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,628        >(e);629        drop(unerased);630    }631}632633// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.634unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>635where636    C: 'static,637{638    if TypeId::of::<C>() == target {639        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;640        let addr = &(*unerased)._object.context as *const C as *mut ();641        Some(NonNull::new_unchecked(addr))642    } else {643        // Recurse down the context chain per the inner error's vtable.644        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;645        let source = &(*unerased)._object.error;646        (source.inner.vtable.object_downcast)(&source.inner, target)647    }648}649650// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.651unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)652where653    C: 'static,654{655    // Called after downcasting by value to either the C or one of the causes656    // and doing a ptr::read to take ownership of that value.657    if TypeId::of::<C>() == target {658        let unerased = mem::transmute::<659            Box<ErrorImpl<()>>,660            Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,661        >(e);662        // Drop the entire rest of the data structure rooted in the next Error.663        drop(unerased);664    } else {665        let unerased = mem::transmute::<666            Box<ErrorImpl<()>>,667            Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,668        >(e);669        // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.670        let inner = ptr::read(&unerased._object.error.inner);671        drop(unerased);672        let erased = ManuallyDrop::into_inner(inner);673        // Recursively drop the next error using the same target typeid.674        (erased.vtable.object_drop_rest)(erased, target);675    }676}677678// repr C to ensure that E remains in the final position.679#[repr(C)]680pub(crate) struct ErrorImpl<E> {681    vtable: &'static ErrorVTable,682    backtrace: Option<Backtrace>,683    // NOTE: Don't use directly. Use only through vtable. Erased type may have684    // different alignment.685    _object: E,686}687688// repr C to ensure that ContextError<C, E> has the same layout as689// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.690#[repr(C)]691pub(crate) struct ContextError<C, E> {692    pub context: C,693    pub error: E,694}695696impl<E> ErrorImpl<E> {697    fn erase(&self) -> &ErrorImpl<()> {698        // Erase the concrete type of E but preserve the vtable in self.vtable699        // for manipulating the resulting thin pointer. This is analogous to an700        // unsize coersion.701        unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }702    }703}704705impl ErrorImpl<()> {706    pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {707        // Use vtable to attach E's native StdError vtable for the right708        // original type E.709        unsafe { &*(self.vtable.object_ref)(self) }710    }711712    #[cfg(feature = "std")]713    pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {714        // Use vtable to attach E's native StdError vtable for the right715        // original type E.716        unsafe { &mut *(self.vtable.object_mut)(self) }717    }718719    #[cfg(backtrace)]720    pub(crate) fn backtrace(&self) -> &Backtrace {721        // This unwrap can only panic if the underlying error's backtrace method722        // is nondeterministic, which would only happen in maliciously723        // constructed code.724        self.backtrace725            .as_ref()726            .or_else(|| self.error().backtrace())727            .expect("backtrace capture failed")728    }729730    pub(crate) fn chain(&self) -> Chain {731        Chain::new(self.error())732    }733}734735impl<E> StdError for ErrorImpl<E>736where737    E: StdError,738{739    #[cfg(backtrace)]740    fn backtrace(&self) -> Option<&Backtrace> {741        Some(self.erase().backtrace())742    }743744    fn source(&self) -> Option<&(dyn StdError + 'static)> {745        self.erase().error().source()746    }747}748749impl<E> Debug for ErrorImpl<E>750where751    E: Debug,752{753    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {754        self.erase().debug(formatter)755    }756}757758impl<E> Display for ErrorImpl<E>759where760    E: Display,761{762    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {763        Display::fmt(&self.erase().error(), formatter)764    }765}766767impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {768    fn from(error: Error) -> Self {769        let outer = ManuallyDrop::new(error);770        unsafe {771            // Read Box<ErrorImpl<()>> from error. Can't move it out because772            // Error has a Drop impl which we want to not run.773            let inner = ptr::read(&outer.inner);774            let erased = ManuallyDrop::into_inner(inner);775776            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for777            // the right original type E.778            (erased.vtable.object_boxed)(erased)779        }780    }781}782783impl From<Error> for Box<dyn StdError + 'static> {784    fn from(error: Error) -> Self {785        Box::<dyn StdError + Send + Sync>::from(error)786    }787}788789#[cfg(feature = "std")]790impl AsRef<dyn StdError + Send + Sync> for Error {791    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {792        &**self793    }794}795796#[cfg(feature = "std")]797impl AsRef<dyn StdError> for Error {798    fn as_ref(&self) -> &(dyn StdError + 'static) {799        &**self800    }801}