Skip to content
Myr

Merge pull request 134 from thomcc/mirimiri

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parents 52c2c4c, 9757e7f · Browse files · 6 files+184 added−103 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+184 added−103 removed

  • tests:+6 added−0 removed
  • other:+178 added−103 removed

6 files+184 added−103 removed

modified:.github/workflows/ci.yml+10 added
modified:src/context.rs+1 added-1 removed
141 unmodified lines
142 Some(self.error.backtrace())143 }144145 fn source(&self) -> Option<&(dyn StdError + 'static)> {146 Some(self.error.inner.error())146 Some(unsafe { crate::ErrorImpl::error(self.error.inner) })147 }148}149150struct Quoted<C>(C);
27 unmodified lines
modified:src/error.rs+155 added-93 removed
2 unmodified lines
3use crate::chain::Chain;4use crate::{Error, StdError};5use core::any::TypeId;6use core::fmt::{self, Debug, Display};7use core::mem::{self, ManuallyDrop};7use core::mem::ManuallyDrop;8use core::ptr::{self, NonNull};910#[cfg(feature = "std")]11use core::ops::{Deref, DerefMut};
70 unmodified lines
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_downcast_mut: object_downcast_mut::<E>,87 object_drop_rest: object_drop_front::<E>,88 };8990 // Safety: passing vtable that operates on the right type E.
12 unmodified lines
103 #[cfg(feature = "std")]104 object_mut: object_mut::<MessageError<M>>,105 object_boxed: object_boxed::<MessageError<M>>,106 object_downcast: object_downcast::<M>,107 object_downcast_mut: object_downcast_mut::<M>,108 object_drop_rest: object_drop_front::<M>,109 };110111 // Safety: MessageError is repr(transparent) so it is okay for the
13 unmodified lines
125 #[cfg(feature = "std")]126 object_mut: object_mut::<DisplayError<M>>,127 object_boxed: object_boxed::<DisplayError<M>>,128 object_downcast: object_downcast::<M>,129 object_downcast_mut: object_downcast_mut::<M>,130 object_drop_rest: object_drop_front::<M>,131 };132133 // Safety: DisplayError is repr(transparent) so it is okay for the
14 unmodified lines
148 object_ref: object_ref::<ContextError<C, E>>,149 object_mut: object_mut::<ContextError<C, E>>,150 object_boxed: object_boxed::<ContextError<C, E>>,151 object_downcast: context_downcast::<C, E>,152 object_downcast_mut: context_downcast_mut::<C, E>,153 object_drop_rest: context_drop_rest::<C, E>,154 };155156 // Safety: passing vtable that operates on the right type.
12 unmodified lines
169 object_ref: object_ref::<BoxedError>,170 object_mut: object_mut::<BoxedError>,171 object_boxed: object_boxed::<BoxedError>,172 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,173 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,174 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,175 };176177 // Safety: BoxedError is repr(transparent) so it is okay for the vtable
13 unmodified lines
191 ) -> Self192 where193 E: StdError + Send + Sync + 'static,194 {190 let inner = Box::new(ErrorImpl {195 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {196 vtable,197 backtrace,198 _object: error,199 });
2 unmodified lines
202 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the203 // result is a thin pointer. The necessary behavior for manipulating the204 // underlying ErrorImpl<E> is preserved in the vtable provided by the205 // 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);206 let inner = NonNull::new_unchecked(Box::into_raw(inner) as *mut ErrorImpl<()>);207 Error { inner }208 }209210 /// Wrap the error value with additional context.
65 unmodified lines
276 #[cfg(feature = "std")]277 object_mut: object_mut::<ContextError<C, Error>>,278 object_boxed: object_boxed::<ContextError<C, Error>>,279 object_downcast: context_chain_downcast::<C>,280 object_downcast_mut: context_chain_downcast_mut::<C>,281 object_drop_rest: context_chain_drop_rest::<C>,282 };283284 // As the cause is anyhow::Error, we already have a backtrace for it.
23 unmodified lines
308 ///309 /// [tracking]: https://github.com/rust-lang/rust/issues/53487310 #[cfg(backtrace)]311 pub fn backtrace(&self) -> &Backtrace {307 self.inner.backtrace()312 unsafe { ErrorImpl::backtrace(self.inner) }313 }314315 /// An iterator of the chain of source errors contained by this Error.316 ///
18 unmodified lines
335 /// ```336 #[cfg(feature = "std")]337 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]338 pub fn chain(&self) -> Chain {334 self.inner.chain()339 unsafe { ErrorImpl::chain(self.inner) }340 }341342 /// The lowest level cause of this error &mdash; this error's cause's343 /// cause's cause etc.
29 unmodified lines
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.372 let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {377 let addr = match (vtable(self.inner).object_downcast_mut)(self.inner, target) {378 Some(addr) => addr,379 None => return Err(self),380 };381
3 unmodified lines
385386 // Read E from where the vtable found it.387 let error = ptr::read(addr.cast::<E>().as_ptr());388384 // 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);390 (vtable(outer.inner).object_drop_rest)(outer.inner, target);391392 Ok(error)393 }394 }
41 unmodified lines
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)?;440 let addr = (vtable(self.inner).object_downcast)(self.inner, target)?;441 Some(&*addr.cast::<E>().as_ptr())442 }443 }444
5 unmodified lines
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)?;454 let addr = (vtable(self.inner).object_downcast_mut)(self.inner, target)?;455 Some(&mut *addr.cast::<E>().as_ptr())456 }457 }458}
15 unmodified lines
474impl Deref for Error {475 type Target = dyn StdError + Send + Sync + 'static;476477 fn deref(&self) -> &Self::Target {478 self.inner.error()478 unsafe { ErrorImpl::error(self.inner) }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()486 unsafe { ErrorImpl::error_mut(self.inner) }487 }488}489490impl Display for Error {491 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {492 self.inner.display(formatter)492 unsafe { ErrorImpl::display(self.inner, formatter) }493 }494}495496impl Debug for Error {497 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {498 self.inner.debug(formatter)498 unsafe { ErrorImpl::debug(self.inner, 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);508505 // Invoke the vtable's drop behavior.510 (erased.vtable.object_drop)(erased);506 (vtable(self.inner).object_drop)(self.inner);507 }508 }509}510511struct ErrorVTable {516 object_drop: unsafe fn(Box<ErrorImpl<()>>),517 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),512 object_drop: unsafe fn(NonNull<ErrorImpl<()>>),513 object_ref: unsafe fn(NonNull<ErrorImpl<()>>) -> *const (dyn StdError + Send + Sync + 'static),514 #[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),515 object_mut: unsafe fn(NonNull<ErrorImpl<()>>) -> *mut (dyn StdError + Send + Sync + 'static),516 object_boxed: unsafe fn(NonNull<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,517 object_downcast: unsafe fn(NonNull<ErrorImpl<()>>, TypeId) -> Option<NonNull<()>>,518 object_downcast_mut: unsafe fn(NonNull<ErrorImpl<()>>, TypeId) -> Option<NonNull<()>>,519 object_drop_rest: unsafe fn(NonNull<ErrorImpl<()>>, TypeId),520}521522// Safety: requires layout of *e to match ErrorImpl<E>.526unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {523unsafe fn object_drop<E>(e: NonNull<ErrorImpl<()>>) {524 // Cast back to ErrorImpl<E> so that the allocator receives the correct525 // Layout to deallocate the Box's memory.529 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);526 let unerased = Box::from_raw(e.as_ptr() as *mut ErrorImpl<E>);527 drop(unerased);528}529530// Safety: requires layout of *e to match ErrorImpl<E>.534unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {531unsafe fn object_drop_front<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) {532 // Drop the fields of ErrorImpl other than E as well as the Box allocation,533 // without dropping E itself. This is used by downcast after doing a534 // ptr::read to take ownership of the E.535 let _ = target;539 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);536 let unerased = Box::from_raw(e.as_ptr() as *mut ErrorImpl<ManuallyDrop<E>>);537 drop(unerased);538}539540// Safety: requires layout of *e to match ErrorImpl<E>.544unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)541unsafe fn object_ref<E>(e: NonNull<ErrorImpl<()>>) -> *const (dyn StdError + Send + Sync + 'static)542where543 E: StdError + Send + Sync + 'static,544{545 // Attach E's native StdError vtable onto a pointer to self._object.549 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object546 &(*(e.as_ptr() as *const ErrorImpl<E>))._object547}548552// Safety: requires layout of *e to match ErrorImpl<E>.549// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived550// from a `&mut`551#[cfg(feature = "std")]554unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)552unsafe fn object_mut<E>(e: NonNull<ErrorImpl<()>>) -> *mut (dyn StdError + Send + Sync + 'static)553where554 E: StdError + Send + Sync + 'static,555{556 // Attach E's native StdError vtable onto a pointer to self._object.559 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object557 &mut (*(e.as_ptr() as *mut ErrorImpl<E>))._object558}559560// Safety: requires layout of *e to match ErrorImpl<E>.563unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>561unsafe fn object_boxed<E>(e: NonNull<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>562where563 E: StdError + Send + Sync + 'static,564{565 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.568 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)566 Box::<ErrorImpl<E>>::from_raw(e.as_ptr() as *mut ErrorImpl<E>)567}568569// Safety: requires layout of *e to match ErrorImpl<E>.572unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>570unsafe fn object_downcast<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>571where572 E: 'static,573{574 if TypeId::of::<E>() == target {575 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a576 // pointer to its E field.579 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;577 let unerased = e.as_ptr() as *const ErrorImpl<E>;578 let addr = &(*unerased)._object as *const E as *mut ();579 Some(NonNull::new_unchecked(addr))580 } else {581 None582 }583}584585// Safety: requires layout of *e to match ErrorImpl<E>.586unsafe fn object_downcast_mut<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>587where588 E: 'static,589{590 if TypeId::of::<E>() == target {591 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a592 // pointer to its E field.593 let unerased = e.as_ptr() as *mut ErrorImpl<E>;594 let addr = &mut (*unerased)._object as *mut 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")]589unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>603unsafe fn context_downcast<C, E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>604where605 C: 'static,606 E: 'static,607{608 if TypeId::of::<C>() == target {595 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;609 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, E>>;610 let addr = &(*unerased)._object.context as *const C as *mut ();611 Some(NonNull::new_unchecked(addr))612 } else if TypeId::of::<E>() == target {599 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;613 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, E>>;614 let addr = &(*unerased)._object.error as *const E as *mut ();615 Some(NonNull::new_unchecked(addr))616 } else {617 None
1 unmodified line
619}620621// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.622#[cfg(feature = "std")]609unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)623unsafe fn context_downcast_mut<C, E>(624 e: NonNull<ErrorImpl<()>>,625 target: TypeId,626) -> Option<NonNull<()>>627where628 C: 'static,629 E: 'static,630{631 if TypeId::of::<C>() == target {632 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, E>>;633 let addr = &mut (*unerased)._object.context as *mut C as *mut ();634 Some(NonNull::new_unchecked(addr))635 } else if TypeId::of::<E>() == target {636 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, E>>;637 let addr = &mut (*unerased)._object.error as *mut E as *mut ();638 Some(NonNull::new_unchecked(addr))639 } else {640 None641 }642}643644// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.645#[cfg(feature = "std")]646unsafe fn context_drop_rest<C, E>(e: NonNull<ErrorImpl<()>>, target: TypeId)647where648 C: 'static,649 E: 'static,650{651 // Called after downcasting by value to either the C or the E and doing a652 // ptr::read to take ownership of that value.653 if TypeId::of::<C>() == target {617 let unerased = mem::transmute::<618 Box<ErrorImpl<()>>,619 Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,620 >(e);654 let unerased =655 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<ManuallyDrop<C>, E>>);656 drop(unerased);657 } else {623 let unerased = mem::transmute::<624 Box<ErrorImpl<()>>,625 Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,626 >(e);658 let unerased =659 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<C, ManuallyDrop<E>>>);660 drop(unerased);661 }662}663664// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.632unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>665unsafe fn context_chain_downcast<C>(666 e: NonNull<ErrorImpl<()>>,667 target: TypeId,668) -> Option<NonNull<()>>669where670 C: 'static,671{672 if TypeId::of::<C>() == target {637 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;673 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, Error>>;674 let addr = &(*unerased)._object.context as *const C as *mut ();675 Some(NonNull::new_unchecked(addr))676 } else {677 // Recurse down the context chain per the inner error's vtable.642 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;678 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, Error>>;679 let source = &(*unerased)._object.error;644 (source.inner.vtable.object_downcast)(&source.inner, target)680 (vtable(source.inner).object_downcast)(source.inner, target)681 }682}683684// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.649unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)685unsafe fn context_chain_downcast_mut<C>(686 e: NonNull<ErrorImpl<()>>,687 target: TypeId,688) -> Option<NonNull<()>>689where690 C: 'static,691{692 if TypeId::of::<C>() == target {693 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, Error>>;694 let addr = &mut (*unerased)._object.context as *mut C as *mut ();695 Some(NonNull::new_unchecked(addr))696 } else {697 // Recurse down the context chain per the inner error's vtable.698 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, Error>>;699 let source = &mut (*unerased)._object.error;700 (vtable(source.inner).object_downcast_mut)(source.inner, target)701 }702}703704// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.705unsafe fn context_chain_drop_rest<C>(e: NonNull<ErrorImpl<()>>, target: TypeId)706where707 C: 'static,708{709 // Called after downcasting by value to either the C or one of the causes710 // and doing a ptr::read to take ownership of that value.711 if TypeId::of::<C>() == target {656 let unerased = mem::transmute::<657 Box<ErrorImpl<()>>,658 Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,659 >(e);712 let unerased =713 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<ManuallyDrop<C>, Error>>);714 // Drop the entire rest of the data structure rooted in the next Error.715 drop(unerased);716 } 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);717 let unerased =718 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<C, ManuallyDrop<Error>>>);719 // Read the NonNull<ErrorImpl<()>> from the next error.720 let inner = unerased._object.error.inner;721 drop(unerased);670 let erased = ManuallyDrop::into_inner(inner);722 let vtable = inner.as_ref().vtable;723 // Recursively drop the next error using the same target typeid.672 (erased.vtable.object_drop_rest)(erased, target);724 (vtable.object_drop_rest)(inner, target);725 }726}727728// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor729// of raw pointers and `NonNull`.730// repr C to ensure that E remains in the final position.731#[repr(C)]732pub(crate) struct ErrorImpl<E> {733 vtable: &'static ErrorVTable,
2 unmodified lines
736 // different alignment.737 _object: E,738}739740// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but741// avoids converting `p` into a reference.742#[inline]743unsafe fn vtable<E>(p: NonNull<ErrorImpl<E>>) -> &'static ErrorVTable {744 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.745 (p.as_ptr() as *const &'static ErrorVTable).read()746}747748// repr C to ensure that ContextError<C, E> has the same layout as749// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.750#[repr(C)]751pub(crate) struct ContextError<C, E> {
1 unmodified line
753 pub error: E,754}755756impl<E> ErrorImpl<E> {695 fn erase(&self) -> &ErrorImpl<()> {757 fn erase(&self) -> NonNull<ErrorImpl<()>> {758 // Erase the concrete type of E but preserve the vtable in self.vtable759 // for manipulating the resulting thin pointer. This is analogous to an760 // unsize coercion.699 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }761 NonNull::from(self).cast::<ErrorImpl<()>>()762 }763}764765impl ErrorImpl<()> {704 pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {766 pub(crate) unsafe fn error<'a>(767 this: NonNull<Self>,768 ) -> &'a (dyn StdError + Send + Sync + 'static) {769 // Use vtable to attach E's native StdError vtable for the right770 // original type E.707 unsafe { &*(self.vtable.object_ref)(self) }771 &*(vtable(this).object_ref)(this)772 }773774 #[cfg(feature = "std")]711 pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {775 pub(crate) unsafe fn error_mut<'a>(776 this: NonNull<Self>,777 ) -> &'a mut (dyn StdError + Send + Sync + 'static) {778 // Use vtable to attach E's native StdError vtable for the right779 // original type E.714 unsafe { &mut *(self.vtable.object_mut)(self) }780 &mut *(vtable(this).object_mut)(this)781 }782783 #[cfg(backtrace)]718 pub(crate) fn backtrace(&self) -> &Backtrace {784 pub(crate) unsafe fn backtrace<'a>(this: NonNull<Self>) -> &'a Backtrace {785 // This unwrap can only panic if the underlying error's backtrace method786 // is nondeterministic, which would only happen in maliciously787 // constructed code.788 (*this.as_ptr())722 self.backtrace789 .backtrace790 .as_ref()724 .or_else(|| self.error().backtrace())791 .or_else(|| Self::error(this).backtrace())792 .expect("backtrace capture failed")793 }794728 pub(crate) fn chain(&self) -> Chain {729 Chain::new(self.error())795 pub(crate) unsafe fn chain<'a>(this: NonNull<Self>) -> Chain<'a> {796 Chain::new(Self::error(this))797 }798}799800impl<E> StdError for ErrorImpl<E>
1 unmodified line
802 E: StdError,803{804 #[cfg(backtrace)]805 fn backtrace(&self) -> Option<&Backtrace> {739 Some(self.erase().backtrace())806 Some(unsafe { ErrorImpl::backtrace(self.erase()) })807 }808809 fn source(&self) -> Option<&(dyn StdError + 'static)> {743 self.erase().error().source()810 unsafe { ErrorImpl::error(self.erase()).source() }811 }812}813814impl<E> Debug for ErrorImpl<E>815where816 E: Debug,817{818 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {752 self.erase().debug(formatter)819 unsafe { ErrorImpl::debug(self.erase(), formatter) }820 }821}822823impl<E> Display for ErrorImpl<E>824where825 E: Display,826{827 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {761 Display::fmt(&self.erase().error(), formatter)828 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }829 }830}831832impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {833 fn from(error: Error) -> Self {834 let outer = ManuallyDrop::new(error);835 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);773836 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for837 // the right original type E.776 (erased.vtable.object_boxed)(erased)838 (vtable(outer.inner).object_boxed)(outer.inner)839 }840 }841}842
25 unmodified lines
modified:src/fmt.rs+7 added-6 removed
1use crate::chain::Chain;2use crate::error::ErrorImpl;3use core::fmt::{self, Debug, Write};4use core::ptr::NonNull;56impl ErrorImpl<()> {6 pub(crate) fn display(&self, f: &mut fmt::Formatter) -> fmt::Result {7 write!(f, "{}", self.error())?;7 pub(crate) unsafe fn display(this: NonNull<Self>, f: &mut fmt::Formatter) -> fmt::Result {8 write!(f, "{}", Self::error(this))?;910 if f.alternate() {10 for cause in self.chain().skip(1) {11 for cause in Self::chain(this).skip(1) {12 write!(f, ": {}", cause)?;13 }14 }1516 Ok(())17 }1818 pub(crate) fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {19 let error = self.error();19 pub(crate) unsafe fn debug(this: NonNull<Self>, f: &mut fmt::Formatter) -> fmt::Result {20 let error = Self::error(this);2122 if f.alternate() {23 return Debug::fmt(error, f);24 }
17 unmodified lines
42 #[cfg(backtrace)]43 {44 use std::backtrace::BacktraceStatus;4545 let backtrace = self.backtrace();46 let backtrace = Self::backtrace(this);47 if let BacktraceStatus::Captured = backtrace.status() {48 let mut backtrace = backtrace.to_string();49 write!(f, "\n\n")?;50 if backtrace.starts_with("stack backtrace:") {
105 unmodified lines
modified:src/lib.rs+5 added-3 removed
246 unmodified lines
247mod kind;248mod macros;249mod wrapper;250251use crate::alloc::Box;251use crate::error::ErrorImpl;252use core::fmt::Display;254use core::mem::ManuallyDrop;253use core::ptr::NonNull;254255#[cfg(not(feature = "std"))]256use core::fmt::Debug;257
111 unmodified lines
369/// }370/// ```371#[repr(transparent)]372pub struct Error {374 inner: ManuallyDrop<Box<ErrorImpl<()>>>,373 inner: NonNull<ErrorImpl<()>>,374}375376unsafe impl Send for Error {}377unsafe impl Sync for Error {}378379/// Iterator of a chain of source errors.380///381/// This type is the iterator returned by [`Error::chain`].382///
277 unmodified lines
modified:tests/test_downcast.rs+6 added
66 unmodified lines
67 .downcast_mut::<io::Error>()68 .unwrap()69 .to_string(),70 );7172 let mut bailed = bail_fmt().unwrap_err();73 *bailed.downcast_mut::<String>().unwrap() = "clobber".to_string();74 assert_eq!(bailed.downcast_ref::<String>().unwrap(), "clobber");75 assert_eq!(bailed.downcast_mut::<String>().unwrap(), "clobber");76 assert_eq!(bailed.downcast::<String>().unwrap(), "clobber");77}7879#[test]80fn test_drop() {
34 unmodified lines