-
Notifications
You must be signed in to change notification settings - Fork 140
/
from_repr.rs
81 lines (74 loc) · 2.37 KB
/
from_repr.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use if_rust_version::if_rust_version;
use strum::FromRepr;
#[derive(Debug, FromRepr, PartialEq)]
#[repr(u8)]
enum Week {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday = 4 + 3,
Saturday = 8,
}
macro_rules! assert_eq_repr {
( $type:ident::from_repr($number:literal), Some($enum:expr) ) => {
assert_eq!($type::from_repr($number), Some($enum));
if_rust_version! { >= 1.34 {
assert_eq!(core::convert::TryInto::<$type>::try_into($number), Ok($enum));
assert_eq!(<$type as core::convert::TryFrom<_>>::try_from($number), Ok($enum));
}}
};
( $type:ident::from_repr($number:literal), None ) => {
assert_eq!($type::from_repr($number), None);
if_rust_version! { >= 1.34 {
assert_eq!(core::convert::TryInto::<$type>::try_into($number), Err(::strum::ParseError::VariantNotFound));
assert_eq!(<$type as core::convert::TryFrom<_>>::try_from($number), Err(::strum::ParseError::VariantNotFound));
}}
};
}
#[test]
fn simple_test() {
assert_eq_repr!(Week::from_repr(0), Some(Week::Sunday));
assert_eq_repr!(Week::from_repr(1), Some(Week::Monday));
assert_eq_repr!(Week::from_repr(6), None);
assert_eq_repr!(Week::from_repr(7), Some(Week::Friday));
assert_eq_repr!(Week::from_repr(8), Some(Week::Saturday));
assert_eq_repr!(Week::from_repr(9), None);
}
#[rustversion::since(1.46)]
#[test]
fn const_test() {
// This is to test that it works in a const fn
const fn from_repr(discriminant: u8) -> Option<Week> {
Week::from_repr(discriminant)
}
assert_eq!(from_repr(0), Some(Week::Sunday));
assert_eq!(from_repr(1), Some(Week::Monday));
assert_eq!(from_repr(6), None);
assert_eq!(from_repr(7), Some(Week::Friday));
assert_eq!(from_repr(8), Some(Week::Saturday));
assert_eq!(from_repr(9), None);
}
#[test]
fn crate_module_path_test() {
pub mod nested {
pub mod module {
pub use strum;
}
}
#[derive(Debug, FromRepr, PartialEq)]
#[strum(crate = "nested::module::strum")]
enum Week {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
assert_eq_repr!(Week::from_repr(0), Some(Week::Sunday));
assert_eq_repr!(Week::from_repr(6), Some(Week::Saturday));
assert_eq_repr!(Week::from_repr(7), None);
}