#custom #derive #enum #primitive #tryfrom

macro derive-try-from-primitive

Custom derive a try_from method for primitive to enum conversions

2 releases (1 stable)

✓ Uses Rust 2018 edition

1.0.0 Mar 30, 2020
0.1.0 Jul 12, 2017

#98 in Rust patterns

Download history 1005/week @ 2020-03-23 898/week @ 2020-03-30 679/week @ 2020-04-06 760/week @ 2020-04-13 999/week @ 2020-04-20 1054/week @ 2020-04-27 1228/week @ 2020-05-04 1083/week @ 2020-05-11 1141/week @ 2020-05-18 903/week @ 2020-05-25 949/week @ 2020-06-01 833/week @ 2020-06-08 683/week @ 2020-06-15 842/week @ 2020-06-22 728/week @ 2020-06-29 599/week @ 2020-07-06

3,709 downloads per month
Used in dtn7-plus

MIT/Apache

10KB
191 lines

Example

use core::convert::TryFrom;
use derive_try_from_primitive::TryFromPrimitive;


#[derive(TryFromPrimitive)]
#[repr(u16)]
enum Foo {
    Bar,
    Baz = 100,
    Quix = 200,
}

// Generated Code:
impl core::convert::TryFrom<u16> for Foo {
    type Error = u16;

    fn try_from(n: 16) -> Result<Self, Self::Error> {
        match n {
            0 => Ok(Foo::Bar),
            100 => Ok(Foo::Baz),
            200 => Ok(Foo::Quix),
            _ => Err(n),
        }
    }
}

fn main() {
    let bar = Foo::try_from(0);
    let baz = Foo::try_from(100);
    let quix = Foo::try_from(200);
    let bad = Foo::try_from(300);
    assert_eq!(bar.unwrap() as u16, 0);
    assert_eq!(baz.unwrap() as u16, 100);
    assert_eq!(quix.unwrap() as u16, 200);
    if let Err(value) = bad {
        assert_eq!(value, 300, "Input is returned for convenience");
    }
}

Dependencies

~385–710KB
~17K SLoC