base62_uuid/
lib.rs

1use uuid::Uuid;
2
3/// Generate a Base62 UUID
4#[must_use]
5pub fn base62_uuid(pad: bool) -> String {
6    zero_pad(&base62::encode(Uuid::new_v4().as_u128()), pad, 22)
7}
8
9/// Generate a u128 UUID
10#[must_use]
11pub fn u128_uuid(pad: bool) -> String {
12    zero_pad(&Uuid::new_v4().as_u128().to_string(), pad, 39)
13}
14
15/**
16Convert a u128 UUID into a standard hyphenated UUID
17
18# Panics
19
20Panics if the given `&str` does not parse to a `u128`
21*/
22#[must_use]
23pub fn decode_u128(s: &str) -> String {
24    Uuid::from_u128(s.parse::<u128>().unwrap())
25        .hyphenated()
26        .to_string()
27}
28
29/**
30Convert a standard hyphenated UUID into a u128 UUID
31
32# Panics
33
34Panics if the given `&str` does not parse to a UUID
35*/
36#[must_use]
37pub fn encode_u128(s: &str, pad: bool) -> String {
38    zero_pad(&Uuid::parse_str(s).unwrap().as_u128().to_string(), pad, 39)
39}
40
41/**
42Convert a Base62 UUID into a standard hyphenated UUID
43
44# Panics
45
46Panics if the given `&str` does not parse to a base62 UUID
47*/
48#[must_use]
49pub fn decode(s: &str) -> String {
50    Uuid::from_u128(base62::decode(s).unwrap())
51        .hyphenated()
52        .to_string()
53}
54
55/**
56Convert a standard hyphenated UUID into a Base62 UUID
57
58# Panics
59
60Panics if the given `&str` does not parse to a UUID
61*/
62#[must_use]
63pub fn encode(s: &str, pad: bool) -> String {
64    zero_pad(
65        &base62::encode(Uuid::parse_str(s).unwrap().as_u128()),
66        pad,
67        22,
68    )
69}
70
71/// Pad UUIDs via leading zeroes
72#[must_use]
73pub fn zero_pad(s: &str, pad: bool, n: usize) -> String {
74    if !pad {
75        return s.to_string();
76    }
77    let mut s = s.to_string();
78    while s.len() < n {
79        s.insert(0, '0');
80    }
81    s
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn roundtrip() {
90        let id = base62_uuid(true);
91        let id_decoded = decode(&id);
92        let id_encoded = encode(&id_decoded, true);
93        assert_eq!(id_encoded, id);
94    }
95
96    #[test]
97    #[ignore]
98    fn roundtrip_100000() {
99        for _ in 0..100000 {
100            roundtrip();
101        }
102    }
103}