rustuuid

How to convert short UUID's back to UUID's


With short-uuid-rs a regular UUID can be shortened. For example, when I want to convert a UUID to fit with Code39 barcodes, this will work:

let uuid_str = "420e04de-4f06-4e3b-8718-9f6ede92ea9e";
let custom_alphabet = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ-.$/+%";
let translator = CustomTranslator::new(custom_alphabet).unwrap();
let uuid = uuid::Uuid::from_str(uuid_str).unwrap();
let short = ShortUuidCustom::from_uuid(&uuid, &translator);
println!("{}", short.to_string());  // prints "0CK3Z2YL23B7.Q1FR8N65R7X6"

But once the short code is scanned with a barcode scanner it needs to becode a regular UUID again.

How to convert it back?

I've tried the solution from MindSwipe:

let custom_alphabet = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ-.$/+%";
let translator = CustomTranslator::new(custom_alphabet).unwrap();
// there
let orig_uuid_str = "420e04de-4f06-4e3b-8718-9f6ede92ea9e";
let short = ShortUuidCustom::from_uuid_str(&orig_uuid_str, &translator).unwrap();
let short_uuid_str = &short.to_string();
// and back again
let short = match ShortUuidCustom::parse_str(short_uuid_str, &translator) {
  Ok(s) => s,
  Err(e) => panic!("{:?}", e),
};
let new_uuid_str = &short.to_uuid(&translator).unwrap().to_string();
assert_eq!(orig_uuid_str, new_uuid_str);

Unfortunately parse_str() gives me an InvalidShortUuid error. I guess I must be doing *something* wrong ?


Solution

  • It looks like the ShortCustomUuid::parse_str is bugged, or at least only works with 58-character alphabets like FLICKR_BASE_58.

    I have reported an issue here: https://github.com/radim10/short-uuid/issues/4

    Fortunately, it looks like there's a workaround by manually converting bytes using it's BaseConverter type (which is what parse_str was using internally):

    use short_uuid::converter::BaseConverter;
    use short_uuid::{CustomTranslator, ShortUuidCustom, COOKIE_BASE_90};
    use uuid::Uuid;
    
    fn main() {
        let translator = CustomTranslator::new(COOKIE_BASE_90).unwrap();
        let orig_uuid_str = "420e04de-4f06-4e3b-8718-9f6ede92ea9e";
        let short = ShortUuidCustom::from_uuid_str(orig_uuid_str, &translator).unwrap();
        let short_uuid_str = short.to_string();
    
        // let short = ShortUuidCustom::parse_str(&short_uuid_str, &translator).unwrap();
    
        let converter = BaseConverter::new_custom(COOKIE_BASE_90).unwrap();
        let uuid_str = converter.convert_to_hex(short_uuid_str.as_bytes()).unwrap();
        let uuid: Uuid = uuid_str.parse().unwrap();
        println!("{uuid}");
    }
    
    420e04de-4f06-4e3b-8718-9f6ede92ea9e