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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#![feature(test)]
#![feature(no_more_cas)]
use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize};
#[macro_use]
extern crate lazy_static;
extern crate hostname;
extern crate rand;
extern crate test;
mod counter;
mod error;
mod fingerprint;
mod random;
mod text;
mod time;
pub use error::CuidError;
static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
static BASE: u8 = 36;
static BLOCK_SIZE: u8 = 4;
static DISCRETE_VALUES: u32 = 1679616;
static START_STR: &str = "c";
lazy_static! {
static ref FINGERPRINT: String = fingerprint::fingerprint().unwrap().into();
}
pub fn cuid() -> Result<String, CuidError> {
Ok([
START_STR,
&time::timestamp()?,
&counter::current()?,
&FINGERPRINT,
&random::random_block()?,
&random::random_block()?,
].concat())
}
pub fn slug() -> Result<String, CuidError> {
let timestamp = time::timestamp()?;
let count = counter::current()?;
let rand = random::random_block()?;
Ok([
×tamp[timestamp.len()-2..],
&count[count.len().saturating_sub(4)..],
&FINGERPRINT[..1],
&FINGERPRINT[FINGERPRINT.len()-1..],
&rand[rand.len()-2..],
].concat())
}
pub fn is_cuid<S: Into<String>>(to_check: S) -> bool {
&to_check.into()[..1] == START_STR
}
pub fn is_slug<S: Into<String>>(to_check: S) -> bool {
let length = to_check.into().len();
length >= 7 && length <=10
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correct_discrete_values() {
assert_eq!(
(BASE as u32).pow(BLOCK_SIZE as u32),
DISCRETE_VALUES,
);
}
#[test]
fn cuid_is_cuid() {
assert!(is_cuid(cuid().unwrap()));
}
#[test]
fn slug_max_len() {
assert!(slug().unwrap().len() <= 10);
}
#[test]
fn slug_min_len() {
assert!(slug().unwrap().len() >= 7);
}
#[test]
fn slug_is_slug() {
assert!(is_slug(slug().unwrap()));
}
}
#[cfg(test)]
mod benchmarks {
use test::Bencher;
use super::*;
#[bench]
fn bench_cuid(b: &mut Bencher) {
b.iter(|| {
cuid().unwrap();
})
}
#[bench]
fn bench_slug(b: &mut Bencher) {
b.iter(|| {
slug().unwrap();
})
}
}