Skip to content
Myr

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

5 files+227 added−112 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(unsafe { crate::ErrorImpl::error(self.error.inner) })146 Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })147 }148}149150struct Quoted<C>(C);
27 unmodified lines
modified:src/error.rs+94 added-103 removed
1use crate::alloc::Box;2use crate::backtrace::Backtrace;3use crate::chain::Chain;4use crate::ptr::{Mut, Own, Ref};5use crate::{Error, StdError};6use core::any::TypeId;7use core::fmt::{self, Debug, Display};8use core::mem::ManuallyDrop;8use core::ptr::{self, NonNull};9use core::ptr::NonNull;1011#[cfg(feature = "std")]12use core::ops::{Deref, DerefMut};13
189 unmodified lines
203 // 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 }210211 /// Wrap the error value with additional context.
97 unmodified lines
309 ///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 }315316 /// An iterator of the chain of source errors contained by this Error.317 ///
18 unmodified lines
336 /// ```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 }342343 /// The lowest level cause of this error &mdash; this error's cause's344 /// cause's cause etc.
21 unmodified lines
366 self.downcast_ref::<E>().is_some()367 }368369 /// 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 };383384 // 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);387388 // 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();390391 // 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);393394 Ok(error)395 }396 }
41 unmodified lines
438 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 }446447 /// Downcast this error object by mutable reference.
4 unmodified lines
452 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 lines
476impl Deref for Error {477 type Target = dyn StdError + Send + Sync + 'static;478479 fn deref(&self) -> &Self::Target {478 unsafe { ErrorImpl::error(self.inner) }480 unsafe { ErrorImpl::error(self.inner.by_ref()) }481 }482}483484#[cfg(feature = "std")]485#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]486impl 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}491492impl 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}497498impl 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}503504impl 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}512513struct 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}523524// Safety: requires layout of *e to match ErrorImpl<E>.523unsafe fn object_drop<E>(e: NonNull<ErrorImpl>) {525unsafe 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}531532// Safety: requires layout of *e to match ErrorImpl<E>.531unsafe fn object_drop_front<E>(e: NonNull<ErrorImpl>, target: TypeId) {533unsafe 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}541542// Safety: requires layout of *e to match ErrorImpl<E>.541unsafe fn object_ref<E>(e: NonNull<ErrorImpl>) -> *const (dyn StdError + Send + Sync + 'static)543unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> &(dyn StdError + Send + Sync + 'static)544where545 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}550551// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived552// from a `&mut`553#[cfg(feature = "std")]552unsafe fn object_mut<E>(e: NonNull<ErrorImpl>) -> *mut (dyn StdError + Send + Sync + 'static)554unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)555where556 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}561562// Safety: requires layout of *e to match ErrorImpl<E>.561unsafe fn object_boxed<E>(e: NonNull<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>563unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>564where565 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}570571// Safety: requires layout of *e to match ErrorImpl<E>.570unsafe fn object_downcast<E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>572unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>573where574 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}585586// Safety: requires layout of *e to match ErrorImpl<E>.586unsafe fn object_downcast_mut<E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>587unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>588where589 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}600601// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.602#[cfg(feature = "std")]603unsafe fn context_downcast<C, E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>603unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>604where605 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}618619// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.620#[cfg(feature = "std")]623unsafe fn context_downcast_mut<C, E>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>621unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>622where623 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}636637// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.638#[cfg(feature = "std")]643unsafe fn context_drop_rest<C, E>(e: NonNull<ErrorImpl>, target: TypeId)639unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)640where641 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}658659// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.662unsafe fn context_chain_downcast<C>(e: NonNull<ErrorImpl>, target: TypeId) -> Option<NonNull<()>>660unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>661where662 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}674675// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.679unsafe fn context_chain_downcast_mut<C>(680 e: NonNull<ErrorImpl>,681 target: TypeId,682) -> Option<NonNull<()>>676unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>677where678 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}690691// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.699unsafe fn context_chain_drop_rest<C>(e: NonNull<ErrorImpl>, target: TypeId)692unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)693where694 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 lines
729// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but730// avoids converting `p` into a reference.731unsafe 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}735736// repr C to ensure that ContextError<C, E> has the same layout as737// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.
3 unmodified lines
741 pub error: E,742}743744impl<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}752753impl 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 }759760 #[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 }766767 #[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 }778788 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 lines
818 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 lines
modified:src/fmt.rs+3 added-3 removed
1use crate::chain::Chain;2use crate::error::ErrorImpl;3use crate::ptr::Ref;4use core::fmt::{self, Debug, Write};4use core::ptr::NonNull;56impl 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))?;910 if f.alternate() {11 for cause in Self::chain(this).skip(1) {
3 unmodified lines
1516 Ok(())17 }1819 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);2122 if f.alternate() {23 return Debug::fmt(error, f);
132 unmodified lines
modified:src/lib.rs+3 added-5 removed
244 unmodified lines
245mod error;246mod fmt;247mod kind;248mod macros;249mod ptr;250mod wrapper;251252use crate::error::ErrorImpl;253use crate::ptr::Own;254use core::fmt::Display;253use core::ptr::NonNull;255256#[cfg(not(feature = "std"))]257use core::fmt::Debug;258
111 unmodified lines
370/// }371/// ```372#[repr(transparent)]373pub struct Error {373 inner: NonNull<ErrorImpl>,374 inner: Own<ErrorImpl>,375}376376unsafe impl Send for Error {}377unsafe impl Sync for Error {}378377/// Iterator of a chain of source errors.378///379/// This type is the iterator returned by [`Error::chain`].380///
277 unmodified lines
added:src/ptr.rs+126 added
1use crate::alloc::Box;2use core::marker::PhantomData;3use core::ptr::NonNull;45#[repr(transparent)]6pub struct Own<T> {7 pub ptr: NonNull<T>,8}910unsafe impl<T> Send for Own<T> {}11unsafe impl<T> Sync for Own<T> {}12impl<T> Copy for Own<T> {}13impl<T> Clone for Own<T> {14 fn clone(&self) -> Self {15 *self16 }17}1819impl<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 }2526 pub fn cast<U>(self) -> Own<U> {27 Own {28 ptr: self.ptr.cast(),29 }30 }3132 pub unsafe fn boxed(self) -> Box<T> {33 Box::from_raw(self.ptr.as_ptr())34 }3536 pub fn by_ref(&self) -> Ref<T> {37 Ref {38 ptr: self.ptr,39 lifetime: PhantomData,40 }41 }4243 pub fn by_mut(&mut self) -> Mut<T> {44 Mut {45 ptr: self.ptr,46 lifetime: PhantomData,47 }48 }49}5051#[repr(transparent)]52pub struct Ref<'a, T> {53 pub ptr: NonNull<T>,54 lifetime: PhantomData<&'a T>,55}5657impl<'a, T> Copy for Ref<'a, T> {}58impl<'a, T> Clone for Ref<'a, T> {59 fn clone(&self) -> Self {60 *self61 }62}6364impl<'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 }7172 pub fn cast<U>(self) -> Ref<'a, U> {73 Ref {74 ptr: self.ptr.cast(),75 lifetime: PhantomData,76 }77 }7879 pub unsafe fn deref(self) -> &'a T {80 &*self.ptr.as_ptr()81 }82}8384#[repr(transparent)]85pub struct Mut<'a, T> {86 pub ptr: NonNull<T>,87 lifetime: PhantomData<&'a mut T>,88}8990impl<'a, T> Copy for Mut<'a, T> {}91impl<'a, T> Clone for Mut<'a, T> {92 fn clone(&self) -> Self {93 *self94 }95}9697impl<'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 }104105 pub fn cast<U>(self) -> Mut<'a, U> {106 Mut {107 ptr: self.ptr.cast(),108 lifetime: PhantomData,109 }110 }111112 pub fn extend<'b>(self) -> Mut<'b, T> {113 Mut {114 ptr: self.ptr,115 lifetime: PhantomData,116 }117 }118119 pub unsafe fn deref_mut(self) -> &'a mut T {120 &mut *self.ptr.as_ptr()121 }122123 pub unsafe fn read(self) -> T {124 self.ptr.as_ptr().read()125 }126}