diff options
| author | Botahamec <botahamec@outlook.com> | 2022-10-23 13:07:16 -0400 |
|---|---|---|
| committer | Botahamec <botahamec@outlook.com> | 2022-10-23 13:07:16 -0400 |
| commit | 9d65dee04abb106afa8e374f18094e94658fcf24 (patch) | |
| tree | 065fef978585f9c8bdd0c28111ead5cafea06764 | |
| parent | 6fae1af77dbfc80b986427ad5a06d96565702c38 (diff) | |
Create the UnexpectedError
| -rw-r--r-- | src/unexpected.rs | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/unexpected.rs b/src/unexpected.rs index 4b8f063..18d0a22 100644 --- a/src/unexpected.rs +++ b/src/unexpected.rs @@ -16,6 +16,12 @@ enum ErrorTy { Error(Box<dyn Error + Send + Sync + 'static>), } +/// A wrapper for an error that isn't expected to occur. +/// +/// This implements [`From<T>`] where `T` implements [`Error`], [`Send`], +/// [`Sync`] and `'static` for easy conversion. Because of this, it cannot +/// itself implement [`Error`]. If you need a type that implements [`Error`] +/// but doesn't implement `From<Error>`, use [`UnexpectedError`]. #[derive(Debug)] pub struct RawUnexpected { internal: ErrorTy, @@ -80,3 +86,33 @@ impl RawUnexpected { } } } + +/// An error that isn't expected to occur. +/// +/// This implements [`Error`]. Because of this, it cannot implement +/// `From<Error>`. If that's something you need, try [`RawUnexpected`]. +#[derive(Debug)] +pub struct UnexpectedError(RawUnexpected); + +impl From<RawUnexpected> for UnexpectedError { + fn from(ru: RawUnexpected) -> Self { + Self(ru) + } +} + +impl Display for UnexpectedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&self.0, f) + } +} + +#[cfg(feature = "std")] +impl Error for UnexpectedError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match &self.0.internal { + ErrorTy::Message(_) => None, + #[cfg(feature = "std")] + ErrorTy::Error(e) => Some(&**e), + } + } +} |
