#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)

3 releases

0.1.2 Oct 23, 2024
0.1.1 Mar 24, 2023
0.1.0 Mar 24, 2023

#533 in Procedural macros

Download history 294/week @ 2024-08-26 190/week @ 2024-09-02 199/week @ 2024-09-09 254/week @ 2024-09-16 230/week @ 2024-09-23 78/week @ 2024-09-30 98/week @ 2024-10-07 15/week @ 2024-10-14 261/week @ 2024-10-21 50/week @ 2024-10-28 85/week @ 2024-11-04 151/week @ 2024-11-11 147/week @ 2024-11-18 33/week @ 2024-12-02 61/week @ 2024-12-09

242 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.2"

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
~37K SLoC