Enum Extension Library
This Rust crate provides procedural
and attribute
macros that enhance Rust enums with additional methods and
conversions. It simplifies working with enums by automatically generating utility methods for common tasks such as
retrieving a list of variants, counting variants, and converting between discriminants and integer types.
See the enum_ext!
and #[enum_extend]
macro examples below for more information.
Both macros generate the same utility methods so you can choose the one that best fits your coding style.
Utility Functions
list()
: Returns an array of all variants in the enum.count()
: Returns the count of variants in the enum.ordinal()
: Returns the ordinal of a variant.iter()
: Returns an iterator over the variants in the enum.from_<IntType>(val)
andto_<IntType>(&self)
, if specified in the attributes.- For example,
from_i32(10)
andas_i32()
ifIntType = "i32"
, orfrom_u32(10)
andas_u32()
ifIntType = "u32"
etc.
- For example,
pascal_spaced(&self)
: Returns the variant name in spaced PascalCase. InQA becomes "In QA".from_pascal_spaced()
: Returns the variant from the spaced PascalCase name. "In QA" becomes InQA.from_ordinal()
: Returns the variant from the ordinal.ref_from_ordinal()
: Returns a reference to the variant from the ordinal.- more to come...
Attributes
Attributes are optional and used to customize the generated methods.
IntType
is currently the only attribute supported and specifies the discriminant type for conversion methods. The generated methods allow conversion from this type to an enum variant and vice versa. Supported types include standard Rust integer types likei32
,u32
,i64
, etc. If this attribute is not specified,usize
is used as the default.- Note: If the enum has discriminant values,
#[derive(Clone)]
is added to the enum (if not already present).
- Note: If the enum has discriminant values,
Assigning attributes vary slightly depending on the macro used.
When using enum_extend
, the attribute is applied directly in the tag:
use enum_extend;
// example with no attribute
// example with an attribute
// <- `IntType` is the discriminant type for conversion methods
When using enum_ext!
, the attribute is applied in an enum_def
parameter to the macro:
use enum_ext;
enum_ext!;
Usage
Using the #[enum_extend]
Attribute Macro
To use the enum_extend attribute macro, simply include it in your Rust project and apply it to your enum definitions. Here's an example:
Using the enum_ext!
Procedural Macro
To use the enum_ext!
macro, simply include it in your Rust project and apply it to your enum definitions. Here's an
example:
Additional utility methods are generated for the enum variants:
use enum_extend;
Getting Started
Add the following to your Cargo.toml file:
[]
= "0.2.0"