#macro-derive #derive #macro

macro digenum

An enum variant extractor

2 releases

0.1.1 Nov 19, 2022
0.1.0 Nov 19, 2022

#124 in #macros

MIT license

6KB
76 lines

An simple enum variant extractor

Can extract a (mutable) reference or turn into a tuple from fields. When variant is different than the expected, return None.

Example

use digenum::DigEnum;
use std::io::Read;

#[derive(DigEnum)]
enum Login<T: Read> {
    Local,
    Stream(T)
    Token([u8; 64]),
    UserAndPasswd(String, String),
}

Maps to:

Variant Reference Mutable Reference Owned
Local None None None
Stream(T) as_Stream -> Option<&T> as_mut_Stream -> Option<&mut T> into_Stream -> Option<T>
Token([u8; 64]) as_Token -> Option<&[u8; 64]> as_mut_Token -> Option<&mut [u8; 64]> into_Token -> Option<[u8; 64]>
UserAndPasswd(String, String) as_UserAndPasswd -> Option<(&String, &String)> as_mut_UserAndPasswd -> Option<(&mut String, &mut String)> into_UserAndPasswd -> Option<(String, String)>

"Why do not turn snake_case?"

Consider this example:

use digenum::DigEnum;

#[derive(DigEnum)]
enum Foo {
    FOO,
    foo,
    Foo
}

How should I handle it?

Works on

  • Empty enums
  • Empty variants
  • Single-fielded variants
  • Multiple-fielded variants
  • Different-case variants (like Foo::FOO and Foo::foo)
  • Generic variants
  • Unit variants
  • Struct-like variants

Dependencies

~1.5MB
~36K SLoC