Skip to content

Commit 40e16a4

Browse files
authored
perf: only compile regexes once (#110)
1 parent efc4b62 commit 40e16a4

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

pyproject-fmt/rust/src/project.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use lexical_sort::natural_lexical_cmp;
1313
use regex::Regex;
1414
use std::cell::RefMut;
1515
use std::cmp::Ordering;
16+
use std::sync::LazyLock;
1617

1718
pub fn fix(
1819
tables: &mut Tables,
@@ -27,7 +28,7 @@ pub fn fix(
2728
return;
2829
}
2930
let table = &mut table_element.unwrap().first().unwrap().borrow_mut();
30-
let re = Regex::new(r" \.(\W)").unwrap();
31+
static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r" \.(\W)").unwrap());
3132
expand_entry_points_inline_tables(table);
3233
for_entries(table, &mut |key, entry| match key.split('.').next().unwrap() {
3334
"name" => {
@@ -38,7 +39,7 @@ pub fn fix(
3839
}
3940
"description" => {
4041
update_content(entry, |s| {
41-
re.replace_all(
42+
RE.replace_all(
4243
&s.trim()
4344
.lines()
4445
.map(|part| {
@@ -88,8 +89,8 @@ pub fn fix(
8889
}
8990
"import-names" | "import-namespaces" => {
9091
transform(entry, &|s| {
91-
let re = Regex::new(r"\s*;\s*").unwrap();
92-
re.replace_all(s, "; ").trim_end().to_string()
92+
static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s*;\s*").unwrap());
93+
RE.replace_all(s, "; ").trim_end().to_string()
9394
});
9495
sort_strings::<String, _, _>(entry, |s| s.to_lowercase(), &|lhs, rhs| natural_lexical_cmp(lhs, rhs));
9596
}
@@ -398,12 +399,13 @@ fn get_python_requires_with_classifier(
398399

399400
for_entries(table, &mut |key, entry| {
400401
if key == "requires-python" {
401-
let re = Regex::new(r"^(?<op><|<=|==|!=|>=|>)3[.](?<minor>\d+)").unwrap();
402+
static RE: LazyLock<Regex> =
403+
LazyLock::new(|| Regex::new(r"^(?<op><|<=|==|!=|>=|>)3[.](?<minor>\d+)").unwrap());
402404
for child in entry.children_with_tokens() {
403405
if child.kind() == STRING {
404406
let found_str_value = load_text(child.as_token().unwrap().text(), STRING);
405407
for part in found_str_value.split(',') {
406-
if let Some(caps) = re.captures(part) {
408+
if let Some(caps) = RE.captures(part) {
407409
let minor = caps["minor"].parse::<u8>().unwrap();
408410
match &caps["op"] {
409411
"==" => {

0 commit comments

Comments
 (0)