headless_lms_utils/
strings.rs

1use once_cell::sync::Lazy;
2use rand::{Rng, distr::Alphanumeric, rng};
3use regex::Regex;
4
5static IETF_LANGUAGE_CODE_REGEX: Lazy<Regex> = Lazy::new(|| {
6    Regex::new(r"^[a-z]{2,3}(-[A-Z][a-z]{3})?-[A-Z]{2}$")
7        .expect("Invalid IETF language code regex.")
8});
9
10pub fn generate_random_string(length: usize) -> String {
11    rng()
12        .sample_iter(Alphanumeric)
13        .take(length)
14        .map(char::from)
15        .collect()
16}
17
18pub fn generate_easily_writable_random_string(length: usize) -> String {
19    rng()
20        .sample_iter(Alphanumeric)
21        .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
22        // Filter out characters that might be confused with each other
23        .filter(|c| c != &b'l' && c != &b'1' && c != &b'o' && c != &b'0')
24        .take(length)
25        .map(char::from)
26        .collect()
27}
28
29/// Checks whether the string is IETF language code where subtags are separated with underscore.
30pub fn is_ietf_language_code_like(string: &str) -> bool {
31    IETF_LANGUAGE_CODE_REGEX.is_match(string)
32}
33
34#[cfg(test)]
35mod test {
36    use super::*;
37
38    #[test]
39    fn ietf_language_code_validation_works() {
40        // Invalid scenarios
41        assert!(!is_ietf_language_code_like(""));
42        assert!(!is_ietf_language_code_like("en"));
43        assert!(!is_ietf_language_code_like("en_us"));
44        assert!(!is_ietf_language_code_like("en_US"));
45        assert!(!is_ietf_language_code_like("in-cans"));
46        assert!(!is_ietf_language_code_like("in-cans-ca"));
47
48        // Valid scenarios
49        assert!(is_ietf_language_code_like("en-US"));
50        assert!(is_ietf_language_code_like("in-Cans-CA"));
51    }
52}