Skip to main content

enum_helper/
lib.rs

1//! Yet another enum helper.
2//!
3//! This crate provides derive macros that generate common boilerplate for enums.
4//!
5//! - [`EnumStr`]: convert between enum and string
6//! - [`EnumAll`]: get an array of all variants
7//! - [`EnumKind`]: generate a unit kind enum from a data-carrying enum
8//!
9//! ## Feature flags
10//!
11//! - `derive` (default): re-exports derive macros
12//!
13//! [`EnumStr`]: derive@enum_helper_derive::EnumStr
14//! [`EnumAll`]: derive@enum_helper_derive::EnumAll
15//! [`EnumKind`]: derive@enum_helper_derive::EnumKind
16
17#[cfg(feature = "derive")]
18pub use enum_helper_derive::EnumAll;
19#[cfg(feature = "derive")]
20pub use enum_helper_derive::EnumKind;
21#[cfg(feature = "derive")]
22pub use enum_helper_derive::EnumStr;
23
24/// Convert between enum and string.
25///
26/// Derive this trait on unit enums via [`#[derive(EnumStr)]`](derive@enum_helper_derive::EnumStr).
27pub trait EnumStr: Sized {
28    /// Returns the primary string name of this variant.
29    fn as_name(&self) -> &'static str;
30
31    /// Returns all string names and aliases of this variant.
32    ///
33    /// The first element is always the primary name (returned by [`as_name`](EnumStr::as_name)).
34    /// Subsequent elements are aliases added via `alias_all` and `alias`.
35    fn as_aliases(&self) -> &'static [&'static str];
36}
37
38/// Get an array of all variants of an enum.
39///
40/// Derive this trait on unit enums via [`#[derive(EnumAll)]`](derive@enum_helper_derive::EnumAll).
41pub trait EnumAll: Sized {
42    /// Array type that holds every variant.
43    type All;
44
45    /// An array containing all variants of the enum.
46    const ALL: Self::All;
47}
48
49/// Get the kind of an enum variant.
50///
51/// Derive this trait on enums via [`#[derive(EnumKind)]`](derive@enum_helper_derive::EnumKind).
52pub trait EnumKind: Sized {
53    /// The unit kind enum representing the kinds of this enum.
54    type Kind;
55
56    /// Returns the kind of this variant.
57    fn kind(&self) -> Self::Kind;
58}