cni_plugin/
macaddr.rs

1//! MAC address (de)serialisation.
2
3use std::{fmt, str::FromStr};
4
5use macaddr::{MacAddr6, ParseError};
6use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
7
8/// A MAC address.
9///
10/// This type’s entire purpose is to serialize and deserialize from the string
11/// representation of a MAC address, rather than `[u8; 6]` as the underlying
12/// type does.
13#[derive(Debug, Default, Hash, Eq, PartialEq, Ord, PartialOrd, Copy, Clone)]
14pub struct MacAddr(pub MacAddr6);
15
16impl From<MacAddr6> for MacAddr {
17	fn from(m: MacAddr6) -> Self {
18		Self(m)
19	}
20}
21
22impl From<MacAddr> for MacAddr6 {
23	fn from(m: MacAddr) -> Self {
24		m.0
25	}
26}
27
28impl fmt::Display for MacAddr {
29	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30		self.0.fmt(f)
31	}
32}
33
34impl FromStr for MacAddr {
35	type Err = ParseError;
36
37	fn from_str(s: &str) -> Result<Self, Self::Err> {
38		MacAddr6::from_str(s).map(Self)
39	}
40}
41
42impl Serialize for MacAddr {
43	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
44	where
45		S: Serializer,
46	{
47		self.to_string().serialize(serializer)
48	}
49}
50
51impl<'de> Deserialize<'de> for MacAddr {
52	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53	where
54		D: Deserializer<'de>,
55	{
56		let j = String::deserialize(deserializer)?;
57		Self::from_str(&j).map_err(Error::custom)
58	}
59}