#primitive #enums #derive #conversion #tryfrom #try-from #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

#398 in Procedural macros

Download history 14900/week @ 2024-06-04 15640/week @ 2024-06-11 16164/week @ 2024-06-18 13655/week @ 2024-06-25 12581/week @ 2024-07-02 12521/week @ 2024-07-09 14010/week @ 2024-07-16 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 16664/week @ 2024-09-17

88,710 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
~36K SLoC