Skip to content

Commit

Permalink
feat: add const try_from_str constructor to DnsName type.
Browse files Browse the repository at this point in the history
  • Loading branch information
DSharifi committed Jan 24, 2025
1 parent c6b5af3 commit b7c5b4e
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/server_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,14 @@ impl<'a> DnsName<'a> {
Err(_) => Err(s),
}
}

/// Produces a borrowed [`DnsName`] from a borrowed [`str`].
pub const fn try_from_str(s: &str) -> Result<DnsName<'_>, InvalidDnsNameError> {
match validate(s.as_bytes()) {
Ok(_) => Ok(DnsName(DnsNameInner::Borrowed(s))),
Err(_) => Err(InvalidDnsNameError),
}
}
}

#[cfg(feature = "alloc")]
Expand Down Expand Up @@ -300,7 +308,7 @@ impl fmt::Display for InvalidDnsNameError {
#[cfg(feature = "std")]
impl StdError for InvalidDnsNameError {}

fn validate(input: &[u8]) -> Result<(), InvalidDnsNameError> {
const fn validate(input: &[u8]) -> Result<(), InvalidDnsNameError> {
enum State {
Start,
Next,
Expand All @@ -323,7 +331,9 @@ fn validate(input: &[u8]) -> Result<(), InvalidDnsNameError> {
return Err(InvalidDnsNameError);
}

for ch in input {
let mut character_index = 0;
while character_index < input.len() {
let ch = input[character_index];
state = match (state, ch) {
(Start | Next | NextAfterNumericOnly | Hyphen { .. }, b'.') => {
return Err(InvalidDnsNameError)
Expand All @@ -349,6 +359,7 @@ fn validate(input: &[u8]) -> Result<(), InvalidDnsNameError> {
) => Subsequent { len: len + 1 },
_ => return Err(InvalidDnsNameError),
};
character_index += 1;
}

if matches!(
Expand Down

0 comments on commit b7c5b4e

Please sign in to comment.