diff --git a/Cargo.lock b/Cargo.lock index 2822920785d..bba48e09dc6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,5 +1,7 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + [[package]] name = "addr2line" version = "0.15.2" @@ -1306,6 +1308,7 @@ version = "0.100.0-pre" dependencies = [ "ckb-fixed-hash", "linked-hash-map", + "once_cell", "parking_lot", "regex", ] diff --git a/util/Cargo.toml b/util/Cargo.toml index 6eb60155f8c..f55ba166a1a 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -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" } diff --git a/util/src/strings.rs b/util/src/strings.rs index be51674a621..d124cc0926c 100644 --- a/util/src/strings.rs +++ b/util/src/strings.rs @@ -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 = 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(()) }