1use rand::Rng;
2use std::collections::HashSet;
3use uuid::Uuid;
4use sha2::{Digest, Sha256};
5
6pub fn short_code_from_uuid(uuid: &Uuid) -> String {
8 let mut hasher = Sha256::new();
9 hasher.update(uuid.as_bytes());
10 let hash = hasher.finalize();
11
12 let mut num: u64 = ((hash[0] as u64) << 24)
14 | ((hash[1] as u64) << 16)
15 | ((hash[2] as u64) << 8)
16 | (hash[3] as u64);
17
18 let chars: Vec<char> = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
19 .chars()
20 .collect();
21
22 let mut code = String::new();
23 for _ in 0..6 {
24 code.push(chars[(num % 62) as usize]);
25 num /= 62;
26 }
27 code
28}
29
30pub fn unique_short_code(uuid: &Uuid, existing: &mut HashSet<String>) -> String {
32 let code = short_code_from_uuid(uuid);
33
34 if !existing.contains(&code) {
35 existing.insert(code.clone());
36 return code;
37 }
38
39 let mut rng = rand::thread_rng();
41 let insert_pos = rng.gen_range(1..code.len()); let tweak = if rng.gen_bool(0.5) { '-' } else { '_' };
43
44 let mut chars: Vec<char> = code.chars().collect();
45 chars.insert(insert_pos, tweak);
46 let tweaked: String = chars.into_iter().collect();
47
48 existing.insert(tweaked.clone());
49 tweaked
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55 use std::collections::HashSet;
56 use uuid::Uuid;
57
58 #[test]
59 fn short_code_has_six_chars() {
60 let uuid = Uuid::new_v4();
61 let code = short_code_from_uuid(&uuid);
62 assert_eq!(code.len(), 6);
63 }
64
65 #[test]
66 fn unique_short_code_is_unique() {
67 let uuid = Uuid::new_v4();
68 let mut existing = HashSet::new();
69
70 let code1 = unique_short_code(&uuid, &mut existing);
71 let code2 = unique_short_code(&uuid, &mut existing);
72
73 assert_ne!(code1, code2, "two generated codes should differ if collision");
74 }
75}