From eef23541bef97f8e1c715c53ec1e4627621716ba Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Tue, 5 Dec 2023 17:37:07 +0100 Subject: [PATCH] Add a TryFrom for ServerName<'static> impl --- src/server_name.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/server_name.rs b/src/server_name.rs index 1b08c1c..a10cd03 100644 --- a/src/server_name.rs +++ b/src/server_name.rs @@ -74,6 +74,21 @@ impl<'a> fmt::Debug for ServerName<'a> { } } +#[cfg(feature = "alloc")] +impl TryFrom for ServerName<'static> { + type Error = InvalidDnsNameError; + + fn try_from(value: String) -> Result { + 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; @@ -129,6 +144,14 @@ impl<'a> DnsName<'a> { Self(DnsNameInner::Owned(s)) => s.clone(), })) } + + #[cfg(feature = "alloc")] + fn try_from_string(s: String) -> Result { + match validate(s.as_bytes()) { + Ok(_) => Ok(Self(DnsNameInner::Owned(s))), + Err(_) => Err(s), + } + } } #[cfg(feature = "alloc")] @@ -136,8 +159,7 @@ impl TryFrom for DnsName<'static> { type Error = InvalidDnsNameError; fn try_from(value: String) -> Result { - validate(value.as_bytes())?; - Ok(Self(DnsNameInner::Owned(value))) + Self::try_from_string(value).map_err(|_| InvalidDnsNameError) } }