use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum InterfaceRef {
Name(String),
Index(u32),
}
impl InterfaceRef {
#[inline]
pub fn name(name: impl Into<String>) -> Self {
Self::Name(name.into())
}
#[inline]
pub fn index(index: u32) -> Self {
Self::Index(index)
}
#[inline]
pub fn is_name(&self) -> bool {
matches!(self, Self::Name(_))
}
#[inline]
pub fn is_index(&self) -> bool {
matches!(self, Self::Index(_))
}
#[inline]
pub fn as_name(&self) -> Option<&str> {
match self {
Self::Name(name) => Some(name),
Self::Index(_) => None,
}
}
#[inline]
pub fn as_index(&self) -> Option<u32> {
match self {
Self::Name(_) => None,
Self::Index(idx) => Some(*idx),
}
}
}
impl fmt::Display for InterfaceRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Name(name) => write!(f, "{}", name),
Self::Index(idx) => write!(f, "ifindex:{}", idx),
}
}
}
impl From<&str> for InterfaceRef {
#[inline]
fn from(name: &str) -> Self {
Self::Name(name.to_string())
}
}
impl From<String> for InterfaceRef {
#[inline]
fn from(name: String) -> Self {
Self::Name(name)
}
}
impl From<&String> for InterfaceRef {
#[inline]
fn from(name: &String) -> Self {
Self::Name(name.clone())
}
}
impl From<u32> for InterfaceRef {
#[inline]
fn from(index: u32) -> Self {
Self::Index(index)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_interface_ref_name() {
let iface = InterfaceRef::name("eth0");
assert!(iface.is_name());
assert!(!iface.is_index());
assert_eq!(iface.as_name(), Some("eth0"));
assert_eq!(iface.as_index(), None);
assert_eq!(iface.to_string(), "eth0");
}
#[test]
fn test_interface_ref_index() {
let iface = InterfaceRef::index(42);
assert!(!iface.is_name());
assert!(iface.is_index());
assert_eq!(iface.as_name(), None);
assert_eq!(iface.as_index(), Some(42));
assert_eq!(iface.to_string(), "ifindex:42");
}
#[test]
fn test_from_str() {
let iface: InterfaceRef = "eth0".into();
assert_eq!(iface, InterfaceRef::Name("eth0".to_string()));
}
#[test]
fn test_from_string() {
let iface: InterfaceRef = String::from("eth0").into();
assert_eq!(iface, InterfaceRef::Name("eth0".to_string()));
}
#[test]
fn test_from_u32() {
let iface: InterfaceRef = 42u32.into();
assert_eq!(iface, InterfaceRef::Index(42));
}
#[test]
fn test_equality() {
assert_eq!(InterfaceRef::name("eth0"), InterfaceRef::name("eth0"));
assert_eq!(InterfaceRef::index(1), InterfaceRef::index(1));
assert_ne!(InterfaceRef::name("eth0"), InterfaceRef::index(1));
}
}