Skip to main content

net_lattice_model/
mac.rs

1use std::fmt;
2
3/// A MAC (Ethernet hardware) address.
4///
5/// Stored as six octets in transmission order. No OS dependency — this is
6/// pure data, used by `net-lattice-model`'s `interface` module and by
7/// backends that read hardware addresses from the OS.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct MacAddress([u8; 6]);
10
11impl MacAddress {
12    pub const fn new(octets: [u8; 6]) -> Self {
13        Self(octets)
14    }
15
16    pub const fn octets(&self) -> [u8; 6] {
17        self.0
18    }
19}
20
21impl fmt::Display for MacAddress {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        let [a, b, c, d, e, g] = self.0;
24        write!(f, "{a:02x}:{b:02x}:{c:02x}:{d:02x}:{e:02x}:{g:02x}")
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    fn displays_in_colon_hex() {
34        let mac = MacAddress::new([0x02, 0x42, 0xab, 0xcd, 0xef, 0x01]);
35        assert_eq!(mac.to_string(), "02:42:ab:cd:ef:01");
36    }
37
38    #[test]
39    fn octets_round_trip() {
40        let octets = [0xff; 6];
41        let mac = MacAddress::new(octets);
42        assert_eq!(mac.octets(), octets);
43    }
44}