use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq)]
pub enum Method {
Static,
Dhcp,
Loopback,
Manual,
Other(String),
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let method_str = match self {
Method::Static => "static",
Method::Dhcp => "dhcp",
Method::Loopback => "loopback",
Method::Manual => "manual",
Method::Other(s) => s.as_str(),
};
write!(f, "{}", method_str)
}
}
impl FromStr for Method {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"static" => Method::Static,
"dhcp" => Method::Dhcp,
"loopback" => Method::Loopback,
"manual" => Method::Manual,
other => Method::Other(other.to_string()),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_method_from_str() {
assert_eq!(Method::from_str("static").unwrap(), Method::Static);
assert_eq!(Method::from_str("dhcp").unwrap(), Method::Dhcp);
assert_eq!(Method::from_str("loopback").unwrap(), Method::Loopback);
assert_eq!(Method::from_str("manual").unwrap(), Method::Manual);
assert_eq!(
Method::from_str("ppp").unwrap(),
Method::Other("ppp".to_string())
);
}
#[test]
fn test_method_display() {
assert_eq!(Method::Static.to_string(), "static");
assert_eq!(Method::Dhcp.to_string(), "dhcp");
assert_eq!(Method::Loopback.to_string(), "loopback");
assert_eq!(Method::Manual.to_string(), "manual");
assert_eq!(Method::Other("ppp".to_string()).to_string(), "ppp");
}
}