1use rand::Rng;
2
3static CHARACTERS: [char; 36] = [
4 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
5];
6
7pub struct IdGenerator {
8 length: usize,
9}
10
11impl IdGenerator {
12 pub fn new(length: usize) -> Self {
13 Self { length }
14 }
15
16 pub fn generate(&self) -> String {
17 let mut rng = rand::rng();
18 let mut id = String::new();
19 for _ in 0..self.length {
20 id.push(CHARACTERS[rng.random_range(0..CHARACTERS.len())]);
21 }
22 id
23 }
24
25 pub fn generate_unique(&self, existing_ids: &Vec<String>) -> String {
26 let mut id = self.generate();
27 while existing_ids.contains(&id) {
28 id = self.generate();
29 }
30 id
31 }
32}