Add conversion from Error to Box<dyn StdError + Send + Sync>
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 · parent 04a9f51 · Browse files · 1 file·+99 added−46 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+99 added−46 removed
- other:+99 added−46 removed
Provenance
- Commit
dcaff07- Tree
b2958c7- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
04a9f51
1 file changed+99 added−46 removed
modified:src/error.rs+99 added-46 removed
83 unmodified lines84 object_drop: object_drop::<E>,85 object_drop_front: object_drop_front::<E>,86 object_raw: object_raw::<E>,87 object_mut_raw: object_mut_raw::<E>,88+ object_boxed: object_boxed::<E>,89 };90 let inner = Box::new(ErrorImpl {91 vtable,92 type_id,81 unmodified lines174 ///175 /// [tracking]: https://github.com/rust-lang/rust/issues/53487176 #[cfg(backtrace)]177 pub fn backtrace(&self) -> &Backtrace {177- // NB: this unwrap can only fail if the underlying error's backtrace178- // method is nondeterministic, which would only happen in maliciously179- // constructed code180- self.inner181- .backtrace182- .as_ref()183- .or_else(|| self.inner.error().backtrace())184- .expect("backtrace capture failed")178+ self.inner.backtrace()179 }180 181 /// An iterator of the chain of source errors contained by this Error.182 ///16 unmodified lines199 /// None200 /// }201 /// ```202 pub fn chain(&self) -> Chain {209- Chain {210- next: Some(self.inner.error()),211- }203+ self.inner.chain()204 }205 206 /// The lowest level cause of this error — this error's cause's207 /// cause's cause etc.120 unmodified lines328 }329 }330 331 impl Debug for Error {340- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {341- writeln!(f, "{}", self.inner.error())?;342-343- let mut chain = self.chain().skip(1).enumerate().peekable();344- if let Some((n, error)) = chain.next() {345- write!(f, "\nCaused by:\n ")?;346- if chain.peek().is_some() {347- write!(f, "{}: ", n)?;348- }349- writeln!(f, "{}", error)?;350- for (n, error) in chain {351- writeln!(f, " {}: {}", n, error)?;352- }353- }354-355- #[cfg(backtrace)]356- {357- use std::backtrace::BacktraceStatus;358-359- let backtrace = self.backtrace();360- match backtrace.status() {361- BacktraceStatus::Captured => {362- writeln!(f, "\n{}", backtrace)?;363- }364- BacktraceStatus::Disabled => {365- writeln!(366- f,367- "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"368- )?;369- }370- _ => {}371- }372- }373-374- Ok(())332+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {333+ self.inner.debug(formatter)334 }335 }336 337 impl Display for Error {19 unmodified lines357 object_drop: unsafe fn(Box<ErrorImpl<()>>),358 object_drop_front: unsafe fn(Box<ErrorImpl<()>>),359 object_raw: fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),360 object_mut_raw: fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),361+ object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,362 }363 364 unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {365 // Cast back to ErrorImpl<E> so that the allocator receives the correct23 unmodified lines389 {390 e as *mut E391 }392 393+unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>394+where395+ E: StdError + Send + Sync + 'static,396+{397+ mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)398+}399+400 // repr C to ensure that `E` remains in the final position401 #[repr(C)]402 struct ErrorImpl<E> {403 vtable: &'static ErrorVTable,55 unmodified lines459 460 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {461 unsafe { &mut *(self.vtable.object_mut_raw)(&mut self.error) }462 }463+464+ #[cfg(backtrace)]465+ fn backtrace(&self) -> &Backtrace {466+ // This unwrap can only panic if the underlying error's backtrace method467+ // is nondeterministic, which would only happen in maliciously468+ // constructed code.469+ self.backtrace470+ .as_ref()471+ .or_else(|| self.error().backtrace())472+ .expect("backtrace capture failed")473+ }474+475+ fn chain(&self) -> Chain {476+ Chain {477+ next: Some(self.error()),478+ }479+ }480+481+ fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {482+ writeln!(f, "{}", self.error())?;483+484+ let mut chain = self.chain().skip(1).enumerate().peekable();485+ if let Some((n, error)) = chain.next() {486+ write!(f, "\nCaused by:\n ")?;487+ if chain.peek().is_some() {488+ write!(f, "{}: ", n)?;489+ }490+ writeln!(f, "{}", error)?;491+ for (n, error) in chain {492+ writeln!(f, " {}: {}", n, error)?;493+ }494+ }495+496+ #[cfg(backtrace)]497+ {498+ use std::backtrace::BacktraceStatus;499+500+ let backtrace = self.backtrace();501+ match backtrace.status() {502+ BacktraceStatus::Captured => {503+ writeln!(f, "\n{}", backtrace)?;504+ }505+ BacktraceStatus::Disabled => {506+ writeln!(507+ f,508+ "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"509+ )?;510+ }511+ _ => {}512+ }513+ }514+515+ Ok(())516+ }517 }518 519+impl<E> StdError for ErrorImpl<E> where E: StdError {}520+521+impl<E> Debug for ErrorImpl<E>522+where523+ E: Debug,524+{525+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {526+ let erased = unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) };527+ erased.debug(formatter)528+ }529+}530+531+impl<E> Display for ErrorImpl<E>532+where533+ E: Display,534+{535+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {536+ Display::fmt(&self.error, formatter)537+ }538+}539+540+impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {541+ fn from(error: Error) -> Self {542+ let outer = ManuallyDrop::new(error);543+ unsafe {544+ let inner = ptr::read(&outer.inner);545+ let erased = ManuallyDrop::into_inner(inner);546+ (erased.vtable.object_boxed)(erased)547+ }548+ }549+}550+551 /// Iterator of a chain of source errors.552 ///553 /// This type is the iterator returned by [`Error::chain`].554 ///28 unmodified lines