stry_common/utils/
nanoid.rs

1#[cfg(feature = "with-nanoid")]
2use {
3    crate::models::Id,
4    arrayvec::ArrayString,
5    rand::{rngs::StdRng, Rng as _, SeedableRng as _},
6    std::panic,
7};
8
9/// How long an entity `Id` is, recommended 6 or above.
10///
11/// # Note
12///
13/// This is only used in the [`Id`] type as its length parameter and with the
14/// [`nanoid`] output length.
15///
16/// [`Id`]: crate::models::Id
17pub const SIZE: usize = 6;
18
19#[cfg(feature = "with-nanoid")]
20const LEN: usize = 54;
21#[cfg(feature = "with-nanoid")]
22const MASK: usize = LEN.next_power_of_two() - 1;
23#[cfg(feature = "with-nanoid")]
24const STEP: usize = 8 * SIZE / 5;
25
26#[cfg(feature = "with-nanoid")]
27static ALPHABET: [char; LEN] = [
28    '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
29    'm', 'n', 'p', 'q', 'r', 's', 't', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
30    'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
31];
32
33/// Returns a new [`Id`] generated using [nanoid](https://github.com/ai/nanoid) with a custom alphabet.
34///
35/// Customized version of [the Rust version](https://github.com/nikolay-govorov/nanoid).
36#[cfg(feature = "with-nanoid")]
37pub fn nanoid() -> Option<Id> {
38    let mut id = ArrayString::<[u8; SIZE]>::new();
39
40    loop {
41        // `SeedableRng::from_entropy` can panic if getrandom fails, not sure
42        // the situation in which that could happen but I want to catch it just incase.
43        let mut rng = panic::catch_unwind(StdRng::from_entropy).ok()?;
44        let mut bytes = [0u8; STEP];
45
46        rng.fill(&mut bytes[..]);
47
48        for &byte in &bytes {
49            let byte = byte as usize & MASK;
50
51            if ALPHABET.len() > byte {
52                id.push(ALPHABET[byte]);
53
54                if id.len() == SIZE {
55                    return Some(Id(id));
56                }
57            }
58        }
59    }
60}