use mac_oui::Oui;
use std::fmt;
use std::str::FromStr;
use std::sync::OnceLock;
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MacAddr([u8; 6]);
impl MacAddr {
pub const fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> Self {
Self([a, b, c, d, e, f])
}
pub const fn octets(self) -> [u8; 6] {
self.0
}
pub const fn is_locally_administered(self) -> bool {
self.0[0] & 0b0000_0010 != 0
}
pub const fn is_multicast(self) -> bool {
self.0[0] & 0b0000_0001 != 0
}
}
impl From<[u8; 6]> for MacAddr {
fn from(octets: [u8; 6]) -> Self {
Self(octets)
}
}
impl From<MacAddr> for [u8; 6] {
fn from(mac: MacAddr) -> Self {
mac.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("'{input}' is not a MAC address: expected six hex octets separated by ':' or '-'")]
pub struct MacAddrParseError {
pub input: String,
}
impl FromStr for MacAddr {
type Err = MacAddrParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let fail = || MacAddrParseError {
input: s.to_string(),
};
let mut octets = [0u8; 6];
let mut parts = s.trim().split([':', '-']);
for octet in &mut octets {
let part = parts.next().ok_or_else(fail)?;
if part.len() != 2 {
return Err(fail());
}
*octet = u8::from_str_radix(part, 16).map_err(|_| fail())?;
}
if parts.next().is_some() {
return Err(fail());
}
Ok(Self(octets))
}
}
impl fmt::Debug for MacAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
)
}
}
impl fmt::Display for MacAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
)
}
}
static OUI_DB: OnceLock<Option<Oui>> = OnceLock::new();
fn oui_db() -> Option<&'static Oui> {
OUI_DB.get_or_init(|| Oui::default().ok()).as_ref()
}
pub fn vendor(mac: &MacAddr) -> Option<String> {
let entry = oui_db()?.lookup_by_mac(&mac.to_string()).ok()??;
Some(entry.company_name.clone())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_address_renders_as_lowercase_colon_separated_hex() {
let mac = MacAddr::new(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E);
assert_eq!(mac.to_string(), "00:1a:2b:3c:4d:5e");
assert_eq!(format!("{mac:?}"), "00:1a:2b:3c:4d:5e");
}
#[test]
fn octets_survive_the_conversions_frame_parsing_uses() {
let octets = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
let mac = MacAddr::from(octets);
assert_eq!(mac.octets(), octets);
assert_eq!(<[u8; 6]>::from(mac), octets);
}
#[test]
fn an_address_round_trips_through_its_own_rendering() {
let mac = MacAddr::new(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E);
assert_eq!(mac.to_string().parse(), Ok(mac));
}
#[test]
fn both_separators_and_either_case_are_accepted() {
let mac = MacAddr::new(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E);
assert_eq!("00-1A-2B-3C-4D-5E".parse(), Ok(mac));
assert_eq!("00:1a:2b:3c:4d:5e".parse(), Ok(mac));
}
#[test]
fn malformed_addresses_are_refused() {
for input in [
"",
"00:1a:2b:3c:4d",
"00:1a:2b:3c:4d:5e:6f",
"zz:1a:2b:3c:4d:5e",
"001a2b3c4d5e",
] {
assert!(
input.parse::<MacAddr>().is_err(),
"'{input}' parsed as an address"
);
}
}
#[test]
fn the_locally_administered_and_multicast_bits_are_read() {
assert!(MacAddr::new(0x02, 0, 0, 0, 0, 0).is_locally_administered());
assert!(!MacAddr::new(0x00, 0x0C, 0x29, 0, 0, 0).is_locally_administered());
assert!(MacAddr::new(0x01, 0, 0x5e, 0, 0, 0).is_multicast());
assert!(!MacAddr::new(0x00, 0x0C, 0x29, 0, 0, 0).is_multicast());
}
#[test]
fn a_registered_oui_resolves_to_a_vendor() {
let vmware = MacAddr::new(0x00, 0x0C, 0x29, 0xAB, 0xCD, 0xEF);
assert!(vendor(&vmware).is_some());
}
#[test]
fn a_locally_administered_address_has_no_vendor() {
let local = MacAddr::new(0x02, 0x00, 0x00, 0x00, 0x00, 0x00);
assert_eq!(vendor(&local), None);
}
}