blob_uuid/
lib.rs

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
12/// Convert uuid to a 22 character string blob
13/// ```rust
14///  extern crate uuid;
15///  use uuid::Uuid;
16///
17///  extern crate blob_uuid;
18///  fn main(){
19///     let uuid = Uuid::parse_str("557c8018-5e21-4b74-8bb0-9040e2e8ead1").unwrap();
20///     assert_eq!("VXyAGF4hS3SLsJBA4ujq0Q", blob_uuid::to_blob(&uuid));
21///  }
22///
23/// ```
24pub fn to_blob(uuid: &Uuid) -> String {
25    base64::encode_config(uuid.as_bytes(), base64::URL_SAFE_NO_PAD)
26}
27
28/// Generate a random uuid and return its string blob
29///
30pub fn random_blob() -> String {
31    let uuid = Uuid::new_v4();
32    to_blob(&uuid)
33}
34
35/// Convert a string blob back to uuid
36/// ```rust
37/// extern crate uuid;
38/// extern crate blob_uuid;
39/// use uuid::Uuid;
40/// fn main(){
41///  let uuid = Uuid::parse_str("557c8018-5e21-4b74-8bb0-9040e2e8ead1").unwrap();
42///  assert_eq!(uuid, blob_uuid::to_uuid("VXyAGF4hS3SLsJBA4ujq0Q").unwrap());
43/// }
44/// ```
45pub 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}