1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#[cfg(feature = "with-nanoid")]
use {
crate::models::Id,
arrayvec::ArrayString,
rand::{rngs::StdRng, Rng as _, SeedableRng as _},
std::panic,
};
pub const SIZE: usize = 6;
#[cfg(feature = "with-nanoid")]
const LEN: usize = 54;
#[cfg(feature = "with-nanoid")]
const MASK: usize = LEN.next_power_of_two() - 1;
#[cfg(feature = "with-nanoid")]
const STEP: usize = 8 * SIZE / 5;
#[cfg(feature = "with-nanoid")]
static ALPHABET: [char; LEN] = [
'2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'm', 'n', 'p', 'q', 'r', 's', 't', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
#[cfg(feature = "with-nanoid")]
pub fn nanoid() -> Option<Id> {
let mut id = ArrayString::<[u8; SIZE]>::new();
loop {
let mut rng = panic::catch_unwind(StdRng::from_entropy).ok()?;
let mut bytes = [0u8; STEP];
rng.fill(&mut bytes[..]);
for &byte in &bytes {
let byte = byte as usize & MASK;
if ALPHABET.len() > byte {
id.push(ALPHABET[byte]);
if id.len() == SIZE {
return Some(Id(id));
}
}
}
}
}