#primitive #enums #derive #conversion #try-from #tryfrom #custom

macro derive-try-from-primitive

Custom derive a try_from method for primitive to enum conversions

2 releases (1 stable)

1.0.0 Mar 30, 2020
0.1.0 Jul 12, 2017

#427 in Procedural macros

Download history 17748/week @ 2024-07-23 18886/week @ 2024-07-30 18534/week @ 2024-08-06 18941/week @ 2024-08-13 18565/week @ 2024-08-20 23656/week @ 2024-08-27 24734/week @ 2024-09-03 20216/week @ 2024-09-10 20752/week @ 2024-09-17 19896/week @ 2024-09-24 17290/week @ 2024-10-01 10590/week @ 2024-10-08 21858/week @ 2024-10-15 23331/week @ 2024-10-22 21718/week @ 2024-10-29 18631/week @ 2024-11-05

88,745 downloads per month
Used in 13 crates (8 directly)

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

~1.5MB
~37K SLoC