Github
Github Download Tests crates.io docs.rs

penum is a procedural macro that is used for enum conformity and static dispatch. This is done by specifying a declarative pattern that expresses how we should interpret the enum. It's a tool for asserting how enums should look and behave through simple expressive rust grammar.

Installation

This crate is available on crates.io and can be used by adding the following to your project's Cargo.toml: toml [dependencies] penum = "0.1.27" Or run this command in your cargo project: sh $ cargo add penum

Latest feature

You can now use enum descriminants as expression blocks for ToString and Display.

```rust

[penum::to_string]

enum EnumVariants { Variant0 = "Return on match", Variant1(i32) = "Return {f0} on match", Variant2(i32, u32) = stringify!(f0, f1).tostring(), Variant3 { name: String } = format!("My string {name}"), Variant4 { age: u32 } = age.tostring(), }

let enumvariants = Enum::Variant0; println!("{}", enumvariants.to_string()); ```

Add the attribute #[penum::to_string] or #[penum::fmt] to replace strict enum descriminant.


Overview

A Penum expression can look like this: ```console Dispatch symbol. |

[penum( (T) where T: ^Trait )]

     ^^^       ^^^^^^^^^
     |         |
     |         Predicate bound.
     |
     Pattern fragment.

```

A Penum expression without specifying a pattern: ```console

[penum( impl Trait for Type )]

     ^^^^^^^^^^^^^^^^^^^

`` *Shorthand syntax for_ where Type: ^Trait`*

More details

Important to include ^ for traits that you want to dispatch. ```rust

[penum( impl Type: ^Trait )]

```

Note that in a penum impl for expression, no ^ is needed. ```rust

[penum( impl Trait for Type )]

In Rust 1.68.0, `From<bool>` for `{f32,f64}` has stabilized. That means you can do this. rust

[penum( impl From for {f32,f64} )]

```


Trivial example

Use Penum to automatically implement a trait for the enum.

```rust

[penum(impl String: ^AsRef)]

enum Store { V0(), V1(i32), V2(String, i32), V3(i32, usize, String), V4(i32, String, usize), V5 { age: usize, name: String }, V6, } - Will turn into this: rust impl AsRef for Store { fn asref(&self) -> &str { match self { Store::V2(val, ..) => val.asref(), Store::V3(, _, val) => val.asref(), Store::V4(, val, ..) => val.asref(), Store::V5 { name, .. } => name.as_ref(), _ => "", } } } ```

There is also support for user defined traits, but make sure that they are tagged before the enum. ```rust

[penum]

trait Trait { fn method(&self, text: &str) -> &Option<&str>; } ```


Supported std traits

Any, Borrow, BorrowMut, Eq, AsMut, AsRef, From, Into, TryFrom, TryInto, Default, Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex, Future, IntoFuture, FromIterator, FusedIterator, IntoIterator, Product, Sum, Sized, ToSocketAddrs, Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Deref, DerefMut, Div, DivAssign, Drop, Index, IndexMut, Mul, MulAssign, MultiMethod, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, Termination, SliceIndex, FromStr, ToString

Penum is smart enough to infer certain return types for non-matching variants. e.g Option<T>, &Option<T>, String, &str. It can even handle &String, referenced non-const types. The goal is to support any type, which we could potentially do by checking for types implementing the Default trait.

Note, when dispatching traits with associated types, it's important to declare them. e.g Add<i32, Output = i32>.

Examples

Used penum to force every variant to be a tuple with one field that must implement Trait.

```rust

[penum( (T, ..) where T: Trait )]

enum Guard { Bar(String), ^^^^^^ // ERROR: String doesn't implement Trait

Bor(Option<String>), 
    ^^^^^^^^^^^^^^
// ERROR: `Option<String>` doesn't implement `Trait`

Bur(Vec<String>), 
    ^^^^^^^^^^^
// ERROR: `Vec<String>` doesn't implement `Trait`

Byr(), 
^^^^^
// ERROR: `Byr()` doesn't match pattern `(T)`

Bxr { name: usize }, 
    ^^^^^^^^^^^^^^^
// ERROR: `{ nname: usize }` doesn't match pattern `(T)`

Brr,
^^^
// ERROR: `Brr` doesn't match pattern `(T)`

Bir(i32, String), // Works!
Beer(i32)         // Works!

} ```

If you don't care about the actual pattern matching, then you could use _ to automatically infer every shape and field. Combine this with concrete dispatch types, and you got yourself a auto dispatcher.

Under development

For non-std types we rely on the Default trait, which means, if we can prove that a type implements Default we can automatically add them as return types for non-matching variants,

```rust

[penum( _ where Ce: ^Special, Be: ^AsInner )]

enum Foo { V1(Al), V2(i32, Be), V3(Ce), V4 { name: String, age: Be }, }

// Will create these implementations impl Special for Foo { fn ret(&self) -> Option<&String> { match self { Foo::V3(val) => val.ret(), _ => None, } } }

impl AsInner for Foo { fn asinner(&self) -> &i32 { match self { Foo::V2(, val) => val.asinner(), Foo::V4 { age, .. } => age.asinner(), _ => &0, } } } ```

```

More details