From 4144debb6c0317efcde3c97fc6d8b369c6530b6d Mon Sep 17 00:00:00 2001 From: Bryan Newbold Date: Fri, 20 Jul 2018 13:34:33 -0700 Subject: entity ident (fcid) UUID helpers Could perhaps implement these as impl methods on the uuid::Uuid struct instead? --- rust/src/lib.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'rust/src') diff --git a/rust/src/lib.rs b/rust/src/lib.rs index d9193f2f..9de94d86 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -16,6 +16,7 @@ extern crate iron; extern crate serde_json; #[macro_use] extern crate log; +extern crate data_encoding; pub mod api_helpers; pub mod api_server; @@ -32,6 +33,7 @@ mod errors { Uuid(::uuid::ParseError); Io(::std::io::Error) #[cfg(unix)]; Serde(::serde_json::Error); + Base32(::data_encoding::DecodeError); } } } @@ -47,6 +49,7 @@ use dotenv::dotenv; use iron::middleware::AfterMiddleware; use iron::{Request, Response}; use std::env; +use data_encoding::BASE32_NOPAD; #[cfg(feature = "postgres")] embed_migrations!("../migrations/"); @@ -100,3 +103,21 @@ impl AfterMiddleware for XClacksOverheadMiddleware { Ok(res) } } + +/// Convert fatcat IDs (base32 strings) to UUID +pub fn fcid2uuid(fcid: &str) -> Result { + if fcid.len() != 20 { + bail!("invalid fatcat ID (expecting 20-chars of base32"); + } + let mut raw = vec![0; 16]; + BASE32_NOPAD.decode_mut(fcid.to_uppercase().as_bytes(), &mut raw) + .map_err(|dp| dp.error)?; + // unwrap() is safe here, because we know raw is always 16 bytes + Ok(uuid::Uuid::from_bytes(&raw).unwrap()) +} + +/// Convert UUID to fatcat ID string (base32 encoded) +pub fn uuid2fcid(id: &uuid::Uuid) -> String { + let raw = id.as_bytes(); + BASE32_NOPAD.encode(raw).to_lowercase() +} -- cgit v1.2.3