Skip to content

Commit

Permalink
WIP: Add an exported macro to impl From for all errors
Browse files Browse the repository at this point in the history
When we use this crate downstream and wish to create a custom error enum
with a variant to hold the general purpose error type we need all the
`From` impls implemented.

Is this too much magic?
  • Loading branch information
tcharding committed Jul 26, 2023
1 parent 5f053b4 commit cd28e09
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,57 @@ use crate::key::error::{
};
use crate::{schnorr, MessageLengthError};

/// Implements `From<E> for $error` for all the specific errors in this crate.
///
/// Requires `$error` to be a an enum with a variant `Secp256k1`.
#[macro_export]
macro_rules! impl_from_for_all_crate_errors_for {
($error:ty) => {
$crate::impl_from_for_all_crate_errors_for!($error, Secp256k1);
};
($error:ty, $variant:ident) => {
impl From<$crate::Error> for $error {
fn from(e: $crate::Error) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::NotEnoughMemoryError> for $error {
fn from(e: $crate::NotEnoughMemoryError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::MessageLengthError> for $error {
fn from(e: $crate::MessageLengthError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::schnorr::SignatureError> for $error {
fn from(e: $crate::schnorr::SignatureError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::ecdsa::SignatureError> for $error {
fn from(e: $crate::ecdsa::SignatureError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::RecoveryIdError> for $error {
fn from(e: $crate::RecoveryIdError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::SecretKeyError> for $error {
fn from(e: $crate::SecretKeyError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::PublicKeyError> for $error {
fn from(e: $crate::PublicKeyError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::PublicKeySumError> for $error {
fn from(e: $crate::PublicKeySumError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::TweakError> for $error {
fn from(e: $crate::TweakError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::ParityValueError> for $error {
fn from(e: $crate::ParityValueError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::XOnlyTweakError> for $error {
fn from(e: $crate::XOnlyTweakError) -> Self { Self::$variant(e.into()) }
}
impl From<$crate::SharedSecretError> for $error {
fn from(e: $crate::SharedSecretError) -> Self { Self::$variant(e.into()) }
}
};
}

/// This is a general purpose error type that can be used to wrap all the errors in this crate.
///
/// Every error types in this crate can be converted (using `?`) to this type. We also support
Expand Down

0 comments on commit cd28e09

Please sign in to comment.