Skip to content

Commit

Permalink
Every item is now documented.
Browse files Browse the repository at this point in the history
  • Loading branch information
JorgeRicoVivas committed Mar 2, 2024
1 parent d6192c0 commit 95ef9b4
Show file tree
Hide file tree
Showing 5 changed files with 264 additions and 93 deletions.
162 changes: 87 additions & 75 deletions README.md
@@ -1,12 +1,13 @@
![crates.io](https://img.shields.io/crates/v/indexed_valued_enums.svg)
![Crates.io License](https://img.shields.io/crates/l/indexed_valued_enums)
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/JorgeRicoVivas/indexed_valued_enums/rust.yml)
![docs.rs](https://img.shields.io/docsrs/indexed_valued_enums)
![GitHub License](https://img.shields.io/github/license/JorgeRicoVivas/indexed_valued_enums)

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](#1-motivation-and-use)<br>
2 [Creating a valued enum](#2-example-of-valued-enum-use-via-the-declarative-macro)<br>
2 [Creating a valued enum](#2a1-introductory-example-of-valued-enum-use-via-the-declarative-macro)<br>
&nbsp;&nbsp;&nbsp;&nbsp;2.a Via the declarative macro<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.a.1 [Introductory example of valued enum use via the declarative macro](#2a1-introductory-example-of-valued-enum-use-via-the-declarative-macro)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.a.2 [How to use the declarative macro](#2a2-how-to-use-the-declarative-macro)<br>
Expand All @@ -25,13 +26,13 @@ out of that identifier, it also allows applying a constructor to them, making ea
constant values to each variant, allowing to define enums like this one:

```java
public enum Planets {
public enum Planet {
Earth(6357.0, 9.807), Mars(3389.5, 3.71), Mercury(2439.7, 3.7);

private Double radius;
private Double gravity;

Planets(Double radius, Double gravity) {
Planet(Double radius, Double gravity) {
this.radius = radius;
this.gravity = gravity;
}
Expand All @@ -46,62 +47,68 @@ public enum Planets {
}
```
<br>
To replicate those mechanics two traits have been created:
To replicate those mechanics two trais have been created:

* [indexed_valued_enums::indexed_enum::Indexed] Allows to get a discriminant / index for a variant through the function
[discriminant], and get said 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, in the example below, Planet::Earth gives a value of Planet{ radius: 6357.0, gravity: 9.807 }, and
said value would return Planet::Earth back.<br>
* [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>


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

#[derive(PartialEq)]
pub struct Planet {
pub struct CelestialBody {
radius: f32,
gravity: f32,
}

#[derive(PartialEq, Debug, Valued)]
#[enum_valued_as(Planet)]
#[enum_valued_as(CelestialBody)]
#[enum_valued_features(DerefToValue, Delegators, ValueToVariantDelegators)]
enum Planets {
#[value(Planet{ radius: 6357.0, gravity: 9.807 })]
enum Planet {
#[value(CelestialBody{ radius: 6357.0, gravity: 9.807 })]
Earth,
#[value(Planet{ radius: 3389.5, gravity: 3.71 })]
#[value(CelestialBody{ radius: 3389.5, gravity: 3.71 })]
Mars,
#[value(Planet{ radius: 2439.7, gravity: 3.7 })]
#[value(CelestialBody{ radius: 2439.7, gravity: 3.7 })]
Mercury,
}

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

//Value mechanics
assert_eq!(Planets::Earth.value().radius, 6357.0);
assert_eq!(Planets::Mars.gravity, 3.71);
assert_eq!(Planets::Mercury, Planets::value_to_variant(&Planet{ radius: 2439.7, gravity: 3.7 }));
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 }));
}
```

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>
* [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 perfect for the declarative macro instead.
It requires you to add the 'derive' feature on your Cargo.toml, like
* [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>
* [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", ...] }```.

## 2.a.1 Introductory example of valued enum use via the declarative macro
Expand Down Expand Up @@ -158,19 +165,20 @@ create_indexed_valued_enum!{ <br>

<br>

On each of these fields you can indicate different parameters to change the implementation of the
enum:
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](#extra-features) for more information about this.
[extra features](#3-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).
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).
<br>

## 2.a.3 Other examples for the declarative macro
Expand All @@ -191,7 +199,7 @@ create_indexed_valued_enum! {
```
A more complex example could look like:

```rust ignore
```rust
use indexed_valued_enums::create_indexed_valued_enum;

create_indexed_valued_enum! {
Expand All @@ -200,9 +208,7 @@ create_indexed_valued_enum! {
#[derive(Hash, Ord, PartialOrd, Eq, PartialEq, Debug)]
//Gives a list of features that are decomposed functions for specific behaviours, you have
//more details about them down below
###[features(Clone, DerefToValue, Delegators, ValueToVariantDelegators,
Serialize, Deserialize,
NanoDeBin, NanoSerBin, NanoDeJson, NanoSerJson)]
###[features(Clone, DerefToValue, Delegators, ValueToVariantDelegators)]
//Defines the enum and the value type it resolves to
pub enum MyOtherNumber valued as &'static str;
//Defines every variant and their value, note that values must be const
Expand All @@ -217,7 +223,7 @@ create_indexed_valued_enum! {
This creates a public enum where every Number has an associated value of type NumberDescription,
just like in the declarative macro example.

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

#[derive(Eq, PartialEq, Debug, Valued)]
Expand Down Expand Up @@ -275,7 +281,7 @@ pub enum MyEnum{
**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](#extra-features).<br>
[extra features](#3-extra-features).<br>

```rust ignore
...
Expand All @@ -288,9 +294,9 @@ pub enum MyEnum{
```
<br>

**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.<br>
**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.<br>

```rust ignore
...
Expand All @@ -306,9 +312,9 @@ pub enum MyEnum{
<br>

**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 variants, we also
need to create those variants with values at compile, when this situation arises you have two
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 variants, 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*)]: Here you write the default contents
Expand All @@ -327,7 +333,7 @@ pub enum MyEnum{
Variant1(u8, &'static str),
/// Since the attribute #[variant_initialize_uses] isn't specified, when applying
/// [from::discriminant] to 1, it will return MyEnum::Variant2{age: 0}, as ConstDefault
/// for u8 returns 0
/// for u8 returns 0
Variant2{age:u8},
}
```
Expand All @@ -336,7 +342,7 @@ pub enum MyEnum{
## 2.b.3 Other examples for the derive macro
A simple example could look like this:

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

#[derive(Valued)]
Expand All @@ -353,16 +359,15 @@ pub enum Number{
}
```

A more complex example would look like:
A more complex example could look like:

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

#[derive(Hash, Ord, PartialOrd, Eq, PartialEq, Debug)]
#[derive(Valued)]
#[enum_valued_as(&'static str)]
#[enum_valued_features(Clone, DerefToValue, Delegators,
ValueToVariantDelegators, Serialize, Deserialize)]
#[enum_valued_features(Clone, DerefToValue, Delegators, ValueToVariantDelegators)]
#[unvalued_default("My default string")]
pub enum Number{
/// Zero doesn't have a value, so it's value will resolve to "My default string"
Expand All @@ -385,18 +390,21 @@ pub enum Number{

## 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>
* **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>
* **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>
* **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>
* **ValueToVariantDelegators**: Implements delegator functions calling to [Valued::value_to_variant] and
[Valued::value_to_variant_opt].<br><br>
* **ValueToVariantDelegators**: Implements delegator functions calling to
[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>
Expand All @@ -414,12 +422,16 @@ 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](#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 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.
* 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>
* 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>
* 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>
6 changes: 2 additions & 4 deletions indexed_valued_enums/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "indexed_valued_enums"
version = "0.9.3"
version = "1.0.0"
edition = "2021"
authors = ["Jorge Rico Vivas <jorgericosoftware@gmail.com>"]
license-file = "../LICENSE.txt"
Expand All @@ -17,14 +17,12 @@ crate-type = ["lib"]
serde = { version = "1.0.197", optional = true }
indexed_valued_enums_derive = { path = "../indexed_valued_enums_derive", optional = true }


[features]
serde_enums = ["dep:serde"]
derive = ["dep:indexed_valued_enums_derive"]

[dev-dependencies]
indexed_valued_enums_derive = { path = "../indexed_valued_enums_derive" }
serde = { version = "1.0.197" }
const-default = { version = "1.0.0" }
nanoserde = { version = "0.1.37" }

const-default = { version = "1.0.0" }

0 comments on commit 95ef9b4

Please sign in to comment.