ndisapi_rs/netlib/
net.rs

1/// This module provides a type for a MAC address, represented as a 6-byte array of unsigned
2/// integers. It implements `Display` and `Debug` traits for displaying a MAC address in the
3/// standard colon-separated format.
4///
5/// # Example
6///
7/// ```
8/// use ndisapi_rs::MacAddress;
9///
10/// let mac = MacAddress::from_slice(&[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC]).unwrap();
11/// assert_eq!(format!("{}", mac), "12:34:56:78:9A:BC");
12/// assert_eq!(format!("{:?}", mac), "12:34:56:78:9A:BC");
13/// ```
14use std::fmt::{Debug, Display, Formatter, Result};
15
16const ETHER_ADDR_LENGTH: usize = 6;
17
18/// A MAC address represented as a 6-byte array of unsigned integers.
19#[derive(Default, PartialEq, Eq, Clone, Copy, Hash, PartialOrd, Ord)]
20pub struct MacAddress([u8; ETHER_ADDR_LENGTH]);
21
22impl Display for MacAddress {
23    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
24        write!(
25            f,
26            "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
27            self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
28        )
29    }
30}
31
32impl Debug for MacAddress {
33    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
34        write!(
35            f,
36            "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
37            self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
38        )
39    }
40}
41
42impl MacAddress {
43    /// Creates a new `MacAddress` instance from a slice of bytes.
44    ///
45    /// # Arguments
46    ///
47    /// * `slice` - A slice of bytes representing a MAC address.
48    ///
49    /// # Returns
50    ///
51    /// An `Option` containing a `MacAddress` instance if the slice has a length of `ETHER_ADDR_LENGTH`
52    /// bytes, `None` otherwise.
53    pub fn from_slice(slice: &[u8]) -> Option<MacAddress> {
54        let mut mac_address = MacAddress::default();
55        if slice.len() < ETHER_ADDR_LENGTH {
56            None
57        } else {
58            mac_address.0[..ETHER_ADDR_LENGTH].copy_from_slice(&slice[..ETHER_ADDR_LENGTH]);
59            Some(mac_address)
60        }
61    }
62
63    /// Returns a reference to the internal byte array of the `MacAddress` instance.
64    pub fn get(&self) -> &[u8; 6] {
65        &self.0
66    }
67
68    /// Returns a mutable reference to the internal byte array of the `MacAddress` instance.
69    pub fn get_mut(&mut self) -> &mut [u8; 6] {
70        &mut self.0
71    }
72}