UnitEnum Crate Documentation
The unit-enum
crate provides a procedural macro UnitEnum
designed to enhance enums in Rust, particularly those
consisting of unit variants. This macro simplifies working with such enums by providing useful utility methods.
Features
name
: Retrieve the name of an enum variant.ordinal
: Retrieve the ordinal of an enum variant, starting from 0.from_ordinal
: Convert an ordinal back to an enum variant, if possible.discriminant
: Retrieve the discriminant of an enum variant.from_discriminant
: Convert a discriminant back to an enum variant.len
: Get the total number of unit variants in the enum (excluding the "other" variant if present).values
: Returns an iterator over all unit variants of the enum.
Supported Enum Types
The macro supports two types of enums:
- Enums with only unit variants
- Enums with unit variants plus one "other" variant for handling undefined discriminant values
Installation
Add the following to your Cargo.toml
:
[]
= "1.4.1"
Quick Start
Basic Usage (Unit Variants Only)
use UnitEnum;
// Specify the discriminant type (optional, defaults to i32)
Usage with "Other" Variant
use UnitEnum;
// repr attribute is required when using an "other" variant
Discriminant Types
The crate respects the enum's #[repr]
attribute to determine the type of discriminant values. Supported types include:
#[repr(i8)]
,#[repr(i16)]
,#[repr(i32)]
,#[repr(i64)]
,#[repr(i128)]
#[repr(u8)]
,#[repr(u16)]
,#[repr(u32)]
,#[repr(u64)]
,#[repr(u128)]
If no #[repr]
attribute is specified, the discriminant type defaults to i32
. Note that when using an "other" variant, the #[repr]
attribute is required and must match the type of the "other" variant's field.
// Use u8 for discriminants
// Use i64 for large discriminants
Requirements for "Other" Variant
When using an "other" variant, the following requirements must be met:
- The enum must have a
#[repr(type)]
attribute - Only one variant can be marked with
#[unit_enum(other)]
- The "other" variant must have exactly one unnamed field matching the repr type
- All other variants must be unit variants
Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues on our GitHub repository.
License
This project is licensed under either of MIT or Apache-2.0, at your choice.