Skip to content

Commit

Permalink
Improved documentation.
Browse files Browse the repository at this point in the history
  • Loading branch information
JorgeRicoVivas committed Mar 3, 2024
1 parent 6ab0b98 commit 0bc199d
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 113 deletions.
185 changes: 87 additions & 98 deletions README.md
Expand Up @@ -20,7 +20,6 @@ discriminant, inspired by Java's enums.
4 [Assumptions this crate does](#4-assumptions-this-crate-does)<br>

## 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
Expand All @@ -47,20 +46,20 @@ public enum Planet {
}
}
```

<br>
To replicate those mechanics two trais have been created:

* [indexed_valued_enums::indexed_enum::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].<br>
In the example below, Planet::Mars gives discriminant 1, and the
discriminant 1 would give Planet::Mars Back.<br><br>
* [indexed_valued_enums::valued_enum::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.<br>
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.<br>
* [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'.
<br><br>
In the example below, Planet::Mars gives discriminant 1, and the
discriminant 1 would give Planet::Mars Back.<br><br><br>
* [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.<br><br>
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.<br>


```rust
use indexed_valued_enums::{Valued, enum_valued_as};
Expand All @@ -84,37 +83,35 @@ enum Planet {
}

#[test]
fn example_test() {
fn example_test(){
//Identifiers mechanics
assert_eq!(Planet::Mars, Planet::from_discriminant(1));
assert_eq!(Planet::Mercury.discriminant(), 2);

//Value mechanics
assert_eq!(Planet::Earth.value().radius, 6357.0);
assert_eq!(Planet::Mars.gravity, 3.71);
assert_eq!(Planet::Mercury, Planet::value_to_variant(&CelestialBody { radius: 2439.7, gravity: 3.7 }));
assert_eq!(Planet::Mercury, Planet::value_to_variant(&CelestialBody{ radius: 2439.7, gravity: 3.7 }));
}
```

You can implement this on your enums using one of two macros:

* [The declarative macro](#2a1-introductory-example-of-valued-enum-use-via-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.
<br><br>
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.
<br><br>
* [The Derive macro](#2b1-introductory-example-of-valued-enum-use-via-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", ...] }```.
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.

Expand Down Expand Up @@ -149,23 +146,21 @@ fn test() {
&NumberDescription { description: "Third position", index: 3 }));
}
```

## 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!{ <br>
&nbsp;&nbsp;&nbsp;&nbsp; **Your metadata** //Like '#[derive(...)]', this is optional <br>
&nbsp;&nbsp;&nbsp;&nbsp; **##**[features(**Feature1**, **Feature2**, ...)] // this is optional, but it needs **two**
octothorpes<br>
&nbsp;&nbsp;&nbsp;&nbsp; **Visibility** enum **Enum's name** values as **TypeOfValue**; <br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant1's metadata*** //this is optional<br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant1***, ***Value1***,<br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant2's metadata*** //this is optional<br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant2***, ***Value2***,<br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ...<br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ***VariantN's metadata*** //this is optional<br>
&nbsp;&nbsp;&nbsp;&nbsp; ***VariantN***, ***ValueN***<br>
&nbsp;&nbsp;&nbsp;&nbsp; **Your metadata** //Like '#[derive(...)]', this is optional <br>
&nbsp;&nbsp;&nbsp;&nbsp; **##**[features(**Feature1**, **Feature2**, ...)] // this is optional, but it needs **two** octothorpes<br>
&nbsp;&nbsp;&nbsp;&nbsp; **Visibility** enum **Enum's name** values as **TypeOfValue**; <br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant1's metadata*** //this is optional<br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant1***, ***Value1***,<br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant2's metadata*** //this is optional<br>
&nbsp;&nbsp;&nbsp;&nbsp; ***Variant2***, ***Value2***,<br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ...<br><br>
&nbsp;&nbsp;&nbsp;&nbsp; ***VariantN's metadata*** //this is optional<br>
&nbsp;&nbsp;&nbsp;&nbsp; ***VariantN***, ***ValueN***<br>
}

<br>
Expand All @@ -187,7 +182,6 @@ it).
<br>

## 2.a.3 Other examples for the declarative macro

A simple example could look like:

```rust
Expand All @@ -203,7 +197,6 @@ create_indexed_valued_enum! {
Third, "Third position"
}
```

A more complex example could look like:

```rust
Expand All @@ -227,7 +220,6 @@ 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.

Expand All @@ -236,7 +228,7 @@ use indexed_valued_enums::{enum_valued_as, Valued};

#[derive(Eq, PartialEq, Debug, Valued)]
#[enum_valued_as(NumberDescription)]
pub enum Number {
pub enum Number{
#[value(NumberDescription { description: "Zero position", index: 0 })]
Zero,
#[value(NumberDescription { description: "First position", index: 1 })]
Expand Down Expand Up @@ -268,23 +260,23 @@ fn test() {
**IMPORTANT**: To use it, the 'derive' feature should be indicated on your Cargo.toml, like
```indexed_valued_enums = { version = "1.0.0", features=["derive", ...] }```.

**Basic implementation**: Add the derive [indexed_valued_enums::Valued] macro 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: <br><br>
**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:
<br><br>

```rust
use indexed_valued_enums::{Valued, enum_valued_as};

#[derive(Valued)]
#[enum_valued_as(u8)]
pub enum MyEnum {
pub enum MyEnum{
#[value(10)]
Variant1,
#[value(20)]
Variant2,
}
```

<br>

**Add extra functionality**: Below the Derive declaration you can write the attribute
Expand All @@ -301,7 +293,6 @@ pub enum MyEnum{
...
}
```

<br>

**Don't repeat yourself**: For variants whose variants values are often repeated or irrelevant
Expand All @@ -311,15 +302,14 @@ unvalued variants to resolve into said value.<br>
```rust ignore
...
#[unvalued_default(50)]
pub enum MyEnum {
pub enum MyEnum{
/// This variant's value will resolve to 10 as it is specified.
#[value(10)]
Variant1,
/// This variant's value will resolve to the default of 50 as a value it is not specified.
Variant2,
}
```

<br>

**Variant's with fields can be added too!** Unlike the declarative macro, this one is compatible
Expand All @@ -329,12 +319,12 @@ need to create those variants with values at compile, when this situation arises
options:

* Use the #[variant_initialize_uses(*Your default value*)]: 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)]<br><br>
for these variants, for example, if one was ```IP{host: &'static str, port: u16}```, you could
write: #[variant_initialize_uses(host: "localhost", port: 8080)]<br><br>
* If the values on 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].
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].

```rust ignore
...
Expand All @@ -348,19 +338,17 @@ pub enum MyEnum{
Variant2{age:u8},
}
```

<br>

## 2.b.3 Other examples for the derive macro

A simple example could look like this:

```rust
use indexed_valued_enums::{Valued, enum_valued_as};

#[derive(Valued)]
#[enum_valued_as(& 'static str)]
pub enum Number {
#[enum_valued_as(&'static str)]
pub enum Number{
#[value("Zero position")]
Zero,
#[value("First position")]
Expand All @@ -379,10 +367,10 @@ use indexed_valued_enums::{Valued, enum_valued_as};

#[derive(Hash, Ord, PartialOrd, Eq, PartialEq, Debug)]
#[derive(Valued)]
#[enum_valued_as(& 'static str)]
#[enum_valued_as(&'static str)]
#[enum_valued_features(Clone, DerefToValue, Delegators, ValueToVariantDelegators)]
#[unvalued_default("My default string")]
pub enum Number {
pub enum Number{
/// Zero doesn't have a value, so it's value will resolve to "My default string"
Zero,
#[value("First position")]
Expand All @@ -397,53 +385,54 @@ pub enum Number {
/// my_age: 23, my_name: "Jorge"
#[variant_initialize_uses(my_age: 23, my_name: "Jorge")]
#[value("Third position")]
Third { my_age: u8, my_name: &'static str },
Third{my_age: u8, my_name:&'static str},
}
```

## 3 Extra features

* **DerefToValue**: Implements Deref, dereferencing each variant to a static reference of their
value.<br><br>
* **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.<br>Since it calls [discriminant] and then
[from_discriminant], this operation is O(1). <br><br>
value.<br><br>
* **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.<br>Since it calls 'discriminant' and then
'from_discriminant', this operation is O(1). <br><br>
* **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.<br>
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**.<br><br>
[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.<br>
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**.<br><br>
* **ValueToVariantDelegators**: Implements delegator functions calling to
[Valued::value_to_variant] and [Valued::value_to_variant_opt].<br><br>
[Valued::value_to_variant] and [Valued::value_to_variant_opt].<br><br>
* 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.
<br><br>
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"] } ``` <br><br>
The features **NanoSerBin**, **NanoDeBin**, **NanoSerJson** and **NanoDeJson** implements the
nanoserde's traits SerBin, DeBin, SerJson and DeJson respectively.<br><br>
**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.
discriminant value, this is useful when your enum consists on variants without fields.
<br><br>
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"] } ``` <br><br>
The features **NanoSerBin**, **NanoDeBin**, **NanoSerJson** and **NanoDeJson** implements the
nanoserde's traits SerBin, DeBin, SerJson and DeJson respectively.<br><br>
**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 crates name or any of those used in the
[extra features](#3-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```, and ```const-default```.<br><br>
[extra features](#3-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```, and ```const-default```.<br><br>
* 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.<br><br>
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.<br><br>
* 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.<br><br>
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.<br><br>

0 comments on commit 0bc199d

Please sign in to comment.