Skip to content

Commit

Permalink
convenient implementation TryFrom<&Option<String>> for MacAddress (#983)
Browse files Browse the repository at this point in the history
## Problem

When we parse xml, the address field is optional and we use
`Option<String>` as type. For this it is convenient to have such a
TryFrom implementation as well.

## Testing

- *Added a new unit test*
  • Loading branch information
imobachgs committed Jan 10, 2024
2 parents 62b8c57 + a7bd07b commit a805fc2
Showing 1 changed file with 62 additions and 0 deletions.
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

0 comments on commit a805fc2

Please sign in to comment.