Crate enum_primitive [] [src]

This crate exports a macro enum_from_primitive! that wraps an enum declaration and automatically adds an implementation of num::FromPrimitive (reexported here), to allow conversion from primitive integers to the enum. It therefore provides an alternative to the built-in #[derive(FromPrimitive)], which requires the unstable std::num::FromPrimitive and is disabled in Rust 1.0.

Example

#[macro_use] extern crate enum_primitive;
extern crate num_traits;
use num_traits::FromPrimitive;

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum FooBar {
    Foo = 17,
    Bar = 42,
    Baz,
}
}

fn main() {
    assert_eq!(FooBar::from_i32(17), Some(FooBar::Foo));
    assert_eq!(FooBar::from_i32(42), Some(FooBar::Bar));
    assert_eq!(FooBar::from_i32(43), Some(FooBar::Baz));
    assert_eq!(FooBar::from_i32(91), None);
}

Macros

enum_from_primitive

Wrap this macro around an enum declaration to get an automatically generated implementation of num::FromPrimitive.

enum_from_primitive_impl

Helper macro for internal use by enum_from_primitive!.

enum_from_primitive_impl_ty

Helper macro for internal use by enum_from_primitive!.

Enums

Option

The Option type. See the module level documentation for more.

Traits

FromPrimitive

A generic trait for converting a number to a value.