aboutsummaryrefslogtreecommitdiff
path: root/src/util.rs
diff options
context:
space:
mode:
authorRobin Krahl <robin.krahl@ireas.org>2019-02-18 11:39:39 +0000
committerRobin Krahl <robin.krahl@ireas.org>2019-02-18 15:30:25 +0100
commit8d9241e033e1babeccee49ab848c15edd8831516 (patch)
tree8b7eca5101f299335233038eb80da685ae1ca452 /src/util.rs
parent7da90438dd7851f66abfa81eba2eeb36ff9c9c25 (diff)
downloadntw-8d9241e033e1babeccee49ab848c15edd8831516.tar.gz
ntw-8d9241e033e1babeccee49ab848c15edd8831516.tar.bz2
Add enum_u8 macro to simplify enum conversion
We need several enums that map to a u8 value. This patch adds the enum_u8 macro that automatically derives the From and TryFrom macros for an enum to make these conversions easier. As TryFrom is not stable yet, we add our own TryFrom trait.
Diffstat (limited to 'src/util.rs')
-rw-r--r--src/util.rs43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/util.rs b/src/util.rs
new file mode 100644
index 0000000..4fc4448
--- /dev/null
+++ b/src/util.rs
@@ -0,0 +1,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, ()>;
+}