Skip to main content

raw_ether/
mac.rs

1//! MAC addresses.
2
3use core::fmt;
4use core::str::FromStr;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
7pub struct MacAddress(pub [u8; 6]);
8
9impl MacAddress {
10    pub const BROADCAST: MacAddress = MacAddress([0xff; 6]);
11
12    pub fn is_multicast(self) -> bool {
13        self.0[0] & 0x01 != 0
14    }
15}
16
17impl fmt::Display for MacAddress {
18    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
19        let [a, b, c, d, e, f] = self.0;
20        write!(formatter, "{a:02x}:{b:02x}:{c:02x}:{d:02x}:{e:02x}:{f:02x}")
21    }
22}
23
24impl FromStr for MacAddress {
25    type Err = ParseError;
26
27    /// `00:1b:92:01:ab:cd`, with `:` or `-` between the octets.
28    fn from_str(text: &str) -> Result<Self, Self::Err> {
29        let mut octets = [0; 6];
30        let mut parts = text.trim().split([':', '-']);
31        for octet in &mut octets {
32            let part = parts.next().ok_or(ParseError)?;
33            if part.len() != 2 {
34                return Err(ParseError);
35            }
36            *octet = u8::from_str_radix(part, 16).map_err(|_| ParseError)?;
37        }
38        if parts.next().is_some() {
39            return Err(ParseError);
40        }
41        Ok(MacAddress(octets))
42    }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ParseError;
47
48impl fmt::Display for ParseError {
49    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
50        formatter.write_str("not a valid MAC address")
51    }
52}
53
54impl core::error::Error for ParseError {}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn round_trips() {
62        let mac: MacAddress = "00:01:F2:01:62:e5".parse().unwrap();
63        assert_eq!(mac.to_string(), "00:01:f2:01:62:e5");
64        assert_eq!("00-01-f2-01-62-e5".parse::<MacAddress>(), Ok(mac));
65        assert!(!mac.is_multicast());
66        assert!(MacAddress::BROADCAST.is_multicast());
67    }
68
69    #[test]
70    fn bad_addresses_are_refused() {
71        for text in [
72            "",
73            "00:01:f2:01:62",
74            "00:01:f2:01:62:e5:00",
75            "0:01:f2:01:62:e5",
76            "zz:01:f2:01:62:e5",
77        ] {
78            assert!(text.parse::<MacAddress>().is_err(), "{text}");
79        }
80    }
81}