#enums #index #string #macro #macro-derive

macro enum2pos

enum2pos is a rust derive macro for enums that generates "from_index(usize, Vec<String>) -> Option<Self>" and "to_index()" methods for converting between an variants and their position within the enum declaration (similar to an index)

2 releases

0.1.1 Mar 24, 2023
0.1.0 Mar 24, 2023

#1960 in Procedural macros

Download history 147/week @ 2024-03-10 156/week @ 2024-03-17 284/week @ 2024-03-24 600/week @ 2024-03-31 75/week @ 2024-04-07 107/week @ 2024-04-14 99/week @ 2024-04-21 63/week @ 2024-04-28 177/week @ 2024-05-05 176/week @ 2024-05-12 173/week @ 2024-05-19 128/week @ 2024-05-26 108/week @ 2024-06-02 147/week @ 2024-06-09 89/week @ 2024-06-16 202/week @ 2024-06-23

547 downloads per month

MIT license

7KB
78 lines

enum2pos

github crates.io docs.rs

enum2pos is a rust derive macro for enums that generates from_index(usize, Vec<String>) -> Option<Self> and to_index() methods for converting between an variants and their position within the enum declaration (similar to an index).

Usage

Add this to your Cargo.toml:

enum2pos = "0.1.1"

Example:

use enum2pos::EnumIndex;

#[derive(EnumIndex, PartialEq, Debug)]
enum SampleEnum {
    Unit,
    Unnamed(i32, String),
}

#[test]
fn to_index() {
    let unit = SampleEnum::Unit;
    let unnamed = SampleEnum::Unnamed(42, String::from("test"));

    assert_eq!(unit.to_index(), 0);
    assert_eq!(unnamed.to_index(), 1);
}

#[test]
fn from_index_unit() {
    let index = 0;
    let args: Vec<String> = vec![];
    let expected = Some(SampleEnum::Unit);

    assert_eq!(SampleEnum::from_index(index, &args), expected);
}

#[test]
fn from_index_unnamed() {
    let index = 1;
    let args = vec!["42".to_string(), "test".to_string()];
    let expected = Some(SampleEnum::Unnamed(42, String::from("test")));

    assert_eq!(SampleEnum::from_index(index, &args), expected);
}

#[test]
fn from_index_invalid() {
    let index = 2;
    let args: Vec<String> = vec![];

    assert_eq!(SampleEnum::from_index(index, &args), None);
}

Dependencies

~1.5MB
~35K SLoC