Skip to content
Myr

Allow running tests under miri

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

authored by Thom Chiovoloni · committed by Thom Chiovoloni · parent cb841d6 · Browse files · 5 files+183 added−108 removed
This commit

State

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

Diff stats

5 files+183 added−108 removed

  • tests:+6 added−0 removed
  • other:+177 added−108 removed

5 files+183 added−108 removed

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+164 added-98 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.
28 unmodified lines
372 {373 let target = TypeId::of::<E>();374 unsafe {375 // 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) {376 // somewhere inside the data structure. We use `_mut` here because377 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 because389 // Read Bib<ErrorImpl<()>> from self. Can't move it out because390 // 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);391 let inner = outer.inner;392393 // Drop rest of the data structure outside of E.390 (erased.vtable.object_drop_rest)(erased, target);394 (vtable(inner).object_drop_rest)(outer.inner, target);395396 Ok(error)397 }398 }
41 unmodified lines
440 let target = TypeId::of::<E>();441 unsafe {442 // Use vtable to find NonNull<()> which points to a value of type E443 // somewhere inside the data structure.440 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;444 let addr = (vtable(self.inner).object_downcast)(self.inner, target)?;445 Some(&*addr.cast::<E>().as_ptr())446 }447 }448
5 unmodified lines
454 let target = TypeId::of::<E>();455 unsafe {456 // Use vtable to find NonNull<()> which points to a value of type E457 // somewhere inside the data structure.454 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;458 let addr = (vtable(self.inner).object_downcast_mut)(self.inner, target)?;459 Some(&mut *addr.cast::<E>().as_ptr())460 }461 }462}
15 unmodified lines
478impl Deref for Error {479 type Target = dyn StdError + Send + Sync + 'static;480481 fn deref(&self) -> &Self::Target {478 self.inner.error()482 unsafe { ErrorImpl::error(self.inner) }483 }484}485486#[cfg(feature = "std")]487#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]488impl DerefMut for Error {489 fn deref_mut(&mut self) -> &mut Self::Target {486 self.inner.error_mut()490 unsafe { ErrorImpl::error_mut(self.inner) }491 }492}493494impl Display for Error {495 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {492 self.inner.display(formatter)496 unsafe { ErrorImpl::display(self.inner, formatter) }497 }498}499500impl Debug for Error {501 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {498 self.inner.debug(formatter)502 unsafe { ErrorImpl::debug(self.inner, formatter) }503 }504}505506impl Drop for Error {507 fn drop(&mut self) {508 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);510 (vtable(self.inner).object_drop)(self.inner);511 }512 }513}514515struct ErrorVTable {516 object_drop: unsafe fn(Box<ErrorImpl<()>>),517 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),516 object_drop: unsafe fn(NonNull<ErrorImpl<()>>),517 object_ref: unsafe fn(NonNull<ErrorImpl<()>>) -> *const (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),519 object_mut: unsafe fn(NonNull<ErrorImpl<()>>) -> *mut (dyn StdError + Send + Sync + 'static),520 object_boxed: unsafe fn(NonNull<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,521 object_downcast: unsafe fn(NonNull<ErrorImpl<()>>, TypeId) -> Option<NonNull<()>>,522 object_downcast_mut: unsafe fn(NonNull<ErrorImpl<()>>, TypeId) -> Option<NonNull<()>>,523 object_drop_rest: unsafe fn(NonNull<ErrorImpl<()>>, TypeId),524}525526// Safety: requires layout of *e to match ErrorImpl<E>.526unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {527unsafe fn object_drop<E>(e: NonNull<ErrorImpl<()>>) {528 // Cast back to ErrorImpl<E> so that the allocator receives the correct529 // Layout to deallocate the Box's memory.529 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);530 let unerased = Box::from_raw(e.as_ptr() as *mut ErrorImpl<E>);531 drop(unerased);532}533534// Safety: requires layout of *e to match ErrorImpl<E>.534unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {535unsafe fn object_drop_front<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) {536 // Drop the fields of ErrorImpl other than E as well as the Box allocation,537 // without dropping E itself. This is used by downcast after doing a538 // ptr::read to take ownership of the E.539 let _ = target;539 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);540 let unerased = Box::from_raw(e.as_ptr() as *mut ErrorImpl<ManuallyDrop<E>>);541 drop(unerased);542}543544// Safety: requires layout of *e to match ErrorImpl<E>.544unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)545unsafe fn object_ref<E>(e: NonNull<ErrorImpl<()>>) -> *const (dyn StdError + Send + Sync + 'static)546where547 E: StdError + Send + Sync + 'static,548{549 // Attach E's native StdError vtable onto a pointer to self._object.549 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object550 &(*(e.as_ptr() as *const ErrorImpl<E>))._object551}552552// Safety: requires layout of *e to match ErrorImpl<E>.553// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived554// from a `&mut`555#[cfg(feature = "std")]554unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)556unsafe fn object_mut<E>(e: NonNull<ErrorImpl<()>>) -> *mut (dyn StdError + Send + Sync + 'static)557where558 E: StdError + Send + Sync + 'static,559{560 // Attach E's native StdError vtable onto a pointer to self._object.559 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object561 &mut (*(e.as_ptr() as *mut ErrorImpl<E>))._object562}563564// Safety: requires layout of *e to match ErrorImpl<E>.563unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>565unsafe fn object_boxed<E>(e: NonNull<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>566where567 E: StdError + Send + Sync + 'static,568{569 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.568 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)570 Box::<ErrorImpl<E>>::from_raw(e.as_ptr() as *mut ErrorImpl<E>)571}572573// Safety: requires layout of *e to match ErrorImpl<E>.572unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>574unsafe fn object_downcast<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>575where576 E: 'static,577{578 if TypeId::of::<E>() == target {579 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a580 // pointer to its E field.579 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;581 let unerased = e.as_ptr() as *const ErrorImpl<E>;582 let addr = &(*unerased)._object as *const E as *mut ();583 Some(NonNull::new_unchecked(addr))584 } else {585 None586 }587}588589// Safety: requires layout of *e to match ErrorImpl<E> and for deriving a &mut590// from `e` not to violate provenance591unsafe fn object_downcast_mut<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>592where593 E: 'static,594{595 if TypeId::of::<E>() == target {596 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a597 // pointer to its E field.598 let unerased = e.as_ptr() as *mut ErrorImpl<E>;599 let addr = &mut (*unerased)._object as *mut E as *mut ();600 Some(NonNull::new_unchecked(addr))601 } else {602 None603 }604}605606// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.607#[cfg(feature = "std")]589unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>608unsafe fn context_downcast<C, E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>609where610 C: 'static,611 E: 'static,612{613 if TypeId::of::<C>() == target {595 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;614 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, E>>;615 let addr = &(*unerased)._object.context as *const C as *mut ();616 Some(NonNull::new_unchecked(addr))617 } else if TypeId::of::<E>() == target {599 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;618 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, E>>;619 let addr = &(*unerased)._object.error as *const E as *mut ();620 Some(NonNull::new_unchecked(addr))621 } else {622 None623 }624}625626#[cfg(feature = "std")]627unsafe fn context_downcast_mut<C, E>(628 e: NonNull<ErrorImpl<()>>,629 target: TypeId,630) -> Option<NonNull<()>>631where632 C: 'static,633 E: 'static,634{635 if TypeId::of::<C>() == target {636 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, E>>;637 let addr = &mut (*unerased)._object.context as *mut C as *mut ();638 Some(NonNull::new_unchecked(addr))639 } else if TypeId::of::<E>() == target {640 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, E>>;641 let addr = &mut (*unerased)._object.error as *mut E as *mut ();642 Some(NonNull::new_unchecked(addr))643 } else {644 None645 }646}647648// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.649#[cfg(feature = "std")]609unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)650unsafe fn context_drop_rest<C, E>(e: NonNull<ErrorImpl<()>>, target: TypeId)651where652 C: 'static,653 E: 'static,654{655 // Called after downcasting by value to either the C or the E and doing a656 // ptr::read to take ownership of that value.657 if TypeId::of::<C>() == target {617 let unerased = mem::transmute::<618 Box<ErrorImpl<()>>,619 Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,620 >(e);658 let unerased =659 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<ManuallyDrop<C>, E>>);660 drop(unerased);661 } else {623 let unerased = mem::transmute::<624 Box<ErrorImpl<()>>,625 Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,626 >(e);662 let unerased =663 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<C, ManuallyDrop<E>>>);664 drop(unerased);665 }666}667668// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.632unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>669unsafe fn context_chain_downcast<C>(670 e: NonNull<ErrorImpl<()>>,671 target: TypeId,672) -> Option<NonNull<()>>673where674 C: 'static,675{676 if TypeId::of::<C>() == target {637 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;677 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, Error>>;678 let addr = &(*unerased)._object.context as *const C as *mut ();679 Some(NonNull::new_unchecked(addr))680 } else {681 // Recurse down the context chain per the inner error's vtable.642 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;682 let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, Error>>;683 let source = &(*unerased)._object.error;644 (source.inner.vtable.object_downcast)(&source.inner, target)684 (vtable(source.inner).object_downcast)(source.inner, target)685 }686}687688unsafe fn context_chain_downcast_mut<C>(689 e: NonNull<ErrorImpl<()>>,690 target: TypeId,691) -> Option<NonNull<()>>692where693 C: 'static,694{695 if TypeId::of::<C>() == target {696 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, Error>>;697 let addr = &mut (*unerased)._object.context as *mut C as *mut ();698 Some(NonNull::new_unchecked(addr))699 } else {700 // Recurse down the context chain per the inner error's vtable.701 let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, Error>>;702 let source = &mut (*unerased)._object.error;703 (vtable(source.inner).object_downcast_mut)(source.inner, target)704 }705}706707// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.649unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)708unsafe fn context_chain_drop_rest<C>(e: NonNull<ErrorImpl<()>>, target: TypeId)709where710 C: 'static,711{712 // Called after downcasting by value to either the C or one of the causes713 // and doing a ptr::read to take ownership of that value.714 if TypeId::of::<C>() == target {656 let unerased = mem::transmute::<657 Box<ErrorImpl<()>>,658 Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,659 >(e);715 let unerased =716 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<ManuallyDrop<C>, Error>>);717 // Drop the entire rest of the data structure rooted in the next Error.718 drop(unerased);719 } 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);720 let unerased =721 Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<C, ManuallyDrop<Error>>>);722 // Read the NonNull<ErrorImpl<()>> from the next error.723 let inner = unerased._object.error.inner;724 drop(unerased);670 let erased = ManuallyDrop::into_inner(inner);725 let vtable = inner.as_ref().vtable;726 // Recursively drop the next error using the same target typeid.672 (erased.vtable.object_drop_rest)(erased, target);727 (vtable.object_drop_rest)(inner, target);728 }729}730731// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor732// of raw pointers and `NonNull`.733// repr C to ensure that E remains in the final position.734#[repr(C)]735pub(crate) struct ErrorImpl<E> {736 vtable: &'static ErrorVTable,
2 unmodified lines
739 // different alignment.740 _object: E,741}742743// Read the vtable out of `p`. This is the same as `p.as_ref().vtable`, but744// avoids converting `p` into a reference.745#[inline]746unsafe fn vtable<E>(p: NonNull<ErrorImpl<E>>) -> &'static ErrorVTable {747 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.748 (p.as_ptr() as *const &'static ErrorVTable).read()749}750751// repr C to ensure that ContextError<C, E> has the same layout as752// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.753#[repr(C)]754pub(crate) struct ContextError<C, E> {
1 unmodified line
756 pub error: E,757}758759impl<E> ErrorImpl<E> {695 fn erase(&self) -> &ErrorImpl<()> {760 fn erase(&self) -> NonNull<ErrorImpl<()>> {761 // Erase the concrete type of E but preserve the vtable in self.vtable762 // for manipulating the resulting thin pointer. This is analogous to an763 // unsize coercion.699 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }764 NonNull::from(self).cast::<ErrorImpl<()>>()765 }766}767768impl ErrorImpl<()> {704 pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {769 pub(crate) unsafe fn error<'a>(770 this: NonNull<Self>,771 ) -> &'a (dyn StdError + Send + Sync + 'static) {772 // Use vtable to attach E's native StdError vtable for the right773 // original type E.707 unsafe { &*(self.vtable.object_ref)(self) }774 &*(vtable(this).object_ref)(this)775 }776710 #[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 }716777 #[cfg(backtrace)]718 pub(crate) fn backtrace(&self) -> &Backtrace {778 pub(crate) unsafe fn backtrace<'a>(this: NonNull<Self>) -> &'a Backtrace {779 // Ideally we would use a raw ref to access `backtrace`, but I780 // don't think this matters given how we use781 let backtrace = (*this.as_ptr()).backtrace.as_ref();782 // This unwrap can only panic if the underlying error's backtrace method783 // is nondeterministic, which would only happen in maliciously784 // constructed code.722 self.backtrace723 .as_ref()724 .or_else(|| self.error().backtrace())785 backtrace786 .or_else(|| Self::error(this).backtrace())787 .expect("backtrace capture failed")788 }789728 pub(crate) fn chain(&self) -> Chain {729 Chain::new(self.error())790 #[cfg(feature = "std")]791 pub(crate) unsafe fn error_mut<'a>(792 this: NonNull<ErrorImpl<()>>,793 ) -> &'a mut (dyn StdError + Send + Sync + 'static) {794 // Use vtable to attach E's native StdError vtable for the right795 // original type E.796 &mut *(vtable(this).object_mut)(this)797 }798799 pub(crate) unsafe fn chain<'a>(this: NonNull<Self>) -> Chain<'a> {800 Chain::new(Self::error(this))801 }802}803804impl<E> StdError for ErrorImpl<E>805where806 E: StdError,807{808 #[cfg(backtrace)]809 fn backtrace(&self) -> Option<&Backtrace> {739 Some(self.erase().backtrace())810 Some(unsafe { ErrorImpl::backtrace(self.erase()) })811 }812813 fn source(&self) -> Option<&(dyn StdError + 'static)> {743 self.erase().error().source()814 unsafe { ErrorImpl::error(self.erase()).source() }815 }816}817818impl<E> Debug for ErrorImpl<E>819where820 E: Debug,821{822 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {752 self.erase().debug(formatter)823 unsafe { ErrorImpl::debug(self.erase(), formatter) }824 }825}826827impl<E> Display for ErrorImpl<E>828where829 E: Display,830{831 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {761 Display::fmt(&self.erase().error(), formatter)832 unsafe { Display::fmt(&ErrorImpl::error(self.erase()), formatter) }833 }834}835836impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {837 fn from(error: Error) -> Self {838 let outer = ManuallyDrop::new(error);839 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);773840 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for841 // the right original type E.776 (erased.vtable.object_boxed)(erased)842 (vtable(outer.inner).object_boxed)(outer.inner)843 }844 }845}846
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