error.rs
This file
Path
src/error.rs
800 lines · 26.9 KiB · Rust
Last changed by
Fix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b
History of this fileTake 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 pub fn chain(&self) -> Chain {333 self.inner.chain()334 }335336 /// The lowest level cause of this error — this error's cause's337 /// cause's cause etc.338 ///339 /// The root cause is the last error in the iterator produced by340 /// [`chain()`][Error::chain].341 #[cfg(feature = "std")]342 pub fn root_cause(&self) -> &(dyn StdError + 'static) {343 self.chain().last().unwrap()344 }345346 /// Returns true if `E` is the type held by this error object.347 ///348 /// For errors with context, this method returns true if `E` matches the349 /// type of the context `C` **or** the type of the error on which the350 /// context has been attached. For details about the interaction between351 /// context and downcasting, [see here].352 ///353 /// [see here]: trait.Context.html#effect-on-downcasting354 pub fn is<E>(&self) -> bool355 where356 E: Display + Debug + Send + Sync + 'static,357 {358 self.downcast_ref::<E>().is_some()359 }360361 /// Attempt to downcast the error object to a concrete type.362 pub fn downcast<E>(self) -> Result<E, Self>363 where364 E: Display + Debug + Send + Sync + 'static,365 {366 let target = TypeId::of::<E>();367 unsafe {368 // Use vtable to find NonNull<()> which points to a value of type E369 // somewhere inside the data structure.370 let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {371 Some(addr) => addr,372 None => return Err(self),373 };374375 // Prepare to read E out of the data structure. We'll drop the rest376 // of the data structure separately so that E is not dropped.377 let outer = ManuallyDrop::new(self);378379 // Read E from where the vtable found it.380 let error = ptr::read(addr.cast::<E>().as_ptr());381382 // Read Box<ErrorImpl<()>> from self. Can't move it out because383 // Error has a Drop impl which we want to not run.384 let inner = ptr::read(&outer.inner);385 let erased = ManuallyDrop::into_inner(inner);386387 // Drop rest of the data structure outside of E.388 (erased.vtable.object_drop_rest)(erased, target);389390 Ok(error)391 }392 }393394 /// Downcast this error object by reference.395 ///396 /// # Example397 ///398 /// ```399 /// # use anyhow::anyhow;400 /// # use std::fmt::{self, Display};401 /// # use std::task::Poll;402 /// #403 /// # #[derive(Debug)]404 /// # enum DataStoreError {405 /// # Censored(()),406 /// # }407 /// #408 /// # impl Display for DataStoreError {409 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {410 /// # unimplemented!()411 /// # }412 /// # }413 /// #414 /// # impl std::error::Error for DataStoreError {}415 /// #416 /// # const REDACTED_CONTENT: () = ();417 /// #418 /// # let error = anyhow!("...");419 /// # let root_cause = &error;420 /// #421 /// # let ret =422 /// // If the error was caused by redaction, then return a tombstone instead423 /// // of the content.424 /// match root_cause.downcast_ref::<DataStoreError>() {425 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),426 /// None => Err(error),427 /// }428 /// # ;429 /// ```430 pub fn downcast_ref<E>(&self) -> Option<&E>431 where432 E: Display + Debug + Send + Sync + 'static,433 {434 let target = TypeId::of::<E>();435 unsafe {436 // Use vtable to find NonNull<()> which points to a value of type E437 // somewhere inside the data structure.438 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;439 Some(&*addr.cast::<E>().as_ptr())440 }441 }442443 /// Downcast this error object by mutable reference.444 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>445 where446 E: Display + Debug + Send + Sync + 'static,447 {448 let target = TypeId::of::<E>();449 unsafe {450 // Use vtable to find NonNull<()> which points to a value of type E451 // somewhere inside the data structure.452 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;453 Some(&mut *addr.cast::<E>().as_ptr())454 }455 }456}457458#[cfg(feature = "std")]459impl<E> From<E> for Error460where461 E: StdError + Send + Sync + 'static,462{463 fn from(error: E) -> Self {464 let backtrace = backtrace_if_absent!(error);465 Error::from_std(error, backtrace)466 }467}468469#[cfg(feature = "std")]470impl Deref for Error {471 type Target = dyn StdError + Send + Sync + 'static;472473 fn deref(&self) -> &Self::Target {474 self.inner.error()475 }476}477478#[cfg(feature = "std")]479impl DerefMut for Error {480 fn deref_mut(&mut self) -> &mut Self::Target {481 self.inner.error_mut()482 }483}484485impl Display for Error {486 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {487 self.inner.display(formatter)488 }489}490491impl Debug for Error {492 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {493 self.inner.debug(formatter)494 }495}496497impl Drop for Error {498 fn drop(&mut self) {499 unsafe {500 // Read Box<ErrorImpl<()>> from self.501 let inner = ptr::read(&self.inner);502 let erased = ManuallyDrop::into_inner(inner);503504 // Invoke the vtable's drop behavior.505 (erased.vtable.object_drop)(erased);506 }507 }508}509510struct ErrorVTable {511 object_drop: unsafe fn(Box<ErrorImpl<()>>),512 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),513 #[cfg(feature = "std")]514 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),515 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,516 object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,517 object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),518}519520// Safety: requires layout of *e to match ErrorImpl<E>.521unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {522 // Cast back to ErrorImpl<E> so that the allocator receives the correct523 // Layout to deallocate the Box's memory.524 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);525 drop(unerased);526}527528// Safety: requires layout of *e to match ErrorImpl<E>.529unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {530 // Drop the fields of ErrorImpl other than E as well as the Box allocation,531 // without dropping E itself. This is used by downcast after doing a532 // ptr::read to take ownership of the E.533 let _ = target;534 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);535 drop(unerased);536}537538// Safety: requires layout of *e to match ErrorImpl<E>.539unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)540where541 E: StdError + Send + Sync + 'static,542{543 // Attach E's native StdError vtable onto a pointer to self._object.544 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object545}546547// Safety: requires layout of *e to match ErrorImpl<E>.548#[cfg(feature = "std")]549unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)550where551 E: StdError + Send + Sync + 'static,552{553 // Attach E's native StdError vtable onto a pointer to self._object.554 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object555}556557// Safety: requires layout of *e to match ErrorImpl<E>.558unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>559where560 E: StdError + Send + Sync + 'static,561{562 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.563 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)564}565566// Safety: requires layout of *e to match ErrorImpl<E>.567unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>568where569 E: 'static,570{571 if TypeId::of::<E>() == target {572 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a573 // pointer to its E field.574 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;575 let addr = &(*unerased)._object as *const E as *mut ();576 Some(NonNull::new_unchecked(addr))577 } else {578 None579 }580}581582// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.583#[cfg(feature = "std")]584unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>585where586 C: 'static,587 E: 'static,588{589 if TypeId::of::<C>() == target {590 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;591 let addr = &(*unerased)._object.context as *const C as *mut ();592 Some(NonNull::new_unchecked(addr))593 } else if TypeId::of::<E>() == target {594 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;595 let addr = &(*unerased)._object.error as *const E as *mut ();596 Some(NonNull::new_unchecked(addr))597 } else {598 None599 }600}601602// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.603#[cfg(feature = "std")]604unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)605where606 C: 'static,607 E: 'static,608{609 // Called after downcasting by value to either the C or the E and doing a610 // ptr::read to take ownership of that value.611 if TypeId::of::<C>() == target {612 let unerased = mem::transmute::<613 Box<ErrorImpl<()>>,614 Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,615 >(e);616 drop(unerased);617 } else {618 let unerased = mem::transmute::<619 Box<ErrorImpl<()>>,620 Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,621 >(e);622 drop(unerased);623 }624}625626// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.627unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>628where629 C: 'static,630{631 if TypeId::of::<C>() == target {632 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;633 let addr = &(*unerased)._object.context as *const C as *mut ();634 Some(NonNull::new_unchecked(addr))635 } else {636 // Recurse down the context chain per the inner error's vtable.637 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;638 let source = &(*unerased)._object.error;639 (source.inner.vtable.object_downcast)(&source.inner, target)640 }641}642643// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.644unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)645where646 C: 'static,647{648 // Called after downcasting by value to either the C or one of the causes649 // and doing a ptr::read to take ownership of that value.650 if TypeId::of::<C>() == target {651 let unerased = mem::transmute::<652 Box<ErrorImpl<()>>,653 Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,654 >(e);655 // Drop the entire rest of the data structure rooted in the next Error.656 drop(unerased);657 } else {658 let unerased = mem::transmute::<659 Box<ErrorImpl<()>>,660 Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,661 >(e);662 // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.663 let inner = ptr::read(&unerased._object.error.inner);664 drop(unerased);665 let erased = ManuallyDrop::into_inner(inner);666 // Recursively drop the next error using the same target typeid.667 (erased.vtable.object_drop_rest)(erased, target);668 }669}670671// repr C to ensure that E remains in the final position.672#[repr(C)]673pub(crate) struct ErrorImpl<E> {674 vtable: &'static ErrorVTable,675 backtrace: Option<Backtrace>,676 // NOTE: Don't use directly. Use only through vtable. Erased type may have677 // different alignment.678 _object: E,679}680681// repr C to ensure that ContextError<C, E> has the same layout as682// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.683#[repr(C)]684pub(crate) struct ContextError<C, E> {685 pub context: C,686 pub error: E,687}688689impl<E> ErrorImpl<E> {690 fn erase(&self) -> &ErrorImpl<()> {691 // Erase the concrete type of E but preserve the vtable in self.vtable692 // for manipulating the resulting thin pointer. This is analogous to an693 // unsize coercion.694 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }695 }696}697698impl ErrorImpl<()> {699 pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {700 // Use vtable to attach E's native StdError vtable for the right701 // original type E.702 unsafe { &*(self.vtable.object_ref)(self) }703 }704705 #[cfg(feature = "std")]706 pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {707 // Use vtable to attach E's native StdError vtable for the right708 // original type E.709 unsafe { &mut *(self.vtable.object_mut)(self) }710 }711712 #[cfg(backtrace)]713 pub(crate) fn backtrace(&self) -> &Backtrace {714 // This unwrap can only panic if the underlying error's backtrace method715 // is nondeterministic, which would only happen in maliciously716 // constructed code.717 self.backtrace718 .as_ref()719 .or_else(|| self.error().backtrace())720 .expect("backtrace capture failed")721 }722723 pub(crate) fn chain(&self) -> Chain {724 Chain::new(self.error())725 }726}727728impl<E> StdError for ErrorImpl<E>729where730 E: StdError,731{732 #[cfg(backtrace)]733 fn backtrace(&self) -> Option<&Backtrace> {734 Some(self.erase().backtrace())735 }736737 fn source(&self) -> Option<&(dyn StdError + 'static)> {738 self.erase().error().source()739 }740}741742impl<E> Debug for ErrorImpl<E>743where744 E: Debug,745{746 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {747 self.erase().debug(formatter)748 }749}750751impl<E> Display for ErrorImpl<E>752where753 E: Display,754{755 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {756 Display::fmt(&self.erase().error(), formatter)757 }758}759760impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {761 fn from(error: Error) -> Self {762 let outer = ManuallyDrop::new(error);763 unsafe {764 // Read Box<ErrorImpl<()>> from error. Can't move it out because765 // Error has a Drop impl which we want to not run.766 let inner = ptr::read(&outer.inner);767 let erased = ManuallyDrop::into_inner(inner);768769 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for770 // the right original type E.771 (erased.vtable.object_boxed)(erased)772 }773 }774}775776impl From<Error> for Box<dyn StdError + Send + 'static> {777 fn from(error: Error) -> Self {778 Box::<dyn StdError + Send + Sync>::from(error)779 }780}781782impl From<Error> for Box<dyn StdError + 'static> {783 fn from(error: Error) -> Self {784 Box::<dyn StdError + Send + Sync>::from(error)785 }786}787788#[cfg(feature = "std")]789impl AsRef<dyn StdError + Send + Sync> for Error {790 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {791 &**self792 }793}794795#[cfg(feature = "std")]796impl AsRef<dyn StdError> for Error {797 fn as_ref(&self) -> &(dyn StdError + 'static) {798 &**self799 }800}