Skip to content
Myr

error.rs

This file

Path

src/error.rs

805 lines · 27.2 KiB · Rust

Last changed by

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

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    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]23    pub fn new<E>(error: E) -> Self24    where25        E: StdError + Send + Sync + 'static,26    {27        let backtrace = backtrace_if_absent!(error);28        Error::from_std(error, backtrace)29    }3031    /// Create a new error object from a printable error message.32    ///33    /// If the argument implements std::error::Error, prefer `Error::new`34    /// instead which preserves the underlying error's cause chain and35    /// backtrace. If the argument may or may not implement std::error::Error36    /// now or in the future, use `anyhow!(err)` which handles either way37    /// correctly.38    ///39    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally40    /// convenient in places where a function is preferable over a macro, such41    /// as iterator or stream combinators:42    ///43    /// ```44    /// # mod ffi {45    /// #     pub struct Input;46    /// #     pub struct Output;47    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {48    /// #         unimplemented!()49    /// #     }50    /// # }51    /// #52    /// # use ffi::{Input, Output};53    /// #54    /// use anyhow::{Error, Result};55    /// use futures::stream::{Stream, StreamExt, TryStreamExt};56    ///57    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>58    /// where59    ///     S: Stream<Item = Input>,60    /// {61    ///     stream62    ///         .then(ffi::do_some_work) // returns Result<Output, &str>63    ///         .map_err(Error::msg)64    ///         .try_collect()65    ///         .await66    /// }67    /// ```68    pub fn msg<M>(message: M) -> Self69    where70        M: Display + Debug + Send + Sync + 'static,71    {72        Error::from_adhoc(message, backtrace!())73    }7475    #[cfg(feature = "std")]76    pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self77    where78        E: StdError + Send + Sync + 'static,79    {80        let vtable = &ErrorVTable {81            object_drop: object_drop::<E>,82            object_ref: object_ref::<E>,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            object_mut: object_mut::<ContextError<C, E>>,147            object_boxed: object_boxed::<ContextError<C, E>>,148            object_downcast: context_downcast::<C, E>,149            object_drop_rest: context_drop_rest::<C, E>,150        };151152        // Safety: passing vtable that operates on the right type.153        unsafe { Error::construct(error, vtable, backtrace) }154    }155156    #[cfg(feature = "std")]157    pub(crate) fn from_boxed(158        error: Box<dyn StdError + Send + Sync>,159        backtrace: Option<Backtrace>,160    ) -> Self {161        use crate::wrapper::BoxedError;162        let error = BoxedError(error);163        let vtable = &ErrorVTable {164            object_drop: object_drop::<BoxedError>,165            object_ref: object_ref::<BoxedError>,166            object_mut: object_mut::<BoxedError>,167            object_boxed: object_boxed::<BoxedError>,168            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,169            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,170        };171172        // Safety: BoxedError is repr(transparent) so it is okay for the vtable173        // to allow casting to Box<dyn StdError + Send + Sync>.174        unsafe { Error::construct(error, vtable, backtrace) }175    }176177    // Takes backtrace as argument rather than capturing it here so that the178    // user sees one fewer layer of wrapping noise in the backtrace.179    //180    // Unsafe because the given vtable must have sensible behavior on the error181    // value of type E.182    unsafe fn construct<E>(183        error: E,184        vtable: &'static ErrorVTable,185        backtrace: Option<Backtrace>,186    ) -> Self187    where188        E: StdError + Send + Sync + 'static,189    {190        let inner = Box::new(ErrorImpl {191            vtable,192            backtrace,193            _object: error,194        });195        // Erase the concrete type of E from the compile-time type system. This196        // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to197        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the198        // result is a thin pointer. The necessary behavior for manipulating the199        // underlying ErrorImpl<E> is preserved in the vtable provided by the200        // caller rather than a builtin fat pointer vtable.201        let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);202        let inner = ManuallyDrop::new(erased);203        Error { inner }204    }205206    /// Wrap the error value with additional context.207    ///208    /// For attaching context to a `Result` as it is propagated, the209    /// [`Context`][crate::Context] extension trait may be more convenient than210    /// this function.211    ///212    /// The primary reason to use `error.context(...)` instead of213    /// `result.context(...)` via the `Context` trait would be if the context214    /// needs to depend on some data held by the underlying error:215    ///216    /// ```217    /// # use std::fmt::{self, Debug, Display};218    /// #219    /// # type T = ();220    /// #221    /// # impl std::error::Error for ParseError {}222    /// # impl Debug for ParseError {223    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {224    /// #         unimplemented!()225    /// #     }226    /// # }227    /// # impl Display for ParseError {228    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {229    /// #         unimplemented!()230    /// #     }231    /// # }232    /// #233    /// use anyhow::Result;234    /// use std::fs::File;235    /// use std::path::Path;236    ///237    /// struct ParseError {238    ///     line: usize,239    ///     column: usize,240    /// }241    ///242    /// fn parse_impl(file: File) -> Result<T, ParseError> {243    ///     # const IGNORE: &str = stringify! {244    ///     ...245    ///     # };246    ///     # unimplemented!()247    /// }248    ///249    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {250    ///     let file = File::open(&path)?;251    ///     parse_impl(file).map_err(|error| {252    ///         let context = format!(253    ///             "only the first {} lines of {} are valid",254    ///             error.line, path.as_ref().display(),255    ///         );256    ///         anyhow::Error::new(error).context(context)257    ///     })258    /// }259    /// ```260    pub fn context<C>(self, context: C) -> Self261    where262        C: Display + Send + Sync + 'static,263    {264        let error: ContextError<C, Error> = ContextError {265            context,266            error: self,267        };268269        let vtable = &ErrorVTable {270            object_drop: object_drop::<ContextError<C, Error>>,271            object_ref: object_ref::<ContextError<C, Error>>,272            #[cfg(feature = "std")]273            object_mut: object_mut::<ContextError<C, Error>>,274            object_boxed: object_boxed::<ContextError<C, Error>>,275            object_downcast: context_chain_downcast::<C>,276            object_drop_rest: context_chain_drop_rest::<C>,277        };278279        // As the cause is anyhow::Error, we already have a backtrace for it.280        let backtrace = None;281282        // Safety: passing vtable that operates on the right type.283        unsafe { Error::construct(error, vtable, backtrace) }284    }285286    /// Get the backtrace for this Error.287    ///288    /// Backtraces are only available on the nightly channel. Tracking issue:289    /// [rust-lang/rust#53487][tracking].290    ///291    /// In order for the backtrace to be meaningful, one of the two environment292    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined293    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat294    /// expensive to capture in Rust, so we don't necessarily want to be295    /// capturing them all over the place all the time.296    ///297    /// - If you want panics and errors to both have backtraces, set298    ///   `RUST_BACKTRACE=1`;299    /// - If you want only errors to have backtraces, set300    ///   `RUST_LIB_BACKTRACE=1`;301    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and302    ///   `RUST_LIB_BACKTRACE=0`.303    ///304    /// [tracking]: https://github.com/rust-lang/rust/issues/53487305    #[cfg(backtrace)]306    pub fn backtrace(&self) -> &Backtrace {307        self.inner.backtrace()308    }309310    /// An iterator of the chain of source errors contained by this Error.311    ///312    /// This iterator will visit every error in the cause chain of this error313    /// object, beginning with the error that this error object was created314    /// from.315    ///316    /// # Example317    ///318    /// ```319    /// use anyhow::Error;320    /// use std::io;321    ///322    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {323    ///     for cause in error.chain() {324    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {325    ///             return Some(io_error.kind());326    ///         }327    ///     }328    ///     None329    /// }330    /// ```331    #[cfg(feature = "std")]332    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]333    pub fn chain(&self) -> Chain {334        self.inner.chain()335    }336337    /// The lowest level cause of this error &mdash; this error's cause's338    /// cause's cause etc.339    ///340    /// The root cause is the last error in the iterator produced by341    /// [`chain()`][Error::chain].342    #[cfg(feature = "std")]343    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]344    pub fn root_cause(&self) -> &(dyn StdError + 'static) {345        self.chain().last().unwrap()346    }347348    /// Returns true if `E` is the type held by this error object.349    ///350    /// For errors with context, this method returns true if `E` matches the351    /// type of the context `C` **or** the type of the error on which the352    /// context has been attached. For details about the interaction between353    /// context and downcasting, [see here].354    ///355    /// [see here]: trait.Context.html#effect-on-downcasting356    pub fn is<E>(&self) -> bool357    where358        E: Display + Debug + Send + Sync + 'static,359    {360        self.downcast_ref::<E>().is_some()361    }362363    /// Attempt to downcast the error object to a concrete type.364    pub fn downcast<E>(self) -> Result<E, Self>365    where366        E: Display + Debug + Send + Sync + 'static,367    {368        let target = TypeId::of::<E>();369        unsafe {370            // Use vtable to find NonNull<()> which points to a value of type E371            // somewhere inside the data structure.372            let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {373                Some(addr) => addr,374                None => return Err(self),375            };376377            // Prepare to read E out of the data structure. We'll drop the rest378            // of the data structure separately so that E is not dropped.379            let outer = ManuallyDrop::new(self);380381            // Read E from where the vtable found it.382            let error = ptr::read(addr.cast::<E>().as_ptr());383384            // Read Box<ErrorImpl<()>> from self. Can't move it out because385            // Error has a Drop impl which we want to not run.386            let inner = ptr::read(&outer.inner);387            let erased = ManuallyDrop::into_inner(inner);388389            // Drop rest of the data structure outside of E.390            (erased.vtable.object_drop_rest)(erased, target);391392            Ok(error)393        }394    }395396    /// Downcast this error object by reference.397    ///398    /// # Example399    ///400    /// ```401    /// # use anyhow::anyhow;402    /// # use std::fmt::{self, Display};403    /// # use std::task::Poll;404    /// #405    /// # #[derive(Debug)]406    /// # enum DataStoreError {407    /// #     Censored(()),408    /// # }409    /// #410    /// # impl Display for DataStoreError {411    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {412    /// #         unimplemented!()413    /// #     }414    /// # }415    /// #416    /// # impl std::error::Error for DataStoreError {}417    /// #418    /// # const REDACTED_CONTENT: () = ();419    /// #420    /// # let error = anyhow!("...");421    /// # let root_cause = &error;422    /// #423    /// # let ret =424    /// // If the error was caused by redaction, then return a tombstone instead425    /// // of the content.426    /// match root_cause.downcast_ref::<DataStoreError>() {427    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),428    ///     None => Err(error),429    /// }430    /// # ;431    /// ```432    pub fn downcast_ref<E>(&self) -> Option<&E>433    where434        E: Display + Debug + Send + Sync + 'static,435    {436        let target = TypeId::of::<E>();437        unsafe {438            // Use vtable to find NonNull<()> which points to a value of type E439            // somewhere inside the data structure.440            let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;441            Some(&*addr.cast::<E>().as_ptr())442        }443    }444445    /// Downcast this error object by mutable reference.446    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>447    where448        E: Display + Debug + Send + Sync + 'static,449    {450        let target = TypeId::of::<E>();451        unsafe {452            // Use vtable to find NonNull<()> which points to a value of type E453            // somewhere inside the data structure.454            let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;455            Some(&mut *addr.cast::<E>().as_ptr())456        }457    }458}459460#[cfg(feature = "std")]461#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]462impl<E> From<E> for Error463where464    E: StdError + Send + Sync + 'static,465{466    fn from(error: E) -> Self {467        let backtrace = backtrace_if_absent!(error);468        Error::from_std(error, backtrace)469    }470}471472#[cfg(feature = "std")]473#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]474impl Deref for Error {475    type Target = dyn StdError + Send + Sync + 'static;476477    fn deref(&self) -> &Self::Target {478        self.inner.error()479    }480}481482#[cfg(feature = "std")]483#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]484impl DerefMut for Error {485    fn deref_mut(&mut self) -> &mut Self::Target {486        self.inner.error_mut()487    }488}489490impl Display for Error {491    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {492        self.inner.display(formatter)493    }494}495496impl Debug for Error {497    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {498        self.inner.debug(formatter)499    }500}501502impl Drop for Error {503    fn drop(&mut self) {504        unsafe {505            // Read Box<ErrorImpl<()>> from self.506            let inner = ptr::read(&self.inner);507            let erased = ManuallyDrop::into_inner(inner);508509            // Invoke the vtable's drop behavior.510            (erased.vtable.object_drop)(erased);511        }512    }513}514515struct ErrorVTable {516    object_drop: unsafe fn(Box<ErrorImpl<()>>),517    object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),518    #[cfg(feature = "std")]519    object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),520    object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,521    object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,522    object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),523}524525// Safety: requires layout of *e to match ErrorImpl<E>.526unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {527    // Cast back to ErrorImpl<E> so that the allocator receives the correct528    // Layout to deallocate the Box's memory.529    let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);530    drop(unerased);531}532533// Safety: requires layout of *e to match ErrorImpl<E>.534unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {535    // Drop the fields of ErrorImpl other than E as well as the Box allocation,536    // without dropping E itself. This is used by downcast after doing a537    // ptr::read to take ownership of the E.538    let _ = target;539    let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);540    drop(unerased);541}542543// Safety: requires layout of *e to match ErrorImpl<E>.544unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)545where546    E: StdError + Send + Sync + 'static,547{548    // Attach E's native StdError vtable onto a pointer to self._object.549    &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object550}551552// Safety: requires layout of *e to match ErrorImpl<E>.553#[cfg(feature = "std")]554unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)555where556    E: StdError + Send + Sync + 'static,557{558    // Attach E's native StdError vtable onto a pointer to self._object.559    &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object560}561562// Safety: requires layout of *e to match ErrorImpl<E>.563unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>564where565    E: StdError + Send + Sync + 'static,566{567    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.568    mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)569}570571// Safety: requires layout of *e to match ErrorImpl<E>.572unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>573where574    E: 'static,575{576    if TypeId::of::<E>() == target {577        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a578        // pointer to its E field.579        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;580        let addr = &(*unerased)._object as *const E as *mut ();581        Some(NonNull::new_unchecked(addr))582    } else {583        None584    }585}586587// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.588#[cfg(feature = "std")]589unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>590where591    C: 'static,592    E: 'static,593{594    if TypeId::of::<C>() == target {595        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;596        let addr = &(*unerased)._object.context as *const C as *mut ();597        Some(NonNull::new_unchecked(addr))598    } else if TypeId::of::<E>() == target {599        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;600        let addr = &(*unerased)._object.error as *const E as *mut ();601        Some(NonNull::new_unchecked(addr))602    } else {603        None604    }605}606607// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.608#[cfg(feature = "std")]609unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)610where611    C: 'static,612    E: 'static,613{614    // Called after downcasting by value to either the C or the E and doing a615    // ptr::read to take ownership of that value.616    if TypeId::of::<C>() == target {617        let unerased = mem::transmute::<618            Box<ErrorImpl<()>>,619            Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,620        >(e);621        drop(unerased);622    } else {623        let unerased = mem::transmute::<624            Box<ErrorImpl<()>>,625            Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,626        >(e);627        drop(unerased);628    }629}630631// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.632unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>633where634    C: 'static,635{636    if TypeId::of::<C>() == target {637        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;638        let addr = &(*unerased)._object.context as *const C as *mut ();639        Some(NonNull::new_unchecked(addr))640    } else {641        // Recurse down the context chain per the inner error's vtable.642        let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;643        let source = &(*unerased)._object.error;644        (source.inner.vtable.object_downcast)(&source.inner, target)645    }646}647648// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.649unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)650where651    C: 'static,652{653    // Called after downcasting by value to either the C or one of the causes654    // and doing a ptr::read to take ownership of that value.655    if TypeId::of::<C>() == target {656        let unerased = mem::transmute::<657            Box<ErrorImpl<()>>,658            Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,659        >(e);660        // Drop the entire rest of the data structure rooted in the next Error.661        drop(unerased);662    } else {663        let unerased = mem::transmute::<664            Box<ErrorImpl<()>>,665            Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,666        >(e);667        // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.668        let inner = ptr::read(&unerased._object.error.inner);669        drop(unerased);670        let erased = ManuallyDrop::into_inner(inner);671        // Recursively drop the next error using the same target typeid.672        (erased.vtable.object_drop_rest)(erased, target);673    }674}675676// repr C to ensure that E remains in the final position.677#[repr(C)]678pub(crate) struct ErrorImpl<E> {679    vtable: &'static ErrorVTable,680    backtrace: Option<Backtrace>,681    // NOTE: Don't use directly. Use only through vtable. Erased type may have682    // different alignment.683    _object: E,684}685686// repr C to ensure that ContextError<C, E> has the same layout as687// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.688#[repr(C)]689pub(crate) struct ContextError<C, E> {690    pub context: C,691    pub error: E,692}693694impl<E> ErrorImpl<E> {695    fn erase(&self) -> &ErrorImpl<()> {696        // Erase the concrete type of E but preserve the vtable in self.vtable697        // for manipulating the resulting thin pointer. This is analogous to an698        // unsize coercion.699        unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }700    }701}702703impl ErrorImpl<()> {704    pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {705        // Use vtable to attach E's native StdError vtable for the right706        // original type E.707        unsafe { &*(self.vtable.object_ref)(self) }708    }709710    #[cfg(feature = "std")]711    pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {712        // Use vtable to attach E's native StdError vtable for the right713        // original type E.714        unsafe { &mut *(self.vtable.object_mut)(self) }715    }716717    #[cfg(backtrace)]718    pub(crate) fn backtrace(&self) -> &Backtrace {719        // This unwrap can only panic if the underlying error's backtrace method720        // is nondeterministic, which would only happen in maliciously721        // constructed code.722        self.backtrace723            .as_ref()724            .or_else(|| self.error().backtrace())725            .expect("backtrace capture failed")726    }727728    pub(crate) fn chain(&self) -> Chain {729        Chain::new(self.error())730    }731}732733impl<E> StdError for ErrorImpl<E>734where735    E: StdError,736{737    #[cfg(backtrace)]738    fn backtrace(&self) -> Option<&Backtrace> {739        Some(self.erase().backtrace())740    }741742    fn source(&self) -> Option<&(dyn StdError + 'static)> {743        self.erase().error().source()744    }745}746747impl<E> Debug for ErrorImpl<E>748where749    E: Debug,750{751    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {752        self.erase().debug(formatter)753    }754}755756impl<E> Display for ErrorImpl<E>757where758    E: Display,759{760    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {761        Display::fmt(&self.erase().error(), formatter)762    }763}764765impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {766    fn from(error: Error) -> Self {767        let outer = ManuallyDrop::new(error);768        unsafe {769            // Read Box<ErrorImpl<()>> from error. Can't move it out because770            // Error has a Drop impl which we want to not run.771            let inner = ptr::read(&outer.inner);772            let erased = ManuallyDrop::into_inner(inner);773774            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for775            // the right original type E.776            (erased.vtable.object_boxed)(erased)777        }778    }779}780781impl From<Error> for Box<dyn StdError + Send + 'static> {782    fn from(error: Error) -> Self {783        Box::<dyn StdError + Send + Sync>::from(error)784    }785}786787impl From<Error> for Box<dyn StdError + 'static> {788    fn from(error: Error) -> Self {789        Box::<dyn StdError + Send + Sync>::from(error)790    }791}792793#[cfg(feature = "std")]794impl AsRef<dyn StdError + Send + Sync> for Error {795    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {796        &**self797    }798}799800#[cfg(feature = "std")]801impl AsRef<dyn StdError> for Error {802    fn as_ref(&self) -> &(dyn StdError + 'static) {803        &**self804    }805}