From 1454cede2f242801d7e40dbf2fde15dbb144db18 Mon Sep 17 00:00:00 2001 From: vpochapuis <75721408+vpochapuis@users.noreply.github.com> Date: Mon, 30 Sep 2024 05:33:54 +0800 Subject: [PATCH] Add EnumDiscriminants Trait and related Macro impl (#377) * Add EnumDiscriminants Trait and related Macro impl * Apply related suggestions from Maintainer: add trait method and rename trait --------- Co-authored-by: vchapuis --- strum/src/lib.rs | 11 ++++++++++- strum_macros/src/macros/enum_discriminants.rs | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/strum/src/lib.rs b/strum/src/lib.rs index 3b5af9cf..90f2d750 100644 --- a/strum/src/lib.rs +++ b/strum/src/lib.rs @@ -217,6 +217,15 @@ pub trait VariantNames { const VARIANTS: &'static [&'static str]; } +/// A trait for retrieving the enum generated by [`EnumDiscriminants`] from an associated +/// Type on the original enumeration. This trait can be autoderived by `strum_macros`. +pub trait IntoDiscriminant { + /// Enum listing the same variants as this enum but without any data fields + type Discriminant; + + fn discriminant(&self) -> Self::Discriminant; +} + /// A trait for retrieving a static array containing all the variants in an Enum. /// This trait can be autoderived by `strum_macros`. For derived usage, all the /// variants in the enumerator need to be unit-types, which means you can't autoderive @@ -248,7 +257,7 @@ DocumentMacroRexports! { AsRefStr, Display, EnumCount, - EnumDiscriminants, + IntoDiscriminant, EnumIter, EnumMessage, EnumProperty, diff --git a/strum_macros/src/macros/enum_discriminants.rs b/strum_macros/src/macros/enum_discriminants.rs index f7d63727..aee4bc63 100644 --- a/strum_macros/src/macros/enum_discriminants.rs +++ b/strum_macros/src/macros/enum_discriminants.rs @@ -22,6 +22,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result { // Derives for the generated enum let type_properties = ast.get_type_properties()?; + let strum_module_path = type_properties.crate_module_path(); let derives = type_properties.discriminant_derives; @@ -165,6 +166,14 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result { #(#discriminants),* } + impl #impl_generics #strum_module_path::IntoDiscriminant for #name #ty_generics #where_clause { + type Discriminant = #discriminants_name; + + fn discriminant(&self) -> Self::Discriminant { + >::from(self) + } + } + #impl_from #impl_from_ref })