use crate::types::{C_DLL_ETHERTYPE_EPL, UNSIGNED16};
use core::fmt;
pub const MAC_ADDRESS_SIZE: usize = 6;
pub const ETHERNET_HEADER_SIZE: usize = 14;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MacAddress(pub [u8; MAC_ADDRESS_SIZE]);
impl MacAddress {
pub const fn new(bytes: [u8; MAC_ADDRESS_SIZE]) -> Self {
MacAddress(bytes)
}
pub fn is_multicast(&self) -> bool {
(self.0[0] & 0x01) != 0
}
pub fn is_broadcast(&self) -> bool {
self.0 == [0xFF; 6]
}
}
impl fmt::Display for MacAddress {
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]
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EthernetHeader {
pub destination_mac: MacAddress,
pub source_mac: MacAddress,
pub ether_type: UNSIGNED16,
}
impl EthernetHeader {
pub fn is_powerlink(&self) -> bool {
self.ether_type.to_be() == C_DLL_ETHERTYPE_EPL
}
pub fn new(dest: MacAddress, src: MacAddress) -> Self {
Self {
destination_mac: dest,
source_mac: src,
ether_type: C_DLL_ETHERTYPE_EPL.to_be(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ethernet_header_is_powerlink() {
let mut header = EthernetHeader::new(MacAddress::new([0; 6]), MacAddress::new([0; 6]));
assert!(header.is_powerlink());
header.ether_type = 0x0800; assert!(!header.is_powerlink());
}
#[test]
fn test_ethernet_header_new() {
let dest_mac = MacAddress::new([0x01, 0x11, 0x1E, 0x00, 0x00, 0x01]);
let src_mac = MacAddress::new([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
let header = EthernetHeader::new(dest_mac, src_mac);
assert_eq!(header.destination_mac, dest_mac);
assert_eq!(header.source_mac, src_mac);
assert_eq!(header.ether_type, C_DLL_ETHERTYPE_EPL.to_be());
}
}