Skip to content

Commit

Permalink
Add EnumDiscriminants Trait and related Macro impl (#377)
Browse files Browse the repository at this point in the history
* Add EnumDiscriminants Trait and related Macro impl

* Apply related suggestions from Maintainer: add trait method and rename trait

---------

Co-authored-by: vchapuis <vincent.chapuis@fortune.com.tw>
  • Loading branch information
vpochapuis and vchapuis committed Sep 29, 2024
1 parent 6b09049 commit 1454ced
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
11 changes: 10 additions & 1 deletion strum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -248,7 +257,7 @@ DocumentMacroRexports! {
AsRefStr,
Display,
EnumCount,
EnumDiscriminants,
IntoDiscriminant,
EnumIter,
EnumMessage,
EnumProperty,
Expand Down
9 changes: 9 additions & 0 deletions strum_macros/src/macros/enum_discriminants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {

// 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;

Expand Down Expand Up @@ -165,6 +166,14 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
#(#discriminants),*
}

impl #impl_generics #strum_module_path::IntoDiscriminant for #name #ty_generics #where_clause {
type Discriminant = #discriminants_name;

fn discriminant(&self) -> Self::Discriminant {
<Self::Discriminant as ::core::convert::From<&Self>>::from(self)
}
}

#impl_from
#impl_from_ref
})
Expand Down

0 comments on commit 1454ced

Please sign in to comment.