dpdk_serde/
serde_pub_enum_u8.rs

1// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
2// Copyright © 2016-2017 The developers of dpdk. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT.
3
4
5#[macro_export]
6macro_rules! serde_pub_enum_u8
7{
8	($name:ident { $($variant:ident = $value:expr, )* }) =>
9	{
10		#[repr(u8)]
11		#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
12		pub enum $name
13		{
14			$($variant = $value,)*
15		}
16
17		impl ::serde::Serialize for $name
18		{
19			fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>
20			{
21				serializer.serialize_u8(*self as u8)
22			}
23		}
24
25		impl ::serde::Deserialize for $name
26		{
27			fn deserialize<D: ::serde::Deserializer>(deserializer: D) -> Result<Self, D::Error>
28			{
29				struct Visitor;
30
31				impl ::serde::de::Visitor for Visitor
32				{
33					type Value = $name;
34
35					fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result
36					{
37						formatter.write_str("positive integer")
38					}
39
40					fn visit_u8<E: ::serde::de::Error>(self, value: u8) -> Result<$name, E>
41					{
42						// Rust does not come with a simple way of converting a number to an enum, so use a big `match`.
43						match value
44						{
45							$( $value => Ok($name::$variant), )*
46							_ => Err(E::custom(format!("unknown {} value: {}", stringify!($name), value))),
47						}
48					}
49				}
50
51				deserializer.deserialize_u8(Visitor)
52			}
53		}
54	}
55}