I followed @Thomas and @Shepmaster suggestions and it worked. Currently build.rs
generates a const MAP_MACS: [([u8; 6], &str); 29246]
and I wrote a wrapper function called vendor_lookup
around a binary search of the array. However, it would be good to know how to use a HashMap with a custom Hasher.
main.rs
include!(concat!(env!("OUT_DIR"), "/map_oui.rs"));
fn vendor_lookup(mac_oui: &[u8; 6]) -> &'static str {
let idx = MAP_MACS
.binary_search_by(|probe| probe.0.cmp(mac_oui))
.unwrap(); // this should be a `?`
MAP_MACS[idx].1
}
fn main() {
assert_eq!(vendor_lookup(b"4C3C16"), "Samsung Electronics Co.,Ltd");
}
map_oui.rs
const MAP_MACS: [([u8; 6], &str); 29246] = [
([48, 48, 48, 48, 48, 48], "XEROX CORPORATION"),
([48, 48, 48, 48, 48, 49], "XEROX CORPORATION"),
([48, 48, 48, 48, 48, 50], "XEROX CORPORATION"),
//---snip---
]
build.rs
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::path::Path;
fn main() {
let response = ureq::get("http://standards-oui.ieee.org/oui.txt")
.call()
.expect("Conection Error");
let mut reader = BufReader::new(response.into_reader());
let mut data: Vec<(Vec<u8>, String)> = Vec::new();
let mut line = Vec::new();
while reader.read_until(b'
', &mut line).unwrap() != 0 {
if line.get(12..=18).map_or(false, |s| s == b"base 16") {
let mac_oui = line[0..6].to_owned();
let vendor = String::from_utf8_lossy(&line[22..]).trim().to_owned();
data.push((mac_oui, vendor));
}
line.clear();
}
data.sort_unstable();
let out_dir = env::var_os("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("map_oui.rs");
let handle = File::create(dest_path).unwrap();
let mut writer = BufWriter::new(handle);
writeln!(
&mut writer,
"const MAP_MACS: [([u8; 6], &str); {}] = [",
data.len()
)
.unwrap();
for (key, value) in data {
writeln!(&mut writer, " ({:?}, "{}"),", key, value).unwrap();
}
writeln!(&mut writer, "];").unwrap();
writer.flush().unwrap();
println!("cargo:rerun-if-changed=build.rs");
}