Skip to content
Myr

error.rs

This file

Path

src/error.rs

793 lines · 26.6 KiB · Rust

Last changed by

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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, the environment variable294    /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat295    /// expensive to capture in Rust, so we don't necessarily want to be296    /// capturing them all over the place all the time.297    ///298    /// [tracking]: https://github.com/rust-lang/rust/issues/53487299    #[cfg(backtrace)]300    pub fn backtrace(&self) -> &Backtrace {301        self.inner.backtrace()302    }303304    /// An iterator of the chain of source errors contained by this Error.305    ///306    /// This iterator will visit every error in the cause chain of this error307    /// object, beginning with the error that this error object was created308    /// from.309    ///310    /// # Example311    ///312    /// ```313    /// use anyhow::Error;314    /// use std::io;315    ///316    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {317    ///     for cause in error.chain() {318    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {319    ///             return Some(io_error.kind());320    ///         }321    ///     }322    ///     None323    /// }324    /// ```325    #[cfg(feature = "std")]326    pub fn chain(&self) -> Chain {327        self.inner.chain()328    }329330    /// The lowest level cause of this error &mdash; this error's cause's331    /// cause's cause etc.332    ///333    /// The root cause is the last error in the iterator produced by334    /// [`chain()`][Error::chain].335    #[cfg(feature = "std")]336    pub fn root_cause(&self) -> &(dyn StdError + 'static) {337        let mut chain = self.chain();338        let mut root_cause = chain.next().unwrap();339        for cause in chain {340            root_cause = cause;341        }342        root_cause343    }344345    /// Returns true if `E` is the type held by this error object.346    ///347    /// For errors with context, this method returns true if `E` matches the348    /// type of the context `C` **or** the type of the error on which the349    /// context has been attached. For details about the interaction between350    /// context and downcasting, [see here].351    ///352    /// [see here]: trait.Context.html#effect-on-downcasting353    pub fn is<E>(&self) -> bool354    where355        E: Display + Debug + Send + Sync + 'static,356    {357        self.downcast_ref::<E>().is_some()358    }359360    /// Attempt to downcast the error object to a concrete type.361    pub fn downcast<E>(self) -> Result<E, Self>362    where363        E: Display + Debug + Send + Sync + 'static,364    {365        let target = TypeId::of::<E>();366        unsafe {367            // Use vtable to find NonNull<()> which points to a value of type E368            // somewhere inside the data structure.369            let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {370                Some(addr) => addr,371                None => return Err(self),372            };373374            // Prepare to read E out of the data structure. We'll drop the rest375            // of the data structure separately so that E is not dropped.376            let outer = ManuallyDrop::new(self);377378            // Read E from where the vtable found it.379            let error = ptr::read(addr.cast::<E>().as_ptr());380381            // Read Box<ErrorImpl<()>> from self. Can't move it out because382            // Error has a Drop impl which we want to not run.383            let inner = ptr::read(&outer.inner);384            let erased = ManuallyDrop::into_inner(inner);385386            // Drop rest of the data structure outside of E.387            (erased.vtable.object_drop_rest)(erased, target);388389            Ok(error)390        }391    }392393    /// Downcast this error object by reference.394    ///395    /// # Example396    ///397    /// ```398    /// # use anyhow::anyhow;399    /// # use std::fmt::{self, Display};400    /// # use std::task::Poll;401    /// #402    /// # #[derive(Debug)]403    /// # enum DataStoreError {404    /// #     Censored(()),405    /// # }406    /// #407    /// # impl Display for DataStoreError {408    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {409    /// #         unimplemented!()410    /// #     }411    /// # }412    /// #413    /// # impl std::error::Error for DataStoreError {}414    /// #415    /// # const REDACTED_CONTENT: () = ();416    /// #417    /// # let error = anyhow!("...");418    /// # let root_cause = &error;419    /// #420    /// # let ret =421    /// // If the error was caused by redaction, then return a tombstone instead422    /// // of the content.423    /// match root_cause.downcast_ref::<DataStoreError>() {424    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),425    ///     None => Err(error),426    /// }427    /// # ;428    /// ```429    pub fn downcast_ref<E>(&self) -> Option<&E>430    where431        E: Display + Debug + Send + Sync + 'static,432    {433        let target = TypeId::of::<E>();434        unsafe {435            // Use vtable to find NonNull<()> which points to a value of type E436            // somewhere inside the data structure.437            let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;438            Some(&*addr.cast::<E>().as_ptr())439        }440    }441442    /// Downcast this error object by mutable reference.443    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>444    where445        E: Display + Debug + Send + Sync + 'static,446    {447        let target = TypeId::of::<E>();448        unsafe {449            // Use vtable to find NonNull<()> which points to a value of type E450            // somewhere inside the data structure.451            let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;452            Some(&mut *addr.cast::<E>().as_ptr())453        }454    }455}456457#[cfg(feature = "std")]458impl<E> From<E> for Error459where460    E: StdError + Send + Sync + 'static,461{462    fn from(error: E) -> Self {463        let backtrace = backtrace_if_absent!(error);464        Error::from_std(error, backtrace)465    }466}467468#[cfg(feature = "std")]469impl Deref for Error {470    type Target = dyn StdError + Send + Sync + 'static;471472    fn deref(&self) -> &Self::Target {473        self.inner.error()474    }475}476477#[cfg(feature = "std")]478impl DerefMut for Error {479    fn deref_mut(&mut self) -> &mut Self::Target {480        self.inner.error_mut()481    }482}483484impl Display for Error {485    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {486        self.inner.display(formatter)487    }488}489490impl Debug for Error {491    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {492        self.inner.debug(formatter)493    }494}495496impl Drop for Error {497    fn drop(&mut self) {498        unsafe {499            // Read Box<ErrorImpl<()>> from self.500            let inner = ptr::read(&self.inner);501            let erased = ManuallyDrop::into_inner(inner);502503            // Invoke the vtable's drop behavior.504            (erased.vtable.object_drop)(erased);505        }506    }507}508509struct ErrorVTable {510    object_drop: unsafe fn(Box<ErrorImpl<()>>),511    object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),512    #[cfg(feature = "std")]513    object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),514    object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,515    object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,516    object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),517}518519// Safety: requires layout of *e to match ErrorImpl<E>.520unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {521    // Cast back to ErrorImpl<E> so that the allocator receives the correct522    // Layout to deallocate the Box's memory.523    let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);524    drop(unerased);525}526527// Safety: requires layout of *e to match ErrorImpl<E>.528unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {529    // Drop the fields of ErrorImpl other than E as well as the Box allocation,530    // without dropping E itself. This is used by downcast after doing a531    // ptr::read to take ownership of the E.532    let _ = target;533    let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);534    drop(unerased);535}536537// Safety: requires layout of *e to match ErrorImpl<E>.538unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)539where540    E: StdError + Send + Sync + 'static,541{542    // Attach E's native StdError vtable onto a pointer to self._object.543    &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object544}545546// Safety: requires layout of *e to match ErrorImpl<E>.547#[cfg(feature = "std")]548unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)549where550    E: StdError + Send + Sync + 'static,551{552    // Attach E's native StdError vtable onto a pointer to self._object.553    &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object554}555556// Safety: requires layout of *e to match ErrorImpl<E>.557unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>558where559    E: StdError + Send + Sync + 'static,560{561    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.562    mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)563}564565// Safety: requires layout of *e to match ErrorImpl<E>.566unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>567where568    E: 'static,569{570    if TypeId::of::<E>() == target {571        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a572        // pointer to its E field.573        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;574        let addr = &(*unerased)._object as *const E as *mut ();575        Some(NonNull::new_unchecked(addr))576    } else {577        None578    }579}580581// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.582#[cfg(feature = "std")]583unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>584where585    C: 'static,586    E: 'static,587{588    if TypeId::of::<C>() == target {589        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;590        let addr = &(*unerased)._object.context as *const C as *mut ();591        Some(NonNull::new_unchecked(addr))592    } else if TypeId::of::<E>() == target {593        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;594        let addr = &(*unerased)._object.error as *const E as *mut ();595        Some(NonNull::new_unchecked(addr))596    } else {597        None598    }599}600601// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.602#[cfg(feature = "std")]603unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)604where605    C: 'static,606    E: 'static,607{608    // Called after downcasting by value to either the C or the E and doing a609    // ptr::read to take ownership of that value.610    if TypeId::of::<C>() == target {611        let unerased = mem::transmute::<612            Box<ErrorImpl<()>>,613            Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,614        >(e);615        drop(unerased);616    } else {617        let unerased = mem::transmute::<618            Box<ErrorImpl<()>>,619            Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,620        >(e);621        drop(unerased);622    }623}624625// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.626unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>627where628    C: 'static,629{630    if TypeId::of::<C>() == target {631        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;632        let addr = &(*unerased)._object.context as *const C as *mut ();633        Some(NonNull::new_unchecked(addr))634    } else {635        // Recurse down the context chain per the inner error's vtable.636        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;637        let source = &(*unerased)._object.error;638        (source.inner.vtable.object_downcast)(&source.inner, target)639    }640}641642// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.643unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)644where645    C: 'static,646{647    // Called after downcasting by value to either the C or one of the causes648    // and doing a ptr::read to take ownership of that value.649    if TypeId::of::<C>() == target {650        let unerased = mem::transmute::<651            Box<ErrorImpl<()>>,652            Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,653        >(e);654        // Drop the entire rest of the data structure rooted in the next Error.655        drop(unerased);656    } else {657        let unerased = mem::transmute::<658            Box<ErrorImpl<()>>,659            Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,660        >(e);661        // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.662        let inner = ptr::read(&unerased._object.error.inner);663        drop(unerased);664        let erased = ManuallyDrop::into_inner(inner);665        // Recursively drop the next error using the same target typeid.666        (erased.vtable.object_drop_rest)(erased, target);667    }668}669670// repr C to ensure that E remains in the final position.671#[repr(C)]672pub(crate) struct ErrorImpl<E> {673    vtable: &'static ErrorVTable,674    backtrace: Option<Backtrace>,675    // NOTE: Don't use directly. Use only through vtable. Erased type may have676    // different alignment.677    _object: E,678}679680// repr C to ensure that ContextError<C, E> has the same layout as681// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.682#[repr(C)]683pub(crate) struct ContextError<C, E> {684    pub context: C,685    pub error: E,686}687688impl<E> ErrorImpl<E> {689    fn erase(&self) -> &ErrorImpl<()> {690        // Erase the concrete type of E but preserve the vtable in self.vtable691        // for manipulating the resulting thin pointer. This is analogous to an692        // unsize coersion.693        unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }694    }695}696697impl ErrorImpl<()> {698    pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {699        // Use vtable to attach E's native StdError vtable for the right700        // original type E.701        unsafe { &*(self.vtable.object_ref)(self) }702    }703704    #[cfg(feature = "std")]705    pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {706        // Use vtable to attach E's native StdError vtable for the right707        // original type E.708        unsafe { &mut *(self.vtable.object_mut)(self) }709    }710711    #[cfg(backtrace)]712    pub(crate) fn backtrace(&self) -> &Backtrace {713        // This unwrap can only panic if the underlying error's backtrace method714        // is nondeterministic, which would only happen in maliciously715        // constructed code.716        self.backtrace717            .as_ref()718            .or_else(|| self.error().backtrace())719            .expect("backtrace capture failed")720    }721722    pub(crate) fn chain(&self) -> Chain {723        Chain::new(self.error())724    }725}726727impl<E> StdError for ErrorImpl<E>728where729    E: StdError,730{731    #[cfg(backtrace)]732    fn backtrace(&self) -> Option<&Backtrace> {733        Some(self.erase().backtrace())734    }735736    fn source(&self) -> Option<&(dyn StdError + 'static)> {737        self.erase().error().source()738    }739}740741impl<E> Debug for ErrorImpl<E>742where743    E: Debug,744{745    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {746        self.erase().debug(formatter)747    }748}749750impl<E> Display for ErrorImpl<E>751where752    E: Display,753{754    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {755        Display::fmt(&self.erase().error(), formatter)756    }757}758759impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {760    fn from(error: Error) -> Self {761        let outer = ManuallyDrop::new(error);762        unsafe {763            // Read Box<ErrorImpl<()>> from error. Can't move it out because764            // Error has a Drop impl which we want to not run.765            let inner = ptr::read(&outer.inner);766            let erased = ManuallyDrop::into_inner(inner);767768            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for769            // the right original type E.770            (erased.vtable.object_boxed)(erased)771        }772    }773}774775impl From<Error> for Box<dyn StdError + 'static> {776    fn from(error: Error) -> Self {777        Box::<dyn StdError + Send + Sync>::from(error)778    }779}780781#[cfg(feature = "std")]782impl AsRef<dyn StdError + Send + Sync> for Error {783    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {784        &**self785    }786}787788#[cfg(feature = "std")]789impl AsRef<dyn StdError> for Error {790    fn as_ref(&self) -> &(dyn StdError + 'static) {791        &**self792    }793}