#enum

macro num_enum

Procedural macros to make inter-operation between primitives and enums easier

7 releases

✓ Uses Rust 2018 edition

0.3.0 Jul 11, 2019
0.2.3 Jun 30, 2019
0.2.0 Apr 19, 2019
0.1.1 Nov 12, 2018

#98 in Rust patterns

Download history 81/week @ 2019-03-28 110/week @ 2019-04-04 118/week @ 2019-04-11 118/week @ 2019-04-18 251/week @ 2019-04-25 266/week @ 2019-05-02 55/week @ 2019-05-09 111/week @ 2019-05-16 64/week @ 2019-05-23 219/week @ 2019-05-30 79/week @ 2019-06-06 122/week @ 2019-06-13 192/week @ 2019-06-20 201/week @ 2019-06-27 178/week @ 2019-07-04

657 downloads per month
Used in 3 crates

BSD-3-Clause

10KB
171 lines

num_enum

Procedural macros to make inter-operation between primitives and enums easier. This crate is no_std compatible.

crates.io Documentation Build Status

Turning an enum into a primitive

use num_enum::IntoPrimitive;

#[derive(IntoPrimitive)]
#[repr(u8)]
enum Number {
    Zero,
    One,
}

#[test]
fn convert() {
    let zero: u8 = Number::Zero.into();
    assert_eq!(zero, 0u8);
}

num_enum's IntoPrimitive is more type-safe than using as, because as will silently truncate - num_enum only derives From for exactly the discriminant type of the enum.

Turning a primitive into an enum with try_from

use num_enum::TryFromPrimitive;
use std::convert::TryInto;

#[derive(Debug, Eq, PartialEq, TryFromPrimitive)]
#[repr(u8)]
enum Number {
    Zero,
    One,
}

#[test]
fn convert() {
    let zero: Number = 0u8.try_into().unwrap();
    assert_eq!(zero, Ok(Number::Zero));

    let three: Result<Number, String> = 3u8.try_into();
    assert_eq!(three, Err("No value in enum Number for value 3".to_owned()));
}

Optional features

Some enum values may be composed of complex expressions, for example:

enum Number {
    Zero = (0, 1).0,
    One = (0, 1).1,
}

To cut down on compile time, these are not supported by default, but if you enable the complex-expressions feature of your dependency on num_enum, these should start working.

Dependencies

~752KB
~17K SLoC