From 7a21b713b4701048b7c60378bb1f4668a8461129 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Fri, 10 Jan 2025 15:12:23 -0500 Subject: [PATCH] Avoid allocating for names in the PEP 508 parser (#10476) ## Summary We can read from the slice directly. I don't think this will affect performance today, because `from_str` will then allocate, but it _should_ be a speedup once #10475 merges, since we can then avoid allocating a `String` and go straight from `str` to `ArcStr`. --- crates/uv-pep508/src/lib.rs | 43 ++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/crates/uv-pep508/src/lib.rs b/crates/uv-pep508/src/lib.rs index 95f4a4774..c4b1193a1 100644 --- a/crates/uv-pep508/src/lib.rs +++ b/crates/uv-pep508/src/lib.rs @@ -394,12 +394,9 @@ fn parse_name(cursor: &mut Cursor) -> Result(cursor: &mut Cursor) -> Result { - name.push(char); - cursor.next(); - // [.-_] can't be the final character - if cursor.peek().is_none() && matches!(char, '.' | '-' | '_') { - return Err(Pep508Error { - message: Pep508ErrorSource::String(format!( - "Package name must end with an alphanumeric character, not '{char}'" - )), - start: index, - len: char.len_utf8(), - input: cursor.to_string(), - }); - } - } - Some(_) | None => { - return Ok(PackageName::new(name) - .expect("`PackageName` validation should match PEP 508 parsing")); + if let Some((index, char @ ('A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_'))) = + cursor.peek() + { + cursor.next(); + // [.-_] can't be the final character + if cursor.peek().is_none() && matches!(char, '.' | '-' | '_') { + return Err(Pep508Error { + message: Pep508ErrorSource::String(format!( + "Package name must end with an alphanumeric character, not `{char}`" + )), + start: index, + len: char.len_utf8(), + input: cursor.to_string(), + }); } + } else { + let len = cursor.pos() - start; + return Ok(PackageName::from_str(cursor.slice(start, len)).unwrap()); } } } @@ -1033,7 +1028,7 @@ mod tests { assert_snapshot!( parse_pep508_err("name_"), @" - Package name must end with an alphanumeric character, not '_' + Package name must end with an alphanumeric character, not `_` name_ ^" );