Skip to content

Commit

Permalink
Merge #2982
Browse files Browse the repository at this point in the history
2982: perf: regex new is expensive r=yangby-cryptape,zhangsoledad a=driftluo

### What problem does this PR solve?

regex new is expensive,reinitialization every time enter the function is not a good strategy 

### What is changed and how it works?

use once_cell to wrapper regex

### Release note

```release-note
Title Only: Include only the PR title in the release note.
```



Co-authored-by: driftluo <[email protected]>
  • Loading branch information
bors[bot] and driftluo authored Aug 26, 2021
2 parents 35aa766 + ab7e580 commit 2ca6aa1
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 15 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions util/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ repository = "https://github.com/nervosnetwork/ckb"
parking_lot = "0.11"
linked-hash-map = "0.5"
regex = "1.1.6"
once_cell = "1.8.0"

[dev-dependencies]
ckb-fixed-hash = { path = "fixed-hash", version = "= 0.100.0-pre" }
Expand Down
24 changes: 9 additions & 15 deletions util/src/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,18 @@ use regex::Regex;
/// ```
pub fn check_if_identifier_is_valid(ident: &str) -> Result<(), String> {
const IDENT_PATTERN: &str = r#"^[0-9a-zA-Z_-]+$"#;
static RE: once_cell::sync::OnceCell<Regex> = once_cell::sync::OnceCell::new();
// IDENT_PATTERN is a correct regular expression, so unwrap here
let re = RE.get_or_init(|| Regex::new(IDENT_PATTERN).unwrap());

if ident.is_empty() {
return Err("the identifier shouldn't be empty".to_owned());
}
match Regex::new(IDENT_PATTERN) {
Ok(re) => {
if !re.is_match(&ident) {
return Err(format!(
"invaild identifier \"{}\", the identifier pattern is \"{}\"",
ident, IDENT_PATTERN
));
}
}
Err(err) => {
return Err(format!(
"invalid regular expression \"{}\": {}",
IDENT_PATTERN, err
));
}
if !re.is_match(ident) {
return Err(format!(
"Invalid identifier \"{}\", the identifier pattern is \"{}\"",
ident, IDENT_PATTERN
));
}
Ok(())
}

0 comments on commit 2ca6aa1

Please sign in to comment.