Improve perf, add tests

This commit is contained in:
cool-mist
2026-06-29 16:36:57 +05:30
parent a3da2a5a37
commit faf8238875
+46 -10
View File
@@ -1,28 +1,64 @@
use std::env::args;
use std::net::UdpSocket;
fn get_magic_pkt(mac: &String) -> [u8; 102] {
fn get_magic_pkt(mac: &str, magic_bytes: &mut [u8; 102]) {
let mut mac_bytes = [0u8; 6];
let mut magic_bytes = [0u8; 102];
magic_bytes[..6].fill(0xFF);
for (i, part) in mac.split(':').enumerate() {
mac_bytes[i] = u8::from_str_radix(part, 16).unwrap();
mac_bytes[i] = u8::from_str_radix(part, 16)
.expect(&format!("'{}' is not a valid hex between 00-ff", part));
}
magic_bytes[..6].fill(0xFF);
for i in 0..16 {
let start = 6 + i * 6;
magic_bytes[start..start + 6].copy_from_slice(&mac_bytes);
}
magic_bytes
}
fn main() {
let mac = args().nth(1).expect("no mac given; Usage woly aa:bb:cc:dd:ee:ff");
let magic_bytes = get_magic_pkt(&mac);
let mac = args()
.nth(1)
.expect("no mac given; Usage woly aa:bb:cc:dd:ee:ff");
let mut magic_bytes = [0u8; 102];
get_magic_pkt(&mac, &mut magic_bytes);
let socket = UdpSocket::bind("0.0.0.0:0").expect("couldnt' bind socket");
socket.set_broadcast(true).expect("couldn't set broadcast");
socket.send_to(&magic_bytes, "255.255.255.255:9").expect("couldn't send data");
socket
.send_to(&magic_bytes, "255.255.255.255:9")
.expect("couldn't send data");
println!("Magic packet sent to 255.255.255.255:9 for Mac {:?}", mac);
}
#[cfg(test)]
mod tests {
use crate::get_magic_pkt;
#[test]
fn test_magic_bytes_for_mac() {
let mut magic_bytes = [0u8; 102];
get_magic_pkt("32:1a:ff:3e:10:ef", &mut magic_bytes);
let expected = [
255, 255, 255, 255, 255, 255,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
50, 26, 255, 62, 16, 239,
];
assert_eq!(magic_bytes, expected, "Magic bytes are not created correctly");
}
}