ckb_util/strings.rs
1//! Utilities for std strings.
2
3/// Checks whether the given string is a valid identifier.
4///
5/// This function considers non-empty string containing only alphabets, digits, `-`, and `_` as
6/// a valid identifier.
7///
8/// ## Examples
9///
10/// ```
11/// use ckb_util::strings::check_if_identifier_is_valid;
12///
13/// assert!(check_if_identifier_is_valid("test123").is_ok());
14/// assert!(check_if_identifier_is_valid("123test").is_ok());
15/// assert!(check_if_identifier_is_valid("").is_err());
16/// assert!(check_if_identifier_is_valid("test 123").is_err());
17/// ```
18pub fn check_if_identifier_is_valid(ident: &str) -> Result<(), String> {
19    if ident.is_empty() {
20        return Err("the identifier shouldn't be empty".to_owned());
21    }
22    if ident
23        .chars()
24        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
25    {
26        Ok(())
27    } else {
28        Err(format!(
29            "Invalid identifier \"{ident}\", the identifier can only contain alphabets, digits, `-`, and `_`"
30        ))
31    }
32}