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
use hex::encode;
use rand::Rng;
pub mod iso {
use super::encode;
use super::Rng;
pub fn uuid_v4() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 6]>()),
);
format!(
"{}-{}-4{}-{}-{}",
bytes.0,
bytes.1,
&bytes.2[1..],
bytes.3,
bytes.4
)
}
}
pub const NULL_UUID: &str = "00000000-0000-0000-0000-000000000000";
pub fn uuid8() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 1]>()),
encode(rand::thread_rng().gen::<[u8; 1]>()),
encode(rand::thread_rng().gen::<[u8; 1]>()),
encode(rand::thread_rng().gen::<[u8; 3]>()),
);
format!(
"{}-{}-{}-{}-{}",
bytes.0, bytes.1, bytes.2, bytes.3, bytes.4
)
}
pub fn uuid16() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 6]>()),
);
format!(
"{}-{}-{}-{}-{}",
bytes.0, bytes.1, bytes.2, bytes.3, bytes.4
)
}
pub fn uuid32() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 8]>()),
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 12]>()),
);
format!(
"{}-{}-{}-{}-{}",
bytes.0, bytes.1, bytes.2, bytes.3, bytes.4
)
}
#[cfg(test)]
#[test]
fn test_uuid8() {
let id: String = uuid8();
assert_eq!(id.len(), 20);
}
#[test]
fn test_uuid16() {
let id: String = uuid16();
assert_eq!(id.len(), 36);
}
#[test]
fn test_uuid32() {
let id: String = uuid32();
assert_eq!(id.len(), 68);
}
#[test]
fn test_iso_uuid_v4() {
use self::iso::uuid_v4;
let iso_v4_uuid = uuid_v4();
assert_eq!(iso_v4_uuid.len(), 36);
assert_eq!(iso_v4_uuid.as_bytes()[14] as char, '4');
}