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 a76c79a
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions src/server_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ use std::error::Error as StdError;
/// ```
/// # use rustls_pki_types::ServerName;
/// ServerName::try_from("example.com").expect("invalid DNS name");
/// ```
///
/// If you have an owned `String`, you can use `TryFrom` directly:
///
/// ```
/// # use rustls_pki_types::ServerName;
/// let name = "example.com".to_string();
/// #[cfg(feature = "alloc")]
/// ServerName::try_from(name).expect("invalid DNS name");
/// ```
///
/// which will yield a `ServerName<'static>` if successful.
///
/// // or, alternatively...
///
Expand Down Expand Up @@ -74,6 +86,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 +156,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 a76c79a

Please sign in to comment.