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
use hex::encode;
use rand::Rng;

/// Generates 8-byte UUID as a String
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
    )
}

/// Generates 16-byte UUID as a String
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
    )
}

/// Generates 32-byte UUID as a String
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();

    // 8 * 2 bytes + 4 dashes
    assert_eq!(id.len(), 20);
}

#[test]
fn test_uuid16() {
    let id: String = uuid16();

    // 16 * 2 bytes + 4 dashes
    assert_eq!(id.len(), 36);
}

#[test]
fn test_uuid32() {
    let id: String = uuid32();

    // 32 * 2 bytes + 4 dashes
    assert_eq!(id.len(), 68);
}