#enum #number #ordinal #ordinalize

enum-ordinalize

This crates provides create_ordinalized_enum macro to let enums can not only get its variants’ ordinal but also be constructed from an ordinal

15 stable releases

2.5.0 May 5, 2019
2.4.0 May 5, 2019
2.3.0 Apr 30, 2019
2.2.1 Dec 19, 2018
1.0.1 Sep 2, 2018

#63 in Data structures

Download history 331/week @ 2019-03-21 13/week @ 2019-03-28 12/week @ 2019-04-04 2/week @ 2019-04-11 172/week @ 2019-04-18 31/week @ 2019-04-25 95/week @ 2019-05-02 23/week @ 2019-05-09 28/week @ 2019-05-16 307/week @ 2019-05-23 260/week @ 2019-05-30 89/week @ 2019-06-06 10/week @ 2019-06-13 51/week @ 2019-06-20 251/week @ 2019-06-27

430 downloads per month
Used in 5 crates (3 directly)

MIT license

11KB
182 lines

Enum Ordinalize

Build Status Build status

This crates provides create_ordinalized_enum macro to let enums can not only get its variants' ordinal but also be constructed from an ordinal.

Create an Ordinalized Enum

create_ordinalized_enum macro can create an enum and implement a ordinal method, as well as from_ordinal and from_ordinal_unsafe associated functions for it. The new enum also implements Debug, PartialOrd, Ord, PartialEq, Clone, Eq, Hash and Copy traits.

#[macro_use] extern crate enum_ordinalize;

create_ordinalized_enum!(MyEnum,
    Zero,
    One,
    Two
);

assert_eq!(2, MyEnum::Two.ordinal());
assert_eq!(Some(MyEnum::One), MyEnum::from_ordinal(1));

create_ordinalized_enum!(pub MyPublicEnum,
    A,
    B,
    C
);

assert_eq!(2, MyPublicEnum::C.ordinal());
assert_eq!(Some(MyPublicEnum::B), MyPublicEnum::from_ordinal(1));

create_ordinalized_enum!(MySpecialEnum,
    Two = 2,
    Four = 4,
    Eight = 8
);

assert_eq!(2, MySpecialEnum::Two.ordinal());
assert_eq!(Some(MySpecialEnum::Four), MySpecialEnum::from_ordinal(4));

About an Ordinalized Enum

An ordinalized enum is sized isize by default. If you want to change it, just assign an integer type explicitly.

#[macro_use] extern crate enum_ordinalize;

create_ordinalized_enum!(MyEnum: u8,
    Zero,
    One,
    Two
);

assert_eq!(2u8, MyEnum::Two.ordinal());
assert_eq!(Some(MyEnum::One), MyEnum::from_ordinal(1u8));

If you are 100% sure that the isize value can transmute into a variant of your ordinalized enum. You can use the from_ordinal_unsafe associated function and the unsafe keyword to speed up.

#[macro_use] extern crate enum_ordinalize;

create_ordinalized_enum!(MyEnum,
    Zero,
    One,
    Two
);

assert_eq!(MyEnum::One, unsafe{MyEnum::from_ordinal_unsafe(1)});

Crates.io

https://crates.io/crates/enum-ordinalize

Documentation

https://docs.rs/enum-ordinalize

License

MIT

No runtime deps