Merge pull request #50 from dtolnay/boxed
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conversion from Box<dyn StdError + Send + Sync> to Error
authored by David Tolnay · committed by GitHub · parents 1a7c075, 9256781 · Browse files · 6 files·+108 added−3 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+108 added−3 removed
- tests:+40 added−0 removed
- other:+68 added−3 removed
Provenance
- Commit
74fbea6- Tree
607d912- Author
David Tolnay <dtolnay@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
1a7c075- Parent 2
9256781
6 files changed+108 added−3 removed
modified:src/error.rs+20 added-1 removed
1 use crate::backtrace::Backtrace;2-use crate::wrapper::{DisplayError, MessageError};2+use crate::wrapper::{BoxedError, DisplayError, MessageError};3 use crate::{Chain, Error};4 use std::any::TypeId;5 use std::error::Error as StdError;6 use std::fmt::{self, Debug, Display};135 unmodified lines142 // Safety: passing vtable that operates on the right type.143 unsafe { Error::construct(error, vtable, backtrace) }144 }145 146+ pub(crate) fn from_boxed(147+ error: Box<dyn StdError + Send + Sync>,148+ backtrace: Option<Backtrace>,149+ ) -> Self {150+ let error = BoxedError(error);151+ let vtable = &ErrorVTable {152+ object_drop: object_drop::<BoxedError>,153+ object_ref: object_ref::<BoxedError>,154+ object_mut: object_mut::<BoxedError>,155+ object_boxed: object_boxed::<BoxedError>,156+ object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,157+ object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,158+ };159+160+ // Safety: BoxedError is repr(transparent) so it is okay for the vtable161+ // to allow casting to Box<dyn StdError + Send + Sync>.162+ unsafe { Error::construct(error, vtable, backtrace) }163+ }164+165 // Takes backtrace as argument rather than capturing it here so that the166 // user sees one fewer layer of wrapping noise in the backtrace.167 //168 // Unsafe because the given vtable must have sensible behavior on the error598 unmodified linesmodified:src/kind.rs+19 added
43 unmodified lines44 // let error = $msg;45 // (&error).anyhow_kind().new(error)46 47 use crate::Error;48+use std::error::Error as StdError;49 use std::fmt::{Debug, Display};50 51 #[cfg(backtrace)]52 use std::backtrace::Backtrace;36 unmodified lines89 {90 error.into()91 }92 }93+94+pub struct Boxed;95+96+pub trait BoxedKind: Sized {97+ #[inline]98+ fn anyhow_kind(&self) -> Boxed {99+ Boxed100+ }101+}102+103+impl BoxedKind for Box<dyn StdError + Send + Sync> {}104+105+impl Boxed {106+ pub fn new(self, error: Box<dyn StdError + Send + Sync>) -> Error {107+ let backtrace = backtrace_if_absent!(error);108+ Error::from_boxed(error, backtrace)109+ }110+}modified:src/lib.rs+1 added-1 removed
520 unmodified lines521 522 #[cfg(backtrace)]523 use std::backtrace::Backtrace;524 525- pub use crate::kind::{AdhocKind, TraitKind};525+ pub use crate::kind::{AdhocKind, BoxedKind, TraitKind};526 527 pub fn new_adhoc<M>(message: M) -> Error528 where529 M: Display + Debug + Send + Sync + 'static,4 unmodified linesmodified:src/macros.rs+1 added-1 removed
152 unmodified lines153 $crate::private::new_adhoc($msg)154 };155 ($err:expr $(,)?) => ({156 #[allow(unused_imports)]157- use $crate::private::{AdhocKind, TraitKind};157+ use $crate::private::{AdhocKind, BoxedKind, TraitKind};158 let error = $err;159 (&error).anyhow_kind().new(error)160 });161 ($fmt:expr, $($arg:tt)*) => {3 unmodified linesmodified:src/wrapper.rs+27 added
1+use crate::backtrace::Backtrace;2 use std::error::Error as StdError;3 use std::fmt::{self, Debug, Display};4 5 #[repr(transparent)]40 unmodified lines46 }47 }48 49 impl<M> StdError for DisplayError<M> where M: Display + 'static {}50+51+#[repr(transparent)]52+pub struct BoxedError(pub Box<dyn StdError + Send + Sync>);53+54+impl Debug for BoxedError {55+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {56+ Debug::fmt(&self.0, f)57+ }58+}59+60+impl Display for BoxedError {61+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {62+ Display::fmt(&self.0, f)63+ }64+}65+66+impl StdError for BoxedError {67+ #[cfg(backtrace)]68+ fn backtrace(&self) -> Option<&Backtrace> {69+ self.0.backtrace()70+ }71+72+ fn source(&self) -> Option<&(dyn StdError + 'static)> {73+ self.0.source()74+ }75+}added:tests/test_boxed.rs+40 added
1+use anyhow::anyhow;2+use std::error::Error as StdError;3+use std::io;4+use thiserror::Error;5+6+#[derive(Error, Debug)]7+#[error("outer")]8+struct MyError {9+ source: io::Error,10+}11+12+#[test]13+fn test_boxed_str() {14+ let error = Box::<dyn StdError + Send + Sync>::from("oh no!");15+ let error = anyhow!(error);16+ assert_eq!("oh no!", error.to_string());17+ assert_eq!(18+ "oh no!",19+ error20+ .downcast_ref::<Box<dyn StdError + Send + Sync>>()21+ .unwrap()22+ .to_string()23+ );24+}25+26+#[test]27+fn test_boxed_thiserror() {28+ let error = MyError {29+ source: io::Error::new(io::ErrorKind::Other, "oh no!"),30+ };31+ let error = anyhow!(error);32+ assert_eq!("oh no!", error.source().unwrap().to_string());33+}34+35+#[test]36+fn test_boxed_anyhow() {37+ let error = anyhow!("oh no!").context("it failed");38+ let error = anyhow!(error);39+ assert_eq!("oh no!", error.source().unwrap().to_string());40+}