use failure::Fallible;
use uuid::Uuid;
pub fn uuid_to_b64(uuid_in: uuid::Uuid) -> String {
base64::encode_config(uuid_in.as_bytes(), base64::URL_SAFE)
}
pub fn b64_to_uuid(b64_in: String) -> Fallible<uuid::Uuid> {
let dec_bytes = base64::decode_config(b64_in, base64::URL_SAFE)?;
vec_to_uuid(dec_bytes)
}
pub fn vec_to_uuid(dec_bytes: Vec<u8>) -> Fallible<uuid::Uuid> {
if dec_bytes.len() != 16 {
return Err(failure::err_msg("Input is wrong size"));
}
let mut in_bytes: [u8; 16] = [0; 16];
in_bytes.clone_from_slice(&dec_bytes[0..16]);
Ok(Uuid::from_bytes(in_bytes))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uuid_to_b64_roundtrip() {
let randomid = Uuid::new_v4();
let b64 = uuid_to_b64(randomid);
let decoded = b64_to_uuid(b64).unwrap();
assert_eq!(randomid, decoded);
}
}