Debian Codegraph @

tests/enum_try_from.rs

raw symbols SCIP
1 /*
2 Copyright ⓒ 2015 macro-attr contributors.
3
4 Licensed under the MIT license (see LICENSE or <http://opensource.org
5 /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
6 <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
7 files in the project carrying such notice may not be copied, modified,
8 or distributed except according to those terms.
9 */
10 #[macro_use] extern crate macro_attr;
11
12 trait TryFrom<Src>: Sized {
13 type Err;
14 fn try_from(src: Src) -> Result<Self, Self::Err>;
15 }
16
17 macro_rules! TryFrom {
18 (($prim:ty) $(pub)* enum $name:ident { $($body:tt)* }) => {
19 TryFrom! {
20 @collect_variants ($name, $prim),
21 ($($body)*,) -> ()
22 }
23 };
24
25 (
26 @collect_variants ($name:ident, $prim:ty),
27 ($(,)*) -> ($($var_names:ident,)*)
28 ) => {
29 impl TryFrom<$prim> for $name {
30 type Err = $prim;
31 fn try_from(src: $prim) -> Result<$name, $prim> {
32 $(
33 if src == $name::$var_names as $prim {
34 return Ok($name::$var_names);
35 }
36 )*
37 Err(src)
38 }
39 }
40 };
41
42 (
43 @collect_variants $fixed:tt,
44 ($var:ident $(= $_val:expr)*, $($tail:tt)*) -> ($($var_names:tt)*)
45 ) => {
46 TryFrom! {
47 @collect_variants $fixed,
48 ($($tail)*) -> ($($var_names)* $var,)
49 }
50 };
51
52 (
53 @collect_variants ($name:ident),
54 ($var:ident $_struct:tt, $($tail:tt)*) -> ($($var_names:tt)*)
55 ) => {
56 const _error: () = concat!(
57 "cannot derive TryFrom for ",
58 stringify!($name),
59 ", due to non-unitary variant ",
60 stringify!($var),
61 "."
62 );
63 };
64 }
65
66 macro_attr! {
67 #[derive(Debug, PartialEq, TryFrom!(u8))]
68 enum Get { Up, Down, AllAround }
69 }
70
71 #[test]
72 fn test_try_from() {
73 assert_eq!(Get::try_from(0u8), Ok(Get::Up));
74 assert_eq!(Get::try_from(1u8), Ok(Get::Down));
75 assert_eq!(Get::try_from(2u8), Ok(Get::AllAround));
76 assert_eq!(Get::try_from(3u8), Err(3u8));
77 }