1 // Copyright 2018 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use quote::quote;
6 use syn::{parse_quote, DeriveInput};
7 
8 #[test]
test_repr()9 fn test_repr() {
10     let input: DeriveInput = parse_quote! {
11         #[repr(u8)]
12         enum E {
13             A,
14             B,
15             C,
16         }
17     };
18     let actual = crate::testable_derive(input);
19     let expected = quote! {
20         #[allow(non_upper_case_globals)]
21         impl E {
22             pub fn n(value: u8) -> Option<Self> {
23                 struct discriminant;
24                 impl discriminant {
25                     const A: u8 = E::A as u8;
26                     const B: u8 = E::B as u8;
27                     const C: u8 = E::C as u8;
28                 }
29                 match value {
30                     discriminant::A => Some(E::A),
31                     discriminant::B => Some(E::B),
32                     discriminant::C => Some(E::C),
33                     _ => None,
34                 }
35             }
36         }
37     };
38     assert_eq!(actual.to_string(), expected.to_string());
39 }
40 
41 #[test]
test_no_repr()42 fn test_no_repr() {
43     let input: DeriveInput = parse_quote! {
44         enum E {
45             A,
46             B,
47             C,
48         }
49     };
50     let actual = crate::testable_derive(input);
51     let expected = quote! {
52         #[allow(non_upper_case_globals)]
53         impl E {
54             pub fn n<REPR: Into<i64>>(value: REPR) -> Option<Self> {
55                 struct discriminant;
56                 impl discriminant {
57                     const A: i64 = E::A as i64;
58                     const B: i64 = E::B as i64;
59                     const C: i64 = E::C as i64;
60                 }
61                 match <REPR as Into<i64>>::into(value) {
62                     discriminant::A => Some(E::A),
63                     discriminant::B => Some(E::B),
64                     discriminant::C => Some(E::C),
65                     _ => None,
66                 }
67             }
68         }
69     };
70     assert_eq!(actual.to_string(), expected.to_string());
71 }
72