1#![doc = include_str!("../README.md")]
2#![no_std]
3
4#[macro_export]
5macro_rules! define_into_enum {
6 {
7 $(#[$attr:meta])*
8 $vis:vis enum $name:ident $(< $generic:lifetime >)* {
9 $(#[$variant_attr1:meta])*
10 $variant1:ident ($type1:ty),
11 $(
12 $(#[$variant_attr:meta])*
13 $variant:ident ($type:ty),
14 )*
15 }
16 $into:pat,
17 $output:expr
18 } => {
19 $(#[$attr])*
20 $vis enum $name $(<$generic>)* {
21 $(#[$variant_attr1])*
22 $variant1($type1),
23 $(
24 $(#[$variant_attr])*
25 $variant($type),
26 )*
27 }
28
29 impl$(<$generic>)* Into <$type1> for $name $(<$generic>)* {
30 fn into(self) -> $type1 {
31 match self {
32 $(
33 Self::$variant( $into ) => ( $output ),
34 )+
35 Self::$variant1( $into ) => ( $output ),
36 }
37 }
38 }
39 }
40}
41
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn test_into_impl() {
49 define_into_enum! {
50 #[derive(Debug, PartialEq)]
51 pub enum TestEnum<'a> {
52 #[allow(dead_code)]
53 Variant1(&'a str),
54 #[allow(dead_code)]
55 Variant2(&'a str),
56 #[allow(dead_code)]
57 Variant3(&'a str),
58 }
59 v, v
60 }
61
62 }
63
64 #[test]
65 fn test_enum_variants() {
66 define_into_enum! {
67 #[derive(Debug, PartialEq)]
68 pub enum TestEnum {
69 #[allow(dead_code)]
70 Variant1(i32),
71 #[allow(dead_code)]
72 Variant2(i32),
73 #[allow(dead_code)]
74 Variant3(i32),
75 }
76 v, v
77 }
78
79 assert_eq!(
80 Into::<i32>::into(TestEnum::Variant3(0)),
81 0,
82 "Incorrect conversion for Variant1"
83 );
84 assert_eq!(
85 Into::<i32>::into(TestEnum::Variant3(8i32)),
86 8,
87 "Incorrect conversion for Variant2"
88 );
89 assert_eq!(
90 Into::<i32>::into(TestEnum::Variant3(-9i32)),
91 -9,
92 "Incorrect conversion for Variant3"
93 );
94 }
95}