mac: Add MacAddress type

The `MacAddress` structure represents a 48-bit hardware address. Using a
dedicated type instead of an array will make it easier to validate
inputs and ensure type safety.
master
Dustin 2018-08-17 20:12:52 -05:00
parent 8b0ce4c5be
commit c0b462d8ac
3 changed files with 35 additions and 7 deletions

24
src/mac.rs Normal file
View File

@ -0,0 +1,24 @@
use std::num;
pub struct MacAddress {
addr: [u8; 6],
}
impl MacAddress {
pub fn from_string(s: &str) -> Result<Self, num::ParseIntError> {
s.split(":")
.map(|b| u8::from_str_radix(b, 16))
.collect::<Result<Vec<u8>, _>>()
.and_then(|parts| {
let mut addr = [0u8; 6];
addr.copy_from_slice(&parts[..6]);
Ok(MacAddress { addr })
})
}
pub fn as_bytes(&self) -> &[u8; 6] {
&self.addr
}
}

View File

@ -1,15 +1,16 @@
use std::io; use std::io;
use std::net; use std::net;
use mac;
pub struct MagicPacket { pub struct MagicPacket<'a> {
addr: [u8; 6], mac: &'a mac::MacAddress,
} }
impl MagicPacket { impl<'a> MagicPacket<'a> {
pub fn new(addr: [u8; 6]) -> Self { pub fn new(mac: &'a mac::MacAddress) -> Self {
MagicPacket { addr } MagicPacket { mac }
} }
pub fn send(&self) -> io::Result<usize> { pub fn send(&self) -> io::Result<usize> {
@ -46,7 +47,7 @@ impl<'a> Iterator for MagicPacketIterator<'a> {
self.pos += 1; self.pos += 1;
match self.pos { match self.pos {
1 ... 6 => Some(0xff), 1 ... 6 => Some(0xff),
7 ... 103 => Some(self.packet.addr[(self.pos - 7) % 6]), 7 ... 103 => Some(self.packet.mac.as_bytes()[(self.pos - 7) % 6]),
_ => None, _ => None,
} }
} }

View File

@ -1,6 +1,9 @@
mod mac;
mod magic; mod magic;
fn main() { fn main() {
let packet = magic::MagicPacket::new([0x0c, 0x9d, 0x92, 0x0e, 0x3a, 0x41]); let mac = mac::MacAddress::from_string("0c:9d:92:0e:3a:41").unwrap();
let packet = magic::MagicPacket::new(&mac);
packet.send().unwrap(); packet.send().unwrap();
} }