Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convenient implementation TryFrom<&Option<String>> for MacAddress #983

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions rust/agama-dbus-server/src/network/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,57 @@ mod tests {
use crate::network::error::NetworkStateError;
use uuid::Uuid;

#[test]
fn test_macaddress() {
let mut val: Option<String> = None;
assert!(matches!(
MacAddress::try_from(&val).unwrap(),
MacAddress::Unset
));

val = Some(String::from(""));
assert!(matches!(
MacAddress::try_from(&val).unwrap(),
MacAddress::Unset
));

val = Some(String::from("preserve"));
assert!(matches!(
MacAddress::try_from(&val).unwrap(),
MacAddress::Preserve
));

val = Some(String::from("permanent"));
assert!(matches!(
MacAddress::try_from(&val).unwrap(),
MacAddress::Permanent
));

val = Some(String::from("random"));
assert!(matches!(
MacAddress::try_from(&val).unwrap(),
MacAddress::Random
));

val = Some(String::from("stable"));
assert!(matches!(
MacAddress::try_from(&val).unwrap(),
MacAddress::Stable
));

val = Some(String::from("This is not a MACAddr"));
assert!(matches!(
MacAddress::try_from(&val),
Err(InvalidMacAddress(_))
));

val = Some(String::from("de:ad:be:ef:2b:ad"));
assert_eq!(
MacAddress::try_from(&val).unwrap().to_string(),
String::from("de:ad:be:ef:2b:ad").to_uppercase()
);
}

#[test]
fn test_add_connection() {
let mut state = NetworkState::default();
Expand Down Expand Up @@ -457,6 +508,17 @@ impl FromStr for MacAddress {
}
}

impl TryFrom<&Option<String>> for MacAddress {
type Error = InvalidMacAddress;

fn try_from(value: &Option<String>) -> Result<Self, Self::Error> {
match &value {
Some(str) => MacAddress::from_str(str),
None => Ok(Self::Unset),
}
}
}

impl fmt::Display for MacAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let output = match &self {
Expand Down