aboutsummaryrefslogtreecommitdiff
path: root/src/util.rs
blob: 4fc4448d3a69356ce9c24a01db0b78664cefc70f (plain)
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
// Copyright 2019 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: GPL-3.0-or-later

use core::marker::Sized;

macro_rules! enum_u8 {
    (
        $(#[$outer:meta])*
        pub enum $name:ident {
            $($var:ident = $num:expr),+
            $(,)*
        }
    ) => {
        $(#[$outer])*
        #[repr(u8)]
        pub enum $name {
            $(
                $var = $num,
            )*
        }

        impl crate::util::TryFrom<u8> for $name {
            fn try_from(val: u8) -> ::core::result::Result<Self, ()> {
                match val {
                    $(
                        $num => Ok($name::$var),
                    )*
                    _ => Err(())
                }
            }
        }

        impl From<$name> for u8 {
            fn from(val: $name) -> u8 {
                val as u8
            }
        }
    };
}

pub trait TryFrom<T>: Sized {
    fn try_from(val: T) -> Result<Self, ()>;
}