Adopt some NonNull wrappers
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This makes clear the ownership properties of all the NonNull pointers in the vtable signatures.
authored by David Tolnay · committed by David Tolnay · parent d1b0c9a · Browse files · 5 files·+227 added−112 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+227 added−112 removed
- other:+227 added−112 removed
Provenance
- Commit
62673e2- Tree
7d93b10- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
d1b0c9a
5 files changed+227 added−112 removed
modified: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(unsafe { crate::ErrorImpl::error(self.error.inner) })146+ Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })147 }148 }149 150 struct Quoted<C>(C);27 unmodified linesmodified:src/error.rs+94 added-103 removed
1 use crate::alloc::Box;2 use crate::backtrace::Backtrace;3 use crate::chain::Chain;4+use crate::ptr::{Mut, Own, Ref};5 use crate::{Error, StdError};6 use core::any::TypeId;7 use core::fmt::{self, Debug, Display};8 use core::mem::ManuallyDrop;8-use core::ptr::{self, NonNull};9+use core::ptr::NonNull;10 11 #[cfg(feature = "std")]12 use core::ops::{Deref, DerefMut};13 189 unmodified lines203 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the204 // result is a thin pointer. The necessary behavior for manipulating the205 // underlying ErrorImpl<E> is preserved in the vtable provided by the206 // caller rather than a builtin fat pointer vtable.206- let inner = NonNull::new_unchecked(Box::into_raw(inner) as *mut ErrorImpl);207+ let inner = Own::new(inner).cast::<ErrorImpl>();208 Error { inner }209 }210 211 /// Wrap the error value with additional context.97 unmodified lines309 ///310 /// [tracking]: https://github.com/rust-lang/rust/issues/53487311 #[cfg(backtrace)]312 pub fn backtrace(&self) -> &Backtrace {312- unsafe { ErrorImpl::backtrace(self.inner) }313+ unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }314 }315 316 /// An iterator of the chain of source errors contained by this Error.317 ///18 unmodified lines336 /// ```337 #[cfg(feature = "std")]338 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]339 pub fn chain(&self) -> Chain {339- unsafe { ErrorImpl::chain(self.inner) }340+ unsafe { ErrorImpl::chain(self.inner.by_ref()) }341 }342 343 /// The lowest level cause of this error — this error's cause's344 /// cause's cause etc.21 unmodified lines366 self.downcast_ref::<E>().is_some()367 }368 369 /// Attempt to downcast the error object to a concrete type.369- pub fn downcast<E>(self) -> Result<E, Self>370+ pub fn downcast<E>(mut self) -> Result<E, Self>371 where372 E: Display + Debug + Send + Sync + 'static,373 {374 let target = TypeId::of::<E>();375 unsafe {376 // Use vtable to find NonNull<()> which points to a value of type E377 // somewhere inside the data structure.378+ let addr =377- let addr = match (vtable(self.inner).object_downcast_mut)(self.inner, target) {378- Some(addr) => addr,379- None => return Err(self),380- };379+ match (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target) {380+ Some(addr) => addr.extend(),381+ None => return Err(self),382+ };383 384 // Prepare to read E out of the data structure. We'll drop the rest385 // of the data structure separately so that E is not dropped.386 let outer = ManuallyDrop::new(self);387 388 // Read E from where the vtable found it.387- let error = ptr::read(addr.cast::<E>().as_ptr());389+ let error = addr.cast::<E>().read();390 391 // Drop rest of the data structure outside of E.390- (vtable(outer.inner).object_drop_rest)(outer.inner, target);392+ (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);393 394 Ok(error)395 }396 }41 unmodified lines438 let target = TypeId::of::<E>();439 unsafe {440 // Use vtable to find NonNull<()> which points to a value of type E441 // somewhere inside the data structure.440- let addr = (vtable(self.inner).object_downcast)(self.inner, target)?;441- Some(&*addr.cast::<E>().as_ptr())442+ let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;443+ Some(addr.cast::<E>().deref())444 }445 }446 447 /// Downcast this error object by mutable reference.4 unmodified lines452 let target = TypeId::of::<E>();453 unsafe {454 // Use vtable to find NonNull<()> which points to a value of type E455 // somewhere inside the data structure.454- let addr = (vtable(self.inner).object_downcast_mut)(self.inner, target)?;455- Some(&mut *addr.cast::<E>().as_ptr())456+ let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;457+ Some(addr.cast::<E>().deref_mut())458 }459 }460 }461 14 unmodified lines476 impl Deref for Error {477 type Target = dyn StdError + Send + Sync + 'static;478 479 fn deref(&self) -> &Self::Target {478- unsafe { ErrorImpl::error(self.inner) }480+ unsafe { ErrorImpl::error(self.inner.by_ref()) }481 }482 }483 484 #[cfg(feature = "std")]485 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]486 impl DerefMut for Error {487 fn deref_mut(&mut self) -> &mut Self::Target {486- unsafe { ErrorImpl::error_mut(self.inner) }488+ unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }489 }490 }491 492 impl Display for Error {493 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {492- unsafe { ErrorImpl::display(self.inner, formatter) }494+ unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }495 }496 }497 498 impl Debug for Error {499 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {498- unsafe { ErrorImpl::debug(self.inner, formatter) }500+ unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }501 }502 }503 504 impl Drop for Error {505 fn drop(&mut self) {506 unsafe {507 // Invoke the vtable's drop behavior.506- (vtable(self.inner).object_drop)(self.inner);508+ (vtable(self.inner.ptr).object_drop)(self.inner);509 }510 }511 }512 513 struct ErrorVTable {512- object_drop: unsafe fn(NonNull<ErrorImpl>),513- object_ref: unsafe fn(NonNull<ErrorImpl>) -> *const (dyn StdError + Send + Sync + 'static),514+ object_drop: unsafe fn(Own<ErrorImpl>),515+ object_ref: unsafe fn(Ref<ErrorImpl>) -> &(dyn StdError + Send + Sync + 'static),516 #[cfg(feature = "std")]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),517+ object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),518+ object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,519+ object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,520+ object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,521+ object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),522 }523 524 // Safety: requires layout of *e to match ErrorImpl<E>.523-unsafe fn object_drop<E>(e: NonNull<ErrorImpl>) {525+unsafe fn object_drop<E>(e: Own<ErrorImpl>) {526 // Cast back to ErrorImpl<E> so that the allocator receives the correct527 // Layout to deallocate the Box's memory.526- let unerased = Box::from_raw(e.as_ptr() as *mut ErrorImpl<E>);528+ let unerased = e.cast::<ErrorImpl<E>>().boxed();529 drop(unerased);530 }531 532 // Safety: requires layout of *e to match ErrorImpl<E>.531-unsafe fn object_drop_front<E>(e: NonNull<ErrorImpl>, target: TypeId) {533+unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {534 // Drop the fields of ErrorImpl other than E as well as the Box allocation,535 // without dropping E itself. This is used by downcast after doing a536 // ptr::read to take ownership of the E.537 let _ = target;536- let unerased = Box::from_raw(e.as_ptr() as *mut ErrorImpl<ManuallyDrop<E>>);538+ let unerased = e.cast::<ErrorImpl<ManuallyDrop<E>>>().boxed();539 drop(unerased);540 }541 542 // Safety: requires layout of *e to match ErrorImpl<E>.541-unsafe fn object_ref<E>(e: NonNull<ErrorImpl>) -> *const (dyn StdError + Send + Sync + 'static)543+unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> &(dyn StdError + Send + Sync + 'static)544 where545 E: StdError + Send + Sync + 'static,546 {547 // Attach E's native StdError vtable onto a pointer to self._object.546- &(*(e.as_ptr() as *const ErrorImpl<E>))._object548+ &e.cast::<ErrorImpl<E>>().deref()._object549 }550 551 // Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived552 // from a `&mut`553 #[cfg(feature = "std")]552-unsafe fn object_mut<E>(e: NonNull<ErrorImpl>) -> *mut (dyn StdError + Send + Sync + 'static)554+unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)555 where556 E: StdError + Send + Sync + 'static,557 {558 // Attach E's native StdError vtable onto a pointer to self._object.557- &mut (*(e.as_ptr() as *mut ErrorImpl<E>))._object559+ &mut e.cast::<ErrorImpl<E>>().deref_mut()._object560 }561 562 // Safety: requires layout of *e to match ErrorImpl<E>.561-unsafe fn object_boxed<E>(e: NonNull<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>563+unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>564 where565 E: StdError + Send + Sync + 'static,566 {567 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.566- Box::<ErrorImpl<E>>::from_raw(e.as_ptr() as *mut ErrorImpl<E>)568+ e.cast::<ErrorImpl<E>>().boxed()569 }570 571 // Safety: requires layout of *e to match ErrorImpl<E>.570-unsafe fn object_downcast<E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>572+unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>573 where574 E: 'static,575 {576 if TypeId::of::<E>() == target {577 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a578 // pointer to its E field.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))579+ let unerased = e.cast::<ErrorImpl<E>>().deref();580+ Some(Ref::new(&unerased._object).cast::<()>())581 } else {582 None583 }584 }585 586 // Safety: requires layout of *e to match ErrorImpl<E>.586-unsafe fn object_downcast_mut<E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>587+unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>588 where589 E: 'static,590 {591 if TypeId::of::<E>() == target {592 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a593 // 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))594+ let unerased = e.cast::<ErrorImpl<E>>().deref_mut();595+ Some(Mut::new(&mut unerased._object).cast::<()>())596 } else {597 None598 }599 }600 601 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.602 #[cfg(feature = "std")]603-unsafe fn context_downcast<C, E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>603+unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>604 where605 C: 'static,606 E: 'static,607 {608 if TypeId::of::<C>() == target {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))609+ let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();610+ Some(Ref::new(&unerased._object.context).cast::<()>())611 } else if TypeId::of::<E>() == target {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))612+ let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();613+ Some(Ref::new(&unerased._object.error).cast::<()>())614 } else {615 None616 }617 }618 619 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.620 #[cfg(feature = "std")]623-unsafe fn context_downcast_mut<C, E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>621+unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>622 where623 C: 'static,624 E: 'static,625 {626 if TypeId::of::<C>() == target {629- let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, E>>;630- let addr = &mut (*unerased)._object.context as *mut C as *mut ();631- Some(NonNull::new_unchecked(addr))627+ let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();628+ Some(Mut::new(&mut unerased._object.context).cast::<()>())629 } else if TypeId::of::<E>() == target {633- let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, E>>;634- let addr = &mut (*unerased)._object.error as *mut E as *mut ();635- Some(NonNull::new_unchecked(addr))630+ let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();631+ Some(Mut::new(&mut unerased._object.error).cast::<()>())632 } else {633 None634 }635 }636 637 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.638 #[cfg(feature = "std")]643-unsafe fn context_drop_rest<C, E>(e: NonNull<ErrorImpl>, target: TypeId)639+unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)640 where641 C: 'static,642 E: 'static,643 {644 // Called after downcasting by value to either the C or the E and doing a645 // ptr::read to take ownership of that value.646 if TypeId::of::<C>() == target {651- let unerased =652- Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<ManuallyDrop<C>, E>>);647+ let unerased = e648+ .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>()649+ .boxed();650 drop(unerased);651 } else {655- let unerased =656- Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<C, ManuallyDrop<E>>>);652+ let unerased = e653+ .cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>()654+ .boxed();655 drop(unerased);656 }657 }658 659 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.662-unsafe fn context_chain_downcast<C>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>660+unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>661 where662 C: 'static,663 {664 if TypeId::of::<C>() == target {667- let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, Error>>;668- let addr = &(*unerased)._object.context as *const C as *mut ();669- Some(NonNull::new_unchecked(addr))665+ let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();666+ Some(Ref::new(&unerased._object.context).cast::<()>())667 } else {668 // Recurse down the context chain per the inner error's vtable.672- let unerased = e.as_ptr() as *const ErrorImpl<ContextError<C, Error>>;673- let source = &(*unerased)._object.error;674- (vtable(source.inner).object_downcast)(source.inner, target)669+ let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();670+ let source = &unerased._object.error;671+ (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target)672 }673 }674 675 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.679-unsafe fn context_chain_downcast_mut<C>(680- e: NonNull<ErrorImpl>,681- target: TypeId,682-) -> Option<NonNull<()>>676+unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>677 where678 C: 'static,679 {680 if TypeId::of::<C>() == target {687- let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, Error>>;688- let addr = &mut (*unerased)._object.context as *mut C as *mut ();689- Some(NonNull::new_unchecked(addr))681+ let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref_mut();682+ Some(Mut::new(&mut unerased._object.context).cast::<()>())683 } else {684 // Recurse down the context chain per the inner error's vtable.692- let unerased = e.as_ptr() as *mut ErrorImpl<ContextError<C, Error>>;693- let source = &mut (*unerased)._object.error;694- (vtable(source.inner).object_downcast_mut)(source.inner, target)685+ let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref_mut();686+ let source = &mut unerased._object.error;687+ (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target)688 }689 }690 691 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.699-unsafe fn context_chain_drop_rest<C>(e: NonNull<ErrorImpl>, target: TypeId)692+unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)693 where694 C: 'static,695 {696 // Called after downcasting by value to either the C or one of the causes697 // and doing a ptr::read to take ownership of that value.698 if TypeId::of::<C>() == target {706- let unerased =707- Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<ManuallyDrop<C>, Error>>);699+ let unerased = e700+ .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>()701+ .boxed();702 // Drop the entire rest of the data structure rooted in the next Error.703 drop(unerased);704 } else {711- let unerased =712- Box::from_raw(e.as_ptr() as *mut ErrorImpl<ContextError<C, ManuallyDrop<Error>>>);713- // Read the NonNull<ErrorImpl> from the next error.705+ let unerased = e706+ .cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>()707+ .boxed();708+ // Read the Own<ErrorImpl> from the next error.709 let inner = unerased._object.error.inner;710 drop(unerased);716- let vtable = inner.as_ref().vtable;711+ let vtable = vtable(inner.ptr);712 // Recursively drop the next error using the same target typeid.713 (vtable.object_drop_rest)(inner, target);714 }715 }13 unmodified lines729 // Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but730 // avoids converting `p` into a reference.731 unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {732 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.738- (p.as_ptr() as *const &'static ErrorVTable).read()733+ *p.as_ptr().cast::<&'static ErrorVTable>()734 }735 736 // repr C to ensure that ContextError<C, E> has the same layout as737 // ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.3 unmodified lines741 pub error: E,742 }743 744 impl<E> ErrorImpl<E> {750- fn erase(&self) -> NonNull<ErrorImpl> {745+ fn erase(&self) -> Ref<ErrorImpl> {746 // Erase the concrete type of E but preserve the vtable in self.vtable747 // for manipulating the resulting thin pointer. This is analogous to an748 // unsize coercion.754- NonNull::from(self).cast::<ErrorImpl>()749+ Ref::new(self).cast::<ErrorImpl>()750 }751 }752 753 impl ErrorImpl {759- pub(crate) unsafe fn error<'a>(760- this: NonNull<Self>,761- ) -> &'a (dyn StdError + Send + Sync + 'static) {754+ pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {755 // Use vtable to attach E's native StdError vtable for the right756 // original type E.764- &*(vtable(this).object_ref)(this)757+ (vtable(this.ptr).object_ref)(this)758 }759 760 #[cfg(feature = "std")]768- pub(crate) unsafe fn error_mut<'a>(769- this: NonNull<Self>,770- ) -> &'a mut (dyn StdError + Send + Sync + 'static) {761+ pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {762 // Use vtable to attach E's native StdError vtable for the right763 // original type E.773- &mut *(vtable(this).object_mut)(this)764+ (vtable(this.ptr).object_mut)(this)765 }766 767 #[cfg(backtrace)]777- pub(crate) unsafe fn backtrace<'a>(this: NonNull<Self>) -> &'a Backtrace {768+ pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {769 // This unwrap can only panic if the underlying error's backtrace method770 // is nondeterministic, which would only happen in maliciously771 // constructed code.781- (*this.as_ptr())772+ this.deref()773 .backtrace774 .as_ref()775 .or_else(|| Self::error(this).backtrace())776 .expect("backtrace capture failed")777 }778 788- pub(crate) unsafe fn chain<'a>(this: NonNull<Self>) -> Chain<'a> {779+ pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {780 Chain::new(Self::error(this))781 }782 }783 34 unmodified lines818 let outer = ManuallyDrop::new(error);819 unsafe {820 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for821 // the right original type E.831- (vtable(outer.inner).object_boxed)(outer.inner)822+ (vtable(outer.inner.ptr).object_boxed)(outer.inner)823 }824 }825 }826 25 unmodified linesmodified:src/fmt.rs+3 added-3 removed
1 use crate::chain::Chain;2 use crate::error::ErrorImpl;3+use crate::ptr::Ref;4 use core::fmt::{self, Debug, Write};4-use core::ptr::NonNull;5 6 impl ErrorImpl {7- pub(crate) unsafe fn display(this: NonNull<Self>, f: &mut fmt::Formatter) -> fmt::Result {7+ pub(crate) unsafe fn display(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {8 write!(f, "{}", Self::error(this))?;9 10 if f.alternate() {11 for cause in Self::chain(this).skip(1) {3 unmodified lines15 16 Ok(())17 }18 19- pub(crate) unsafe fn debug(this: NonNull<Self>, f: &mut fmt::Formatter) -> fmt::Result {19+ pub(crate) unsafe fn debug(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {20 let error = Self::error(this);21 22 if f.alternate() {23 return Debug::fmt(error, f);132 unmodified linesmodified:src/lib.rs+3 added-5 removed
244 unmodified lines245 mod error;246 mod fmt;247 mod kind;248 mod macros;249+mod ptr;250 mod wrapper;251 252 use crate::error::ErrorImpl;253+use crate::ptr::Own;254 use core::fmt::Display;253-use core::ptr::NonNull;255 256 #[cfg(not(feature = "std"))]257 use core::fmt::Debug;258 111 unmodified lines370 /// }371 /// ```372 #[repr(transparent)]373 pub struct Error {373- inner: NonNull<ErrorImpl>,374+ inner: Own<ErrorImpl>,375 }376 376-unsafe impl Send for Error {}377-unsafe impl Sync for Error {}378-377 /// Iterator of a chain of source errors.378 ///379 /// This type is the iterator returned by [`Error::chain`].380 ///277 unmodified linesadded:src/ptr.rs+126 added
1+use crate::alloc::Box;2+use core::marker::PhantomData;3+use core::ptr::NonNull;4+5+#[repr(transparent)]6+pub struct Own<T> {7+ pub ptr: NonNull<T>,8+}9+10+unsafe impl<T> Send for Own<T> {}11+unsafe impl<T> Sync for Own<T> {}12+impl<T> Copy for Own<T> {}13+impl<T> Clone for Own<T> {14+ fn clone(&self) -> Self {15+ *self16+ }17+}18+19+impl<T> Own<T> {20+ pub fn new(ptr: Box<T>) -> Self {21+ Own {22+ ptr: unsafe { NonNull::new_unchecked(Box::into_raw(ptr)) },23+ }24+ }25+26+ pub fn cast<U>(self) -> Own<U> {27+ Own {28+ ptr: self.ptr.cast(),29+ }30+ }31+32+ pub unsafe fn boxed(self) -> Box<T> {33+ Box::from_raw(self.ptr.as_ptr())34+ }35+36+ pub fn by_ref(&self) -> Ref<T> {37+ Ref {38+ ptr: self.ptr,39+ lifetime: PhantomData,40+ }41+ }42+43+ pub fn by_mut(&mut self) -> Mut<T> {44+ Mut {45+ ptr: self.ptr,46+ lifetime: PhantomData,47+ }48+ }49+}50+51+#[repr(transparent)]52+pub struct Ref<'a, T> {53+ pub ptr: NonNull<T>,54+ lifetime: PhantomData<&'a T>,55+}56+57+impl<'a, T> Copy for Ref<'a, T> {}58+impl<'a, T> Clone for Ref<'a, T> {59+ fn clone(&self) -> Self {60+ *self61+ }62+}63+64+impl<'a, T> Ref<'a, T> {65+ pub fn new(ptr: &'a T) -> Self {66+ Ref {67+ ptr: NonNull::from(ptr),68+ lifetime: PhantomData,69+ }70+ }71+72+ pub fn cast<U>(self) -> Ref<'a, U> {73+ Ref {74+ ptr: self.ptr.cast(),75+ lifetime: PhantomData,76+ }77+ }78+79+ pub unsafe fn deref(self) -> &'a T {80+ &*self.ptr.as_ptr()81+ }82+}83+84+#[repr(transparent)]85+pub struct Mut<'a, T> {86+ pub ptr: NonNull<T>,87+ lifetime: PhantomData<&'a mut T>,88+}89+90+impl<'a, T> Copy for Mut<'a, T> {}91+impl<'a, T> Clone for Mut<'a, T> {92+ fn clone(&self) -> Self {93+ *self94+ }95+}96+97+impl<'a, T> Mut<'a, T> {98+ pub fn new(ptr: &'a mut T) -> Self {99+ Mut {100+ ptr: NonNull::from(ptr),101+ lifetime: PhantomData,102+ }103+ }104+105+ pub fn cast<U>(self) -> Mut<'a, U> {106+ Mut {107+ ptr: self.ptr.cast(),108+ lifetime: PhantomData,109+ }110+ }111+112+ pub fn extend<'b>(self) -> Mut<'b, T> {113+ Mut {114+ ptr: self.ptr,115+ lifetime: PhantomData,116+ }117+ }118+119+ pub unsafe fn deref_mut(self) -> &'a mut T {120+ &mut *self.ptr.as_ptr()121+ }122+123+ pub unsafe fn read(self) -> T {124+ self.ptr.as_ptr().read()125+ }126+}