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) } }