4 releases
0.2.2 | Oct 25, 2020 |
---|---|
0.2.1 | Oct 17, 2020 |
0.2.0 | Oct 16, 2020 |
0.1.0 | Oct 13, 2020 |
#110 in #enum
1,230 downloads per month
Used in 326 crates
(2 directly)
16KB
203 lines
Enhanced Fieldless Enumerations and Associated Array Types
In Rust, enumerations can contain data fields which is a powerful language feature. However not all enums have data fields. Fieldless enums are simply a list of variants. This crate provides many features for fieldless enums which are difficult or impossible to provide for enums with data fields.
This crate contains a single item: the enhanced_enum!
macro which generates an enum
.
enhanced_enum::enhanced_enum!(YourEnum { A, B, C });
Translates to:
pub enum YourEnum {
A,
B,
C
}
impl YourEnum {
...
}
/// Custom wrapper around an array of length `YourEnum::len()`.
/// This array can only be indexed by `YourEnum`.
pub struct YourEnumArray<T> {
...
}
Features
- Enhanced enums implement many common traits:
Debug
,Display
,Copy
,Clone
,PartialEq
,Eq
,PartialOrd
,Ord
,Hash
-
Iterate through all variants of your enhanced enum with
YourEnum::iter()
. -
Count the number of variants with
YourEnum::count()
orYourEnum::len()
. -
Make an array which can only be indexed by your enum. The
enhanced_enum!
macro generates a wrapper around a standard array, and this custom array type implements a very similar API to a standard array. The name of the new array type is the enum name with the word "Array" appended. -
Convert between integers, strings, and enhanced enums.
YourEnum::try_from(usize)
Also works withu32
and64
.YourEnum::try_from(&str)
Note that the string must exactly match a variant name, or else this returns an error.your_enum as usize
.your_enum.to_string() -> String
your_enum.to_str() -> &'static str
- Interface with Python via the
pyo3
library. Currently this only implements a converting from python strings to rust. This is optionally compiled. To opt-in: build the enhanced_enum crate using the feature flag "pyo3".
Examples
A histogram for counting DNA nucleotides. This re-implements the example from the documentation for the Trait std::ops::Index.
enhanced_enum::enhanced_enum!(Nucleotide {
A,
C,
G,
T,
});
let nucleotide_count = NucleotideArray::<usize>::new_with(|x| match x {
Nucleotide::A => 14,
Nucleotide::C => 9,
Nucleotide::G => 10,
Nucleotide::T => 12
});
assert_eq!(nucleotide_count[Nucleotide::A], 14);
assert_eq!(nucleotide_count[Nucleotide::C], 9);
assert_eq!(nucleotide_count[Nucleotide::G], 10);
assert_eq!(nucleotide_count[Nucleotide::T], 12);