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
Provenance
- Commit
ae372df- Tree
d785d53- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent 1
52c2c4c- Parent 2
9757e7f
6 files changed+184 added−103 removed
modified:.github/workflows/ci.yml+10 added
42 unmodified lines434445464748495051525354555642 unmodified lines steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic
miri: name: Miri runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@nightly with: components: miri - run: cargo miri testmodified:src/context.rs+1 added-1 removed
141 unmodified lines142 Some(self.error.backtrace())143 }144 145 fn source(&self) -> Option<&(dyn StdError + 'static)> {146- Some(self.error.inner.error())146+ Some(unsafe { crate::ErrorImpl::error(self.error.inner) })147 }148 }149 150 struct Quoted<C>(C);27 unmodified linesmodified:src/error.rs+155 added-93 removed
2 unmodified lines3 use crate::chain::Chain;4 use crate::{Error, StdError};5 use core::any::TypeId;6 use core::fmt::{self, Debug, Display};7-use core::mem::{self, ManuallyDrop};7+use core::mem::ManuallyDrop;8 use core::ptr::{self, NonNull};9 10 #[cfg(feature = "std")]11 use core::ops::{Deref, DerefMut};70 unmodified lines82 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 };89 90 // Safety: passing vtable that operates on the right type E.12 unmodified lines103 #[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 };110 111 // Safety: MessageError is repr(transparent) so it is okay for the13 unmodified lines125 #[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 };132 133 // Safety: DisplayError is repr(transparent) so it is okay for the14 unmodified lines148 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 };155 156 // Safety: passing vtable that operates on the right type.12 unmodified lines169 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 };176 177 // Safety: BoxedError is repr(transparent) so it is okay for the vtable13 unmodified lines191 ) -> 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 lines202 // 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 }209 210 /// Wrap the error value with additional context.65 unmodified lines276 #[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 };283 284 // As the cause is anyhow::Error, we already have a backtrace for it.23 unmodified lines308 ///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 }314 315 /// An iterator of the chain of source errors contained by this Error.316 ///18 unmodified lines335 /// ```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 }341 342 /// The lowest level cause of this error — this error's cause's343 /// cause's cause etc.29 unmodified lines373 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 lines385 386 // Read E from where the vtable found it.387 let error = ptr::read(addr.cast::<E>().as_ptr());388 384- // 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);388-389 // 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);391 392 Ok(error)393 }394 }41 unmodified lines436 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 lines450 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 lines474 impl Deref for Error {475 type Target = dyn StdError + Send + Sync + 'static;476 477 fn deref(&self) -> &Self::Target {478- self.inner.error()478+ unsafe { ErrorImpl::error(self.inner) }479 }480 }481 482 #[cfg(feature = "std")]483 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]484 impl 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 }489 490 impl 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 }495 496 impl 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 }501 502 impl 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);508-505 // Invoke the vtable's drop behavior.510- (erased.vtable.object_drop)(erased);506+ (vtable(self.inner).object_drop)(self.inner);507 }508 }509 }510 511 struct 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 }521 522 // Safety: requires layout of *e to match ErrorImpl<E>.526-unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {523+unsafe 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 }529 530 // Safety: requires layout of *e to match ErrorImpl<E>.534-unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {531+unsafe 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 }539 540 // Safety: requires layout of *e to match ErrorImpl<E>.544-unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)541+unsafe fn object_ref<E>(e: NonNull<ErrorImpl<()>>) -> *const (dyn StdError + Send + Sync + 'static)542 where543 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 }548 552-// 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")]554-unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)552+unsafe fn object_mut<E>(e: NonNull<ErrorImpl<()>>) -> *mut (dyn StdError + Send + Sync + 'static)553 where554 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 }559 560 // Safety: requires layout of *e to match ErrorImpl<E>.563-unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>561+unsafe fn object_boxed<E>(e: NonNull<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>562 where563 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 }568 569 // Safety: requires layout of *e to match ErrorImpl<E>.572-unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>570+unsafe fn object_downcast<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>571 where572 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 }584 585+// Safety: requires layout of *e to match ErrorImpl<E>.586+unsafe fn object_downcast_mut<E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>587+where588+ 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+}600+601 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.602 #[cfg(feature = "std")]589-unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>603+unsafe fn context_downcast<C, E>(e: NonNull<ErrorImpl<()>>, target: TypeId) -> Option<NonNull<()>>604 where605 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 None1 unmodified line619 }620 621 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.622 #[cfg(feature = "std")]609-unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)623+unsafe fn context_downcast_mut<C, E>(624+ e: NonNull<ErrorImpl<()>>,625+ target: TypeId,626+) -> Option<NonNull<()>>627 where628 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+}643+644+// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.645+#[cfg(feature = "std")]646+unsafe fn context_drop_rest<C, E>(e: NonNull<ErrorImpl<()>>, target: TypeId)647+where648+ 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 }663 664 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.632-unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>665+unsafe fn context_chain_downcast<C>(666+ e: NonNull<ErrorImpl<()>>,667+ target: TypeId,668+) -> Option<NonNull<()>>669 where670 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 }683 684 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.649-unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)685+unsafe fn context_chain_downcast_mut<C>(686+ e: NonNull<ErrorImpl<()>>,687+ target: TypeId,688+) -> Option<NonNull<()>>689 where690 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+}703+704+// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.705+unsafe fn context_chain_drop_rest<C>(e: NonNull<ErrorImpl<()>>, target: TypeId)706+where707+ 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 }727 728+// 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)]732 pub(crate) struct ErrorImpl<E> {733 vtable: &'static ErrorVTable,2 unmodified lines736 // different alignment.737 _object: E,738 }739 740+// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but741+// avoids converting `p` into a reference.742+#[inline]743+unsafe 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+}747+748 // 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)]751 pub(crate) struct ContextError<C, E> {1 unmodified line753 pub error: E,754 }755 756 impl<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 }764 765 impl 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 }773 774 #[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 }782 783 #[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 }794 728- 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 }799 800 impl<E> StdError for ErrorImpl<E>1 unmodified line802 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 }808 809 fn source(&self) -> Option<&(dyn StdError + 'static)> {743- self.erase().error().source()810+ unsafe { ErrorImpl::error(self.erase()).source() }811 }812 }813 814 impl<E> Debug for ErrorImpl<E>815 where816 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 }822 823 impl<E> Display for ErrorImpl<E>824 where825 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 }831 832 impl 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);773-836 // 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 linesmodified:src/fmt.rs+7 added-6 removed
1 use crate::chain::Chain;2 use crate::error::ErrorImpl;3 use core::fmt::{self, Debug, Write};4+use core::ptr::NonNull;5 6 impl 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))?;9 10 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 }15 16 Ok(())17 }18 18- 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);21 22 if f.alternate() {23 return Debug::fmt(error, f);24 }17 unmodified lines42 #[cfg(backtrace)]43 {44 use std::backtrace::BacktraceStatus;45 45- 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 linesmodified:src/lib.rs+5 added-3 removed
246 unmodified lines247 mod kind;248 mod macros;249 mod wrapper;250 251-use crate::alloc::Box;251 use crate::error::ErrorImpl;252 use core::fmt::Display;254-use core::mem::ManuallyDrop;253+use core::ptr::NonNull;254 255 #[cfg(not(feature = "std"))]256 use core::fmt::Debug;257 111 unmodified lines369 /// }370 /// ```371 #[repr(transparent)]372 pub struct Error {374- inner: ManuallyDrop<Box<ErrorImpl<()>>>,373+ inner: NonNull<ErrorImpl<()>>,374 }375 376+unsafe impl Send for Error {}377+unsafe impl Sync for Error {}378+379 /// Iterator of a chain of source errors.380 ///381 /// This type is the iterator returned by [`Error::chain`].382 ///277 unmodified linesmodified:tests/test_downcast.rs+6 added
66 unmodified lines67 .downcast_mut::<io::Error>()68 .unwrap()69 .to_string(),70 );71+72+ 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 }78 79 #[test]80 fn test_drop() {34 unmodified lines