Skip to content

Commit

Permalink
When parsing dns Names, avoid iterating each character twice
Browse files Browse the repository at this point in the history
Speed up parsing of `Name` objects by building up labels and converting
to lowercase at the same time we validate that each character is ASCII.
  • Loading branch information
56quarters committed Jun 23, 2024
1 parent 713dc12 commit 69d505c
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion mtop-client/src/dns/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,9 @@ impl FromStr for Name {
}

let is_fqdn = s.ends_with('.');
let mut buf = String::new();
let mut labels = Vec::new();

for label in s.trim_end_matches('.').split('.') {
let len = label.len();
if len > Self::MAX_LABEL_LENGTH {
Expand All @@ -245,6 +247,8 @@ impl FromStr for Name {
)));
}

buf.clear();

for (i, c) in label.char_indices() {
if i == 0 && !c.is_ascii_alphanumeric() && c != '_' {
return Err(MtopError::runtime(format!(
Expand All @@ -261,10 +265,16 @@ impl FromStr for Name {
"Name label must be ASCII letter, number, hyphen, or underscore; got {}",
label
)));
} else {
// If this character isn't otherwise invalid, convert it to lowercase
// and add it to our buffer which will be added to the list of labels
// for this Name. This avoids an extra iteration through the Name to
// convert to lowercase afterward.
buf.push(c.to_ascii_lowercase());
}
}

labels.push(label.to_lowercase());
labels.push(buf.clone());
}

Ok(Name { labels, is_fqdn })
Expand Down

0 comments on commit 69d505c

Please sign in to comment.