#macros #enum #enums #variants #try-from

enum_variant_macros

Macros to generate From & TryFrom for enums

2 unstable releases

Uses new Rust 2021

0.2.0 May 30, 2022
0.1.0 Feb 23, 2022

#292 in Rust patterns

Download history 15/week @ 2022-06-06 17/week @ 2022-06-13 45/week @ 2022-06-20 23/week @ 2022-06-27 23/week @ 2022-07-04 48/week @ 2022-07-11 42/week @ 2022-07-18 37/week @ 2022-07-25 66/week @ 2022-08-01 289/week @ 2022-08-08 257/week @ 2022-08-15 186/week @ 2022-08-22 904/week @ 2022-08-29 670/week @ 2022-09-05 255/week @ 2022-09-12 92/week @ 2022-09-19

1,930 downloads per month
Used in xcodeproj

MIT/Apache

9KB
50 lines

Enum Variant Macros

Macro library for use in generating From & TryFrom implementations for enums composed of unnamed single members. In other terms, of the following format.

pub enum Variants {
    Integer(i32),
    Float(f32),
    Bool(bool),
    Byte(u8),
}

This library has 2 macros, TryFromVariants & FromVariants.

TryFromVariants implements TryFrom for each of the variant types, permitting code such as,

use enum_variant_macros::*;
use std::error::Error;
use strum_macros::IntoStaticStr;

#[derive(IntoStaticStr, TryFromVariants)]
enum Variants {
    Integer(i32),
    Float(f32),
}

fn main() -> Result<(), Box<dyn Error>> {
    let variant = Variants::Float(12.0);
    let float: f32 = TryFrom::try_from(variant)?;
    Ok(())
}

Note: Derivation of this type also requires that impl From<Variant> for &'static str is implemented.

FromVariants is relatively simple, it just generates From for each wrapped type.

use enum_variant_macros::*;

#[derive(Debug, PartialEq, FromVariants)]
enum Variants {
    Integer(i32),
    Float(f32),
}

let variant = Variants::from(12);
assert_eq!(Variants::Integer(12), variant);

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Dependencies

~220–630KB
~15K SLoC