ckb_util/
strings.rs

1//! Utilities for std strings.
2use regex::Regex;
3
4/// Checks whether the given string is a valid identifier.
5///
6/// This function considers non-empty string containing only alphabets, digits, `-`, and `_` as
7/// a valid identifier.
8///
9/// ## Examples
10///
11/// ```
12/// use ckb_util::strings::check_if_identifier_is_valid;
13///
14/// assert!(check_if_identifier_is_valid("test123").is_ok());
15/// assert!(check_if_identifier_is_valid("123test").is_ok());
16/// assert!(check_if_identifier_is_valid("").is_err());
17/// assert!(check_if_identifier_is_valid("test 123").is_err());
18/// ```
19pub fn check_if_identifier_is_valid(ident: &str) -> Result<(), String> {
20    const IDENT_PATTERN: &str = r#"^[0-9a-zA-Z_-]+$"#;
21    static RE: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
22    // IDENT_PATTERN is a correct regular expression, so unwrap here
23    let re = RE.get_or_init(|| Regex::new(IDENT_PATTERN).unwrap());
24
25    if ident.is_empty() {
26        return Err("the identifier shouldn't be empty".to_owned());
27    }
28    if !re.is_match(ident) {
29        return Err(format!(
30            "Invalid identifier \"{ident}\", the identifier pattern is \"{IDENT_PATTERN}\""
31        ));
32    }
33    Ok(())
34}