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 ec5f4bd commit eef2354
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/server_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,21 @@ impl<'a> fmt::Debug for ServerName<'a> {
}
}

#[cfg(feature = "alloc")]
impl 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 +144,22 @@ impl<'a> DnsName<'a> {
Self(DnsNameInner::Owned(s)) => s.clone(),
}))
}

#[cfg(feature = "alloc")]
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 eef2354

Please sign in to comment.