From cdc82cdbf9419aee3a1810a774b6599cbe8c6674 Mon Sep 17 00:00:00 2001 From: Victoria Fischer Date: Sat, 14 Dec 2024 15:32:25 +0100 Subject: [PATCH] events: reimplement From and To impls with macros --- src/events.rs | 89 +++++++++++++-------------------------------------- 1 file changed, 23 insertions(+), 66 deletions(-) diff --git a/src/events.rs b/src/events.rs index bf51f5e..290f5d2 100644 --- a/src/events.rs +++ b/src/events.rs @@ -16,65 +16,34 @@ pub enum Variant { RGB(Rgb) } -impl From for Variant { - fn from(value: u8) -> Self { - Variant::Byte(value) - } -} - -impl Into for Variant { - fn into(self) -> u8 { - match self { - Variant::Byte(b) => b, - _ => 0 +macro_rules! impl_variant_type { + ($type:ty, $var_type:tt) => { + impl From<$type> for Variant { + fn from(value: $type) -> Self { + Variant::$var_type(value) + } } - } -} -impl From for Variant { - fn from(value: u64) -> Self { - Variant::BigUInt(value) - } -} - -impl Into for Variant { - fn into(self) -> u64 { - match self { - Variant::BigUInt(b) => b, - _ => 0 + impl Into<$type> for Variant { + fn into(self) -> $type { + match self { + Variant::$var_type(value) => value, + _ => panic!("Expected Variant::$var_type, but got {:?}", self) + } + } } - } + }; } -impl From for Variant { - fn from(value: bool) -> Self { - Variant::Boolean(value) - } -} - -impl From for Variant { - fn from(value: i64) -> Self { - Variant::BigInt(value) - } -} - -impl From for Variant { - fn from(value: u32) -> Self { - Variant::UInt(value) - } -} - -impl From for Variant { - fn from(value: i32) -> Self { - Variant::Int(value) - } -} - -impl From for Variant { - fn from(value: String) -> Self { - Variant::String(value) - } -} +impl_variant_type!(u8, Byte); +impl_variant_type!(i8, SignedByte); +impl_variant_type!(u32, UInt); +impl_variant_type!(i32, Int); +impl_variant_type!(i64, BigInt); +impl_variant_type!(u64, BigUInt); +impl_variant_type!(bool, Boolean); +impl_variant_type!(String, String); +impl_variant_type!(Rgb, RGB); impl<'a> From<&'a str> for Variant { fn from(value: &'a str) -> Self { @@ -82,18 +51,6 @@ impl<'a> From<&'a str> for Variant { } } -impl From> for Variant { - fn from(value: Rgb) -> Self { - Variant::RGB(value) - } -} - -impl From for Variant { - fn from(value: i8) -> Self { - Variant::SignedByte(value) - } -} - impl Display for Variant { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self {