demikernel/runtime/network/types/
macaddr.rs1use crate::runtime::fail::Fail;
9use ::libc::EINVAL;
10use ::std::{
11 fmt,
12 str::FromStr,
13};
14
15#[derive(Copy, Clone, PartialEq, Eq, Hash)]
21pub struct MacAddress(eui48::MacAddress);
22
23impl MacAddress {
28 pub const fn new(bytes: [u8; 6]) -> Self {
29 MacAddress(eui48::MacAddress::new(bytes))
30 }
31
32 pub fn from_bytes(bytes: &[u8]) -> Self {
33 MacAddress(eui48::MacAddress::from_bytes(bytes).unwrap())
34 }
35
36 pub fn octets(&self) -> [u8; 6] {
38 self.0.to_array()
39 }
40
41 pub fn broadcast() -> MacAddress {
42 MacAddress(eui48::MacAddress::broadcast())
43 }
44
45 pub fn nil() -> MacAddress {
46 MacAddress(eui48::MacAddress::nil())
47 }
48
49 pub fn is_nil(self) -> bool {
50 self.0.is_nil()
51 }
52
53 pub fn is_broadcast(self) -> bool {
54 self.0.is_broadcast()
55 }
56
57 pub fn is_multicast(self) -> bool {
58 self.0.is_multicast()
59 }
60
61 pub fn is_unicast(self) -> bool {
62 self.0.is_unicast()
63 }
64
65 pub fn to_canonical(self) -> String {
66 self.0.to_canonical()
67 }
68
69 pub fn as_bytes(&self) -> &[u8] {
70 self.0.as_bytes()
71 }
72
73 pub fn parse_canonical_str(canonical_macaddr_string: &str) -> Result<Self, Fail> {
74 match eui48::MacAddress::parse_str(canonical_macaddr_string) {
75 Ok(addr) => Ok(Self(addr)),
76 Err(_) => Err(Fail::new(EINVAL, "failed to parse MAC Address")),
77 }
78 }
79
80 pub fn to_array(self) -> [u8; 6] {
82 self.0.to_array()
83 }
84}
85
86impl fmt::Display for MacAddress {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 self.0.fmt(f)
93 }
94}
95
96impl fmt::Debug for MacAddress {
97 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98 write!(f, "MacAddress({})", &self.to_canonical())
99 }
100}
101
102impl FromStr for MacAddress {
103 type Err = Fail;
104
105 fn from_str(s: &str) -> Result<Self, Self::Err> {
106 MacAddress::parse_canonical_str(s)
107 }
108}