You are reading the documentation for indexed_valued_enums version 1.0.0
Create enums resolving into values and get their variants back through their values or their discriminant, inspired by Java's enums.
1 Motivation and use 2 Creating a valued enum 2.a Via the declarative macro 2.a.1 Introductory example of valued enum use via the declarative macro 2.a.2 How to use the declarative macro 2.a.3 Other examples for the declarative macro 2.a Via the derive macro 2.b.1 Introductory example of valued enum use via the Derive macro 2.b.2 How to use the Derive macro 2.b.3 Other examples for the derive macro 3 Extra features 4 Assumptions this crate does
1 Motivation and use
In a few programming languages it is possible to create enums and associate some information at compile time, for example, Java or C# allow to get a variants identifier, and said variant out of that identifier, it also allows applying a constructor to them, making easy to associate constant values to each variant, allowing to define enums like this one:
- [Indexed] allows you to get a discriminant / index of said variant through the function 'discriminant' and get this variant back using the function 'from_discriminant'. In the example below, Planet::Mars gives discriminant 1, and the discriminant 1 would give Planet::Mars Back.
- [Valued] allows you to associate values to discriminants, giving a function 'value' to return the associated constant with the variant, and 'value_to_variant_opt' to get a possible variant whose constant matches said value. In the example below, Planet::Earth gives a value of CelestialBody{ radius: 6357.0, gravity: 9.807 }, and said value would return Planet::Earth back.
use ;
You can implement this on your enums using one of two macros:
- The declarative macro: On this one you write every variant along it's value, being really easy to write and read, and especially useful when creating simple enums without a lot of manipulation, be them short or large however, in case where you need to directly manipulate your enum, it can be quite restrictive and it doesn't support variants with fields, be them named or unnamed, if you find yourself in any of these two scenarios, use the derive macro instead.
- The Derive macro: On this
one you only need to add a few attributes to your enum and your variants indicating the values,
leaving you to fully control your enum as you please, however, too many variants might produce
hard to read code, in these cases, they are usually large enum without any fields, being a
perfect scenario for the declarative macro instead. It requires you to add the 'derive' feature
on your Cargo.toml, like
indexed_valued_enums = { version = "1.0.0", features=["derive", ...] }.
2.a.1 Introductory example of valued enum use via the declarative macro
This creates a public enum where every Number has an associated value of type NumberDescription, just like in the introductory Derive example.
use create_indexed_valued_enum;
use Indexed;
use Valued;
create_indexed_valued_enum!
2.a.2 How to use the declarative macro
Being a macro by rules, you only need to follow this pattern:
create_indexed_valued_enum!{ Your metadata //Like '#[derive(...)]', this is optional ##[features(Feature1, Feature2, ...)] // this is optional, but it needs two octothorpes Visibility enum Enum's name values as TypeOfValue; Variant1's metadata //this is optional Variant1, Value1, Variant2's metadata //this is optional Variant2, Value2, ... VariantN's metadata //this is optional VariantN, ValueN }
On each of these fields you can indicate different parameters to change the implementation of the enum:
- EnumsName: Name the enum will have.
- TypeOfValue: type of the values the variant's resolve to.
- Pairs of Variant, Value: Name of the variant's to create along to the name they resolve to, the values must be const and have 'static lifetime.
- Features: List of specific implementations you want your enum to use, see the section extra features for more information about this.
Note: You can write metadata (Such as #[derive(...)]) before each pair of Variant, Value, and also before the enum, but it is required that the ##[features(...)] is the last of the enum's declaration metadatas as this is not another metadata (hence the double octothorpe to denote it).
2.a.3 Other examples for the declarative macro
A simple example could look like:
use create_indexed_valued_enum;
create_indexed_valued_enum!
A more complex example could look like:
use create_indexed_valued_enum;
create_indexed_valued_enum!
2.b.1 Introductory example of valued enum use via the Derive macro
This creates a public enum where every Number has an associated value of type NumberDescription, just like in the declarative macro example.
use ;
2.b.2 How to use the Derive macro
This requires 'derive' feature indicated on your Cargo.toml, like:
= { = "1.0.0", =["derive", ...] } ```.
Basic implementation: Add the derive macro [indexed_valued_enums_derive::Valued] and then write the #[enum_valued_as(Value type)] attribute indicating the type your variants will resolve to, then on each variant write an attribute #[value(this variants value)]. this way:
use ;
Add extra functionality: Below the Derive declaration you can write the attribute #[enum_valued_features(Your desired features)] which will automatically implement certain traits or functions which will become helpful, you can check these features on the section extra features.
...
/// Adding 'Delegators' allows to call most of functions at
/// compile-time, being able to get values and variants easily
Don't repeat yourself: For variants whose variants values are often repeated or irrelevant you can use the attribute #[unvalued_default(Your default value)] which will make all these unvalued variants to resolve into said value.
...
Variant's with fields can be added too! Unlike the declarative macro, this one is compatible with variants with fields, be them named or unnamed, but they have a downside: since the [Indexed::from_discriminant] function must return a constant value for each variant, we also need to create those variants with values at compile, when this situation arises you have two options:
- Use the #[variant_initialize_uses(Your default value)] attribute: Here you write the default
contents for these variants, for example, if one was
IP{host: &'static str, port: u16}, you could write: #[variant_initialize_uses(host: "localhost", port: 8080)]. - If the values of the variant implement [const_default::ConstDefault]: You can simply add
const-default in your Cargo.toml like
const-default = { version = "1.0.0" }and when this variant gets resolved from [Indexed::from_discriminant], it will return it with all fields as specified in [const_default::ConstDefault].
...
2.b.3 Other examples for the derive macro
A simple example could look like this:
use ;
A more complex example could look like:
use ;
3 Extra features
- DerefToValue: Implements Deref, dereferencing each variant to a static reference of their value.
- Clone: Implements clone calling 'from_discriminant', avoiding large expansions of the Derive Clone, this however won't clone the fields of your variants if there are some, being rather ideal in the case of large field-less enums.Since it calls 'discriminant' and then 'from_discriminant', this operation is O(1).
- Delegators: Implements const functions equivalent to methods from [Indexed] and [Valued], like 'value(&self)' or 'from_discriminant(&self)', note that these delegator functions are not the same as the ones inside the [Indexed] and [Valued] traits, as these delegators are const functions. Note it doesn't delegate the methods 'value_to_variant' and 'value_to_variant_opt' as they require the type of value to implement [PartialEq], you can delegate these too with the feature ValueToVariantDelegators, but these delegator functions are not const.
- ValueToVariantDelegators: Implements delegator functions calling to [Valued::value_to_variant] and [Valued::value_to_variant_opt].
- De/Serialization features: These allow to serialize and deserialize this enum as just it's
discriminant value, this is useful when your enum consists on variants without fields.
The features Serialize and Deserialize match the Serialize and DeserializeOwned traits,
of serde, to use this, you must add the feature serde_enums on Cargo.toml, like:
indexed_valued_enums = { version = "1.0.0", features=["serde_enums"] }The features NanoSerBin, NanoDeBin, NanoSerJson and NanoDeJson implements the nanoserde's traits SerBin, DeBin, SerJson and DeJson respectively. IMPORTANT: When using these De/Serialization, it will try to implement them over your dependencies, this means indexed_valued_enums won't directly depend on Serde or NanoSerde when implementing these interfaces, so if you want to use the De/Serialization methods of nanoserde, then nanoserde must be a dependency on your Cargo.toml, thanks to this, you always have control over which version of Serde and NanoSerde is being applied.
4 Assumptions this crate does
- You won't rename this crate's name or any of those used in the
extra features, this is because when expanding macros, it will try to
target your dependencies, by doing this, you avoid longer compile times when this crate and
yours use different versions, the dependencies you might need would be:
serde,nanoserde, andconst-default. - The variants of your enum don't have their discriminant manually set-up, this is because values to these variants are stored in an array, where each value is stored in the index corresponding to their variant's position and therefore discriminant, meaning the discriminant as an index.
- The enums are attributed with #[repr(usize)], you don't need to do this manually, the declarative macro does it by itself, and when using the attribute '#[enum_valued_as(Your type)]' it silently adds #[repr(usize)], but if you were to use cargo expand and use the original code, the #[repr(usize)] attribute must remain.