summary refs log tree commit diff
path: root/enumn/src/tests.rs
blob: 0d9cb8367bfb7df88e1f3b4dd1b2b7acde03e32d (plain) (blame)
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
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use quote::quote;
use syn::{parse_quote, DeriveInput};

#[test]
fn test_repr() {
    let input: DeriveInput = parse_quote! {
        #[repr(u8)]
        enum E {
            A,
            B,
            C,
        }
    };
    let actual = crate::testable_derive(input);
    let expected = quote! {
        impl E {
            pub fn n(value: u8) -> Option<Self> {
                struct discriminant;
                impl discriminant {
                    const A: u8 = E::A as u8;
                    const B: u8 = E::B as u8;
                    const C: u8 = E::C as u8;
                }
                match value {
                    discriminant::A => Some(E::A),
                    discriminant::B => Some(E::B),
                    discriminant::C => Some(E::C),
                    _ => None,
                }
            }
        }
    };
    assert_eq!(actual.to_string(), expected.to_string());
}

#[test]
fn test_no_repr() {
    let input: DeriveInput = parse_quote! {
        enum E {
            A,
            B,
            C,
        }
    };
    let actual = crate::testable_derive(input);
    let expected = quote! {
        impl E {
            pub fn n<REPR: Into<i64>>(value: REPR) -> Option<Self> {
                struct discriminant;
                impl discriminant {
                    const A: i64 = E::A as i64;
                    const B: i64 = E::B as i64;
                    const C: i64 = E::C as i64;
                }
                match <REPR as Into<i64>>::into(value) {
                    discriminant::A => Some(E::A),
                    discriminant::B => Some(E::B),
                    discriminant::C => Some(E::C),
                    _ => None,
                }
            }
        }
    };
    assert_eq!(actual.to_string(), expected.to_string());
}