Skip to main content

auth_framework/utils/
string.rs

1//! String utility functions for the AuthFramework.
2
3use rand::{RngExt, rng};
4
5/// Generate a random ID with optional prefix
6pub fn generate_id(prefix: Option<&str>) -> String {
7    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
8                             abcdefghijklmnopqrstuvwxyz\
9                             0123456789";
10    let random_part: String = (0..16)
11        .map(|_| {
12            let idx = rng().random_range(0..CHARSET.len());
13            CHARSET[idx] as char
14        })
15        .collect();
16
17    match prefix {
18        Some(p) => format!("{}_{}", p, random_part),
19        None => random_part,
20    }
21}
22/// Generate a UUID-like string
23pub fn generate_uuid() -> String {
24    uuid::Uuid::new_v4().to_string()
25}
26
27/// Sanitize a string for safe use in IDs or filenames
28pub fn sanitize_string(input: &str) -> String {
29    input
30        .chars()
31        .filter(|c| c.is_alphanumeric() || *c == '_' || *c == '-')
32        .collect()
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_generate_id() {
41        let id = generate_id(None);
42        assert_eq!(id.len(), 16);
43
44        let prefixed_id = generate_id(Some("test"));
45        assert!(prefixed_id.starts_with("test_"));
46        assert_eq!(prefixed_id.len(), 21); // "test_" + 16 chars
47    }
48
49    #[test]
50    fn test_generate_uuid() {
51        let uuid = generate_uuid();
52        assert_eq!(uuid.len(), 36); // Standard UUID length
53        assert!(uuid.contains('-'));
54    }
55
56    #[test]
57    fn test_sanitize_string() {
58        let input = "hello@world!#$%";
59        let sanitized = sanitize_string(input);
60        assert_eq!(sanitized, "helloworld");
61    }
62}