#enum #primitive #fromprimitive #macro #built-in #derive #bar #foo

enum_primitive

Macro to generate num::FromPrimitive instances for enum that works in Rust 1.0

4 releases

Uses old Rust 2015

0.1.1 Jan 9, 2017
0.1.0 Aug 13, 2015
0.0.2 Apr 8, 2015
0.0.1 Apr 7, 2015

#1276 in Rust patterns

Download history 22144/week @ 2023-08-14 21773/week @ 2023-08-21 20486/week @ 2023-08-28 20277/week @ 2023-09-04 22900/week @ 2023-09-11 22953/week @ 2023-09-18 22897/week @ 2023-09-25 24210/week @ 2023-10-02 27060/week @ 2023-10-09 26293/week @ 2023-10-16 27154/week @ 2023-10-23 21996/week @ 2023-10-30 19210/week @ 2023-11-06 20904/week @ 2023-11-13 16625/week @ 2023-11-20 17434/week @ 2023-11-27

75,349 downloads per month
Used in fewer than 87 crates

MIT license

9KB
126 lines

enum_primitive Build Status

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.

Documentation

https://andersk.github.io/enum_primitive-rs/enum_primitive/

Usage

Add the following to your Cargo.toml file:

[dependencies]
enum_primitive = "*"

Import the crate using #[macro_use] extern crate enum_primitive, and wrap your enum declaration inside the enum_from_primitive! macro.

Example

#[macro_use] extern crate enum_primitive;
extern crate num;
use num::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);
}

Dependencies

~235KB