use core::{fmt, str::FromStr};
use crate::parser;
#[repr(C)]
#[derive(Debug, Default, Hash, Eq, PartialEq, Ord, PartialOrd, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MacAddr8([u8; 8]);
impl MacAddr8 {
#[allow(clippy::many_single_char_names, clippy::too_many_arguments)]
pub const fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8, h: u8) -> MacAddr8 {
MacAddr8([a, b, c, d, e, f, g, h])
}
pub const fn nil() -> MacAddr8 {
MacAddr8([0x00; 8])
}
pub const fn broadcast() -> MacAddr8 {
MacAddr8([0xFF; 8])
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn is_nil(&self) -> bool {
self.0.iter().all(|&b| b == 0)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn is_broadcast(&self) -> bool {
self.0.iter().all(|&b| b == 0xFF)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub const fn is_unicast(&self) -> bool {
self.0[0] & 1 == 0
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub const fn is_multicast(&self) -> bool {
self.0[0] & 1 == 1
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub const fn is_universal(&self) -> bool {
self.0[0] & 1 << 1 == 0
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub const fn is_local(&self) -> bool {
self.0[0] & 1 << 1 == 2
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub const fn into_array(self) -> [u8; 8] {
self.0
}
}
impl FromStr for MacAddr8 {
type Err = parser::ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parser::Parser::new(s).read_v8_addr()
}
}
impl From<[u8; 8]> for MacAddr8 {
fn from(bytes: [u8; 8]) -> Self {
MacAddr8(bytes)
}
}
impl AsRef<[u8]> for MacAddr8 {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl AsMut<[u8]> for MacAddr8 {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl fmt::Display for MacAddr8 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.sign_minus() {
f.write_fmt(format_args!(
"{:02X}-{:02X}-{:02X}-{:02X}-{:02X}-{:02X}-{:02X}-{:02X}",
self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5], self.0[6], self.0[7],
))
} else if f.alternate() {
f.write_fmt(format_args!(
"{:02X}{:02X}.{:02X}{:02X}.{:02X}{:02X}.{:02X}{:02X}",
self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5], self.0[6], self.0[7],
))
} else {
f.write_fmt(format_args!(
"{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5], self.0[6], self.0[7],
))
}
}
}