Expand description
This crate enables attaching metadata to C-like Enums (or strictly any Enum). The metadata can be of an arbitrary type, but must be of the same type for the all variants although can be different values.
This fills the use-case when the Enum variants are flags for something else – for example, HTTP error codes, or parts of a syntax tree associated with some explicit string rendering when concretized.
The crate provides two macros which can be used to add this metadata to the enum. This can be done at a separate location from the declaration of the enum. The first macro is for values that are determined at compile time:
§Syntax
meta! {
EnumType, MetaDataType;
VariantOne, "MetadataValue";
VariantTwo, "MetadataValue";
VariantThree, "MetadataValue";
}
In this case, the type of the metadata must be defined before hand and will be either a reference type or a copy type, as the values will be returned statically. For example:
#[macro_use] extern crate enum_meta;
use enum_meta::*;
enum Colour
{
Red, Orange, Green
}
meta!{
Colour, &'static str;
Red, "Red";
Orange, "Orange";
Green, "Green";
}
fn main() {
assert_eq!(Colour::Orange.meta(), "Orange");
}
A second macro allows the values to be calculated at run time on first access. The values are calculated only once.
#[macro_use] extern crate enum_meta;
use enum_meta::*;
pub enum Colour{
Red,
Orange,
Green
}
lazy_meta!{
Colour, String, META_Colour;
Red, format!("{}:{}", 1, "Red");
Orange, format!("{}:{}", 2, "Orange");
Green, format!("{}:{}", 3, "Green");
}
fn main() {
assert_eq!(Colour::Red.meta(), "1:Red");
}
In this case, values are stored in a global variable whose name is
provided (META_Colour2
in this instance). Values returned are
references to the given return type.
Reverse lookup is now supported indirectly, by providing an all
method which returns all the enum variants as a vector; this allows
construction of a reverse lookup function; this is hard to achieve in
general, requires putting a lot of constraints on the type of the
metadata and can only sensibly support lookup by direct equality with
the metadata.
#[macro_use] extern crate enum_meta;
use enum_meta::*;
// These derives are required by `assert_eq` rather than `lazy_meta`
#[derive(Debug, Eq, PartialEq)]
pub enum Colour{
Red,
Orange,
Green
}
meta!{
Colour, String;
Red, format!("{}:{}", 1, "Red");
Orange, format!("{}:{}", 2, "Orange");
Green, format!("{}:{}", 3, "Green");
}
fn main() {
assert_eq!(Colour::all(),
vec![Colour::Red, Colour::Orange, Colour::Green]);
}
Macros§
Structs§
- Opaque type representing the discriminant of an enum.
- A hash map implemented with quadratic probing and SIMD lookup.
- A synchronization primitive which can nominally be written to only once.
Traits§
- Trait for accessing metadata
Functions§
- Returns a value uniquely identifying the enum variant in
v
.