#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

12 stable releases

2.2.1 Dec 19, 2018
2.2.0 Nov 19, 2018
2.0.5 Sep 9, 2018
1.0.1 Sep 2, 2018

#18 in Value formatting

Download history 103/week @ 2018-10-16 1/week @ 2018-10-23 228/week @ 2018-10-30 51/week @ 2018-11-06 141/week @ 2018-11-13 26/week @ 2018-11-20 12/week @ 2018-11-27 57/week @ 2018-12-04 13/week @ 2018-12-11 55/week @ 2018-12-18 3/week @ 2018-12-25 6/week @ 2019-01-01 17/week @ 2019-01-08 11/week @ 2019-01-15 1/week @ 2019-01-22

230 downloads per month
Used in 1 crate

MIT license

9KB
126 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 always sized isize in order to directly transmute into an isize value, or conversely. There is a variant named __DoNotUse whose ordinal is always the maximum of an isize value for every ordinalized enum.

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