Skip to content

Commit

Permalink
Slight speed-up for lowercase and uppercase identifier checks
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Feb 2, 2024
1 parent ee5b07d commit 1674ce2
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions crates/ruff_python_stdlib/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,20 @@
/// assert!(is_lowercase("_"));
/// ```
pub fn is_lowercase(s: &str) -> bool {
s.chars().all(|c| !c.is_alphabetic() || c.is_lowercase())
for (i, &c) in s.as_bytes().iter().enumerate() {
match c {
// Match against ASCII uppercase characters.
b'A'..=b'Z' => return false,
_ if c.is_ascii() => {}
// If the character is non-ASCII, fallback to slow path.
_ => {
return s[i..]
.chars()
.all(|c| c.is_lowercase() || !c.is_alphabetic())
}
}
}
true
}

/// Return `true` if a string is uppercase.
Expand All @@ -37,7 +50,20 @@ pub fn is_lowercase(s: &str) -> bool {
/// assert!(is_uppercase("_"));
/// ```
pub fn is_uppercase(s: &str) -> bool {
s.chars().all(|c| !c.is_alphabetic() || c.is_uppercase())
for (i, &c) in s.as_bytes().iter().enumerate() {
match c {
// Match against ASCII lowercase characters.
b'a'..=b'z' => return false,
_ if c.is_ascii() => {}
// If the character is non-ASCII, fallback to slow path.
_ => {
return s[i..]
.chars()
.all(|c| c.is_uppercase() || !c.is_alphabetic())
}
}
}
true
}

/// Return `true` if a string is _cased_ as lowercase.
Expand Down

0 comments on commit 1674ce2

Please sign in to comment.