From 192afd89f3a88a3c6532c97f163c02c96217c301 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 | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/server_name.rs b/src/server_name.rs index 1b08c1c..f428a19 100644 --- a/src/server_name.rs +++ b/src/server_name.rs @@ -74,6 +74,20 @@ impl<'a> fmt::Debug for ServerName<'a> { } } +impl<'a> 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 +143,13 @@ impl<'a> DnsName<'a> { Self(DnsNameInner::Owned(s)) => s.clone(), })) } + + 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 +157,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) } }