Skip to content

Commit

Permalink
Update versions
Browse files Browse the repository at this point in the history
  • Loading branch information
Jasperav committed Sep 25, 2023
1 parent bbfefa3 commit 646fa7d
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 5 deletions.
30 changes: 29 additions & 1 deletion .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "enum_const_value"
version = "0.4.2"
version = "0.4.3"
authors = ["Jasper Visser <[email protected]>"]
edition = "2021"
description = "Providing const values for enums. Unit and enums with associated types are supported. Each variant gets a unique sequential value."
Expand Down
3 changes: 2 additions & 1 deletion example/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use enum_const_value::EnumConstValue;

#[derive(EnumConstValue)]
#[derive(Debug, PartialEq, EnumConstValue)]
enum PlainEnum {
SomeCase,
AnotherCase
Expand Down Expand Up @@ -34,6 +34,7 @@ mod test {

#[test]
fn test_my_enum() {
assert_eq!(PlainEnum::all_values(), [PlainEnum::SomeCase, PlainEnum::AnotherCase]);
assert_eq!(0, PlainEnum::SomeCase.const_value());
assert_eq!(1, PlainEnum::AnotherCase.const_value());
assert_eq!("AnotherCase", PlainEnum::AnotherCase.retrieve_ident());
Expand Down
24 changes: 22 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,27 @@ pub fn enum_const_value(input: proc_macro::TokenStream) -> proc_macro::TokenStre
}
})
.collect::<Vec<_>>();

let mut generate_all_values = !retrieve_ident.is_empty();
let (idents_and_matcher, original_matcher): (Vec<_>, Vec<_>) = enum_data
.into_iter()
.enumerate()
.map(|(index, variant)| {
let index = index as i32;
let variant_name = variant.ident;
let tokens = match variant.fields {
Fields::Unit => quote! {},
Fields::Unit => {
quote! {}
},
Fields::Unnamed(..) => {
generate_const_enum = true;
generate_all_values = false;
quote! {
(..)
}
}
Fields::Named(..) => {
generate_const_enum = true;
generate_all_values = false;
quote! {
{..}
}
Expand All @@ -61,9 +65,25 @@ pub fn enum_const_value(input: proc_macro::TokenStream) -> proc_macro::TokenStre
((variant_name, const_enum_matcher), original_enum_matcher)
})
.unzip();

let (variant_names, const_matcher): (Vec<_>, Vec<_>) = idents_and_matcher.into_iter().unzip();
let tokens_all_values = if generate_all_values {
let number = variant_names.len();
quote! {
pub fn all_values() -> [Self; #number] {
[
#(Self::#variant_names),*
]
}
}
} else {
quote! {}
};

let mut tokens = quote! {
impl #original_enum_type_name {
#tokens_all_values

pub fn retrieve_ident(&self) -> &'static str {
match self {
#(#retrieve_ident),*
Expand Down

0 comments on commit 646fa7d

Please sign in to comment.