rust_rsm/net_ext/
mac_addr.rs1#![allow(non_snake_case)]
2#![allow(non_upper_case_globals)]
3#![allow(non_camel_case_types)]
4
5use super::*;
6use std::fmt;
7use serde::{Serialize,Deserialize};
8#[repr(C)]
9#[derive(Copy, Clone, Eq, PartialEq, Default,Debug,Deserialize,Serialize,Hash)]
10pub struct mac_addr_t {
11 pub a: u8,
12 pub b: u8,
13 pub c: u8,
14 pub d: u8,
15 pub e: u8,
16 pub f: u8,
17}
18const MULTICAST_BIT: u8 = 0x01;
19impl fmt::Display for mac_addr_t {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 write!(f,"{}",self.to_string())
22 }
23}
24impl mac_addr_t {
25 pub fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> mac_addr_t {
26 return mac_addr_t { a, b, c, d, e, f };
27 }
28 pub fn new_broadcast() -> mac_addr_t {
29 return Self::new(0xff, 0xff, 0xff, 0xff, 0xff, 0xff);
30 }
31 pub fn zero() -> mac_addr_t {
32 return Self::new(0, 0, 0, 0, 0, 0);
33 }
34
35 pub fn from_array(addr:&[u8;MAC_ADDR_SIZE])->mac_addr_t {
36 return mac_addr_t {a:addr[0],b:addr[1],c:addr[2],d:addr[3],e:addr[4],f:addr[5]};
37 }
38 pub fn from_slice(addr:&[u8])->mac_addr_t {
39 if addr.len()<MAC_ADDR_SIZE {
40 return Self::new(0, 0, 0, 0, 0, 0);
41 }
42 return mac_addr_t {a:addr[0],b:addr[1],c:addr[2],d:addr[3],e:addr[4],f:addr[5]};
43 }
44 pub fn is_zero(&self)->bool {
45 return self.to_u64()==0
46 }
47 pub fn from_u64(addr: u64) -> mac_addr_t {
48 let p = addr.to_be_bytes();
49
50 return Self::new(p[2], p[3], p[4], p[5], p[6], p[7]);
51 }
52
53 pub fn to_u64(&self) -> u64 {
54 let p: [u8; 8] = [0,0,self.a, self.b, self.c, self.d, self.e, self.f];
55 return u64::from_be_bytes(p)
56 }
57 pub fn to_slice(&self)->&[u8] {
58 let p = unsafe { &*(&self.a as *const u8 as *const [u8;MAC_ADDR_SIZE]) };
59 return p;
60 }
61 pub fn is_broadcast(&self) -> bool {
62 return *self == Self::new_broadcast();
63 }
64 pub fn is_multicast(&self) -> bool {
65 return self.a & MULTICAST_BIT == MULTICAST_BIT;
66 }
67
68 pub fn as_ptr(&self)->*const u8 {
69 std::ptr::addr_of!(self.a)
70 }
71
72 pub fn from_string(mac_str:&String)->Option<Self> {
73 let mac_a:Vec<&str>=mac_str.split(":").collect();
74 if mac_a.len()<6 {
75 return None
76 }
77
78 let mut abytes=[0u8;6];
79
80 for i in 0..6 {
81 abytes[i]=match u8::from_str_radix(mac_a[i], 16) {
82 Ok(v)=>v,
83 Err(_)=>0,
84 }
85 }
86
87 Some(Self::from_array(&abytes))
88 }
89 #[cfg(windows)]
90 pub fn to_string(&self)->String {
91 format!("{:02x}-{:02x}-{:02x}-{:02x}-{:02x}-{:02x}",self.a,self.b,self.c,self.d,self.e,self.f)
92 }
93 #[cfg(unix)]
94 pub fn to_string(&self)->String {
95 format!("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",self.a,self.b,self.c,self.d,self.e,self.f)
96 }
97}