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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
use base64;
use lazy_static::lazy_static;
use ring::rand::{SecureRandom, SystemRandom};
lazy_static! {
static ref RNG: SystemRandom = SystemRandom::new();
}
#[inline(always)]
fn uuid_v4(rng: &dyn SecureRandom) -> [u8; 16] {
let mut bytes = [0u8; 16];
rng.fill(&mut bytes)
.expect("could not generate random values");
bytes[8] = (bytes[8] & 0x3f) | 0x80;
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes
}
#[inline(always)]
fn encode(bytes: &[u8; 16]) -> String {
let mut enc = base64::encode_config(bytes, base64::URL_SAFE);
enc.truncate(22);
enc
}
pub fn v4_rng(rng: &dyn SecureRandom) -> String {
let bytes = uuid_v4(rng);
encode(&bytes)
}
pub fn nice_rng(rng: &dyn SecureRandom) -> String {
let mut bytes = uuid_v4(rng);
bytes[0] = bytes[0] & 0x7f;
encode(&bytes)
}
pub fn v4() -> String {
v4_rng(&*RNG)
}
pub fn nice() -> String {
nice_rng(&*RNG)
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::HashSet;
const CHARS_ALL: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const CHARS_C: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef";
const CHARS_D: &str = "QRST";
const CHARS_E: &str = "CGKOSWaeimquy26-";
const CHARS_F: &str = "AQgw";
fn spread_test(generator: fn() -> String, expected: [&str; 22]) {
let expected: Vec<HashSet<char>> = expected
.iter()
.map(|s| {
let mut set: HashSet<char> = HashSet::new();
for c in s.chars() {
set.insert(c);
}
return set;
})
.collect();
let mut got: Vec<HashSet<char>> = vec![HashSet::new(); 22];
for _ in 0..(64 * 40) {
let slugid = generator();
for (i, c) in slugid.char_indices() {
got[i].insert(c);
}
}
assert_eq!(got, expected);
}
#[test]
fn v4_spread_test() {
let expected = [
CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL,
CHARS_D, CHARS_ALL, CHARS_E, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL,
CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_F,
];
spread_test(v4, expected);
spread_test(|| v4_rng(&SystemRandom::new()), expected);
}
#[test]
fn nice_spread_test() {
let expected = [
CHARS_C, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL,
CHARS_D, CHARS_ALL, CHARS_E, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL,
CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_ALL, CHARS_F,
];
spread_test(nice, expected);
spread_test(|| nice_rng(&SystemRandom::new()), expected);
}
}