Skip to content
Myr

Merge pull request #12 from dtolnay/boxed

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

Add conversion from Error to Box<dyn StdError + Send + Sync>

authored by David Tolnay · committed by GitHub · parents 04a9f51, dcaff07 · 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

1 file+99 added−46 removed

modified:src/error.rs+99 added-46 removed
83 unmodified lines
84 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 lines
174 ///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 }180181 /// An iterator of the chain of source errors contained by this Error.182 ///
16 unmodified lines
199 /// None200 /// }201 /// ```202 pub fn chain(&self) -> Chain {209 Chain {210 next: Some(self.inner.error()),211 }203 self.inner.chain()204 }205206 /// The lowest level cause of this error &mdash; this error's cause's207 /// cause's cause etc.
120 unmodified lines
328 }329}330331impl Debug for Error {340 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {341 writeln!(f, "{}", self.inner.error())?;342343 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 }354355 #[cfg(backtrace)]356 {357 use std::backtrace::BacktraceStatus;358359 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 }373374 Ok(())332 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {333 self.inner.debug(formatter)334 }335}336337impl Display for Error {
19 unmodified lines
357 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}363364unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {365 // Cast back to ErrorImpl<E> so that the allocator receives the correct
23 unmodified lines
389{390 e as *mut E391}392393unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>394where395 E: StdError + Send + Sync + 'static,396{397 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)398}399400// repr C to ensure that `E` remains in the final position401#[repr(C)]402struct ErrorImpl<E> {403 vtable: &'static ErrorVTable,
55 unmodified lines
459460 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {461 unsafe { &mut *(self.vtable.object_mut_raw)(&mut self.error) }462 }463464 #[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 }474475 fn chain(&self) -> Chain {476 Chain {477 next: Some(self.error()),478 }479 }480481 fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {482 writeln!(f, "{}", self.error())?;483484 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 }495496 #[cfg(backtrace)]497 {498 use std::backtrace::BacktraceStatus;499500 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 }514515 Ok(())516 }517}518519impl<E> StdError for ErrorImpl<E> where E: StdError {}520521impl<E> Debug for ErrorImpl<E>522where523 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}530531impl<E> Display for ErrorImpl<E>532where533 E: Display,534{535 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {536 Display::fmt(&self.error, formatter)537 }538}539540impl 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}550551/// Iterator of a chain of source errors.552///553/// This type is the iterator returned by [`Error::chain`].554///
28 unmodified lines