#enums #macro

macro enum_index_derive

Macros for extracting Enum variant index

3 unstable releases

Uses old Rust 2015

0.2.0 May 23, 2017
0.1.1 Apr 30, 2017
0.1.0 Apr 30, 2017

#113 in #enum

Download history 11501/week @ 2023-11-29 8879/week @ 2023-12-06 8889/week @ 2023-12-13 4881/week @ 2023-12-20 4626/week @ 2023-12-27 5559/week @ 2024-01-03 7168/week @ 2024-01-10 10113/week @ 2024-01-17 5847/week @ 2024-01-24 5702/week @ 2024-01-31 13638/week @ 2024-02-07 10711/week @ 2024-02-14 6777/week @ 2024-02-21 7315/week @ 2024-02-28 5580/week @ 2024-03-06 5369/week @ 2024-03-13

27,228 downloads per month
Used in 50 crates (6 directly)

MIT license

4KB
97 lines

EnumIndex

EnumIndex is a trait to extract variant index from enums in Rust.
IndexEnum is a trait that allows you to get an enum variant by indexing. It only works if all parameters of Enum implement Default

The main case is implementation of your own enum serialization.

pub trait EnumIndex {
    fn enum_index(&self) -> usize;
}

pub trait IndexEnum {
    fn index_enum(index: usize) -> Option<Self> where Self: Sized;
}

Example

// Contains needed traits
extern crate enum_index;
// Contains derives
#[macro_use]
extern crate enum_index_derive;
use enum_index::{EnumIndex, IndexEnum};

// IndexEnum can only be derived for enums with parameters implementing Default
// In this example Default is checked for String, f32 and u64.
#[derive(EnumIndex, IndexEnum, Debug)]
enum OpCode {
    Disconnect,                       // 0
    SendData(String),                 // 1
    SomethingElse { a: f32, b: u64 }  // 2
}

fn main() {
    let first = OpCode::Disconnect;
    let second = OpCode::SendData("hello");
    let third = OpCode::SomethingElse {a: 1f32, b: 2u64};
    println!("{}", first.enum_index()); // prints 0
    println!("{}", second.enum_index()); // prints 1
    println!("{}", third.enum_index()); // prints 2

    let opcode_variant = OpCode::index_enum(2).unwrap();
    println!("{:?}", opcode_variant); // prints SomethingElse{a: 0f32, b: 0u64}
}

Using in your project

Add the following in your Cargo.toml file

[dependencies]
enum_index = "0.2.0"
enum_index_derive = "0.2.0"

Then import needed trait and macro

extern crate enum_index;
#[macro_use]
extern crate enum_index_derive;

Dependencies

~1.5MB
~40K SLoC