enum2pos

Crates.ioenum2pos
lib.rsenum2pos
version0.1.2
sourcesrc
created_at2023-03-24 20:20:52.661672
updated_at2024-10-23 20:07:26.297588
descriptionenum2pos is a rust derive macro for enums that generates "from_index(usize, Vec) -> Option" and "to_index()" methods for converting between an variants and their position within the enum declaration (similar to an index).
homepagehttps://github.com/matthewjberger/enum2pos
repositoryhttps://github.com/matthewjberger/enum2pos
max_upload_size
id819685
size9,012
Matthew J. Berger (matthewjberger)

documentation

README

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);
}
Commit count: 7

cargo fmt