use super::ifname;
pub fn get_ifindex(name: &str) -> Result<u32, String> {
ifname::name_to_index(name).map_err(|e| format!("interface not found: {}", e))
}
pub fn get_ifindex_opt(name: Option<&str>) -> Result<Option<u32>, String> {
match name {
Some(n) => Ok(Some(get_ifindex(n)?)),
None => Ok(None),
}
}
pub fn get_ifname(index: u32) -> Result<String, String> {
ifname::index_to_name(index).map_err(|e| format!("interface not found: {}", e))
}
pub fn get_ifname_or_index(index: u32) -> String {
if index == 0 {
return format!("if{}", index);
}
ifname::index_to_name(index).unwrap_or_else(|_| format!("if{}", index))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_ifindex_lo() {
let result = get_ifindex("lo");
assert!(result.is_ok());
assert_eq!(result.unwrap(), 1); }
#[test]
fn test_get_ifindex_not_found() {
let result = get_ifindex("nonexistent_interface_xyz");
assert!(result.is_err());
assert!(result.unwrap_err().contains("interface not found"));
}
#[test]
fn test_get_ifindex_opt_some() {
let result = get_ifindex_opt(Some("lo"));
assert!(result.is_ok());
assert!(result.unwrap().is_some());
}
#[test]
fn test_get_ifindex_opt_none() {
let result = get_ifindex_opt(None);
assert!(result.is_ok());
assert!(result.unwrap().is_none());
}
#[test]
fn test_get_ifname_or_index() {
assert_eq!(get_ifname_or_index(1), "lo");
let result = get_ifname_or_index(99999);
assert!(result.starts_with("if"));
}
}