1use base64::DecodeError;
2use uuid::Error;
3
4pub use uuid::Uuid;
5
6#[derive(Debug)]
7pub enum ConvertError {
8 UuidError(uuid::Error),
9 FromBase64Error(DecodeError),
10}
11
12pub fn to_blob(uuid: &Uuid) -> String {
25 base64::encode_config(uuid.as_bytes(), base64::URL_SAFE_NO_PAD)
26}
27
28pub fn random_blob() -> String {
31 let uuid = Uuid::new_v4();
32 to_blob(&uuid)
33}
34
35pub fn to_uuid(blob: &str) -> Result<Uuid, ConvertError> {
46 match base64::decode_config(blob, base64::URL_SAFE_NO_PAD) {
47 Ok(bytes) => match Uuid::from_slice(&bytes) {
48 Ok(uuid) => Ok(uuid),
49 Err(e) => Err(ConvertError::UuidError(e)),
50 },
51 Err(e) => Err(ConvertError::FromBase64Error(e)),
52 }
53}
54
55#[cfg(test)]
56mod test {
57 use super::*;
58
59 #[test]
60 fn test_blobs() {
61 let uuid_str = "557c8018-5e21-4b74-8bb0-9040e2e8ead1";
62 println!("uuid_str: {}", uuid_str);
63 let blob = "VXyAGF4hS3SLsJBA4ujq0Q";
64 println!("blob: {}", blob);
65 let uuid = Uuid::parse_str(uuid_str).unwrap();
66 assert_eq!(uuid, to_uuid(blob).unwrap());
67 assert_eq!(blob, to_blob(&uuid));
68 }
69
70 #[test]
71 fn test_more_blobs() {
72 for _ in 0..10 {
73 let uuid = Uuid::new_v4();
74 let blob = to_blob(&uuid);
75 assert_eq!(blob.chars().count(), 22);
76 println!("{} | {}", uuid, blob);
77 }
78 }
79}