Skip to content

Commit

Permalink
Add a TryFrom<String> for ServerName<'static> impl
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Dec 5, 2023
1 parent 67fb73f commit 192afd8
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/server_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,20 @@ impl<'a> fmt::Debug for ServerName<'a> {
}
}

impl<'a> TryFrom<String> for ServerName<'static> {
type Error = InvalidDnsNameError;

fn try_from(value: String) -> Result<Self, Self::Error> {
match DnsName::try_from_string(value) {
Ok(dns) => Ok(Self::DnsName(dns)),
Err(value) => match IpAddr::try_from(value.as_str()) {
Ok(ip) => Ok(Self::IpAddress(ip)),
Err(_) => Err(InvalidDnsNameError),
},
}
}
}

impl<'a> TryFrom<&'a [u8]> for ServerName<'a> {
type Error = InvalidDnsNameError;

Expand Down Expand Up @@ -129,15 +143,21 @@ impl<'a> DnsName<'a> {
Self(DnsNameInner::Owned(s)) => s.clone(),
}))
}

fn try_from_string(s: String) -> Result<Self, String> {
match validate(s.as_bytes()) {
Ok(_) => Ok(Self(DnsNameInner::Owned(s))),
Err(_) => Err(s),
}
}
}

#[cfg(feature = "alloc")]
impl TryFrom<String> for DnsName<'static> {
type Error = InvalidDnsNameError;

fn try_from(value: String) -> Result<Self, Self::Error> {
validate(value.as_bytes())?;
Ok(Self(DnsNameInner::Owned(value)))
Self::try_from_string(value).map_err(|_| InvalidDnsNameError)
}
}

Expand Down

0 comments on commit 192afd8

Please sign in to comment.