1use uuid::Uuid;
2
3#[must_use]
5pub fn base62_uuid(pad: bool) -> String {
6 zero_pad(&base62::encode(Uuid::new_v4().as_u128()), pad, 22)
7}
8
9#[must_use]
11pub fn u128_uuid(pad: bool) -> String {
12 zero_pad(&Uuid::new_v4().as_u128().to_string(), pad, 39)
13}
14
15#[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#[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#[must_use]
49pub fn decode(s: &str) -> String {
50 Uuid::from_u128(base62::decode(s).unwrap())
51 .hyphenated()
52 .to_string()
53}
54
55#[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#[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}