Skip to content

Commit 1da0b55

Browse files
authored
Merge pull request #5 from linkmauve/fix-nameprep-ascii-check
Fix the fast path for nameprep
2 parents 8887482 + 914d6ff commit 1da0b55

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/lib.rs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ fn is_prohibited_bidirectional_text(s: &str) -> bool {
126126
pub fn nameprep(s: &str) -> Result<Cow<'_, str>, Error> {
127127
// fast path for ascii text
128128
if s.chars()
129-
.all(|c| c.is_ascii_lowercase() && !tables::ascii_control_character(c))
129+
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '-')
130130
{
131131
return Ok(Cow::Borrowed(s));
132132
}
@@ -179,12 +179,10 @@ pub fn nameprep(s: &str) -> Result<Cow<'_, str>, Error> {
179179
///
180180
/// [RFC 3920, Appendix A]: https://tools.ietf.org/html/rfc3920#appendix-A
181181
pub fn nodeprep(s: &str) -> Result<Cow<'_, str>, Error> {
182-
// fast path for ascii text
183-
if s.chars().all(|c| {
184-
c.is_ascii_lowercase()
185-
&& !tables::ascii_control_character(c)
186-
&& !prohibited_node_character(c)
187-
}) {
182+
// fast path for common ascii text
183+
if s.chars()
184+
.all(|c| matches!(c, '['..='~' | '0'..='9' | '('..='.' | '#'..='%'))
185+
{
188186
return Ok(Cow::Borrowed(s));
189187
}
190188

@@ -248,7 +246,7 @@ fn prohibited_node_character(c: char) -> bool {
248246
pub fn resourceprep(s: &str) -> Result<Cow<'_, str>, Error> {
249247
// fast path for ascii text
250248
if s.chars()
251-
.all(|c| c.is_ascii() && !tables::ascii_control_character(c))
249+
.all(|c| matches!(c, ' '..='~'))
252250
{
253251
return Ok(Cow::Borrowed(s));
254252
}
@@ -323,4 +321,17 @@ mod test {
323321
fn resourceprep_examples() {
324322
assert_eq!("foo@bar", resourceprep("foo@bar").unwrap());
325323
}
324+
325+
#[test]
326+
fn ascii_optimisations() {
327+
if let Cow::Owned(_) = nodeprep("nodepart").unwrap() {
328+
panic!("“nodepart” should get optimised as ASCII");
329+
}
330+
if let Cow::Owned(_) = nameprep("domainpart.example").unwrap() {
331+
panic!("“domainpart.example” should get optimised as ASCII");
332+
}
333+
if let Cow::Owned(_) = resourceprep("resourcepart").unwrap() {
334+
panic!("“resourcepart” should get optimised as ASCII");
335+
}
336+
}
326337
}

0 commit comments

Comments
 (0)