Crates.io | uuid-b64 |
lib.rs | uuid-b64 |
version | 0.2.0 |
source | src |
created_at | 2018-03-11 22:41:57.029752 |
updated_at | 2024-06-20 00:36:21.439384 |
description | Base64 encoding for UUIDs |
homepage | |
repository | https://github.com/quodlibetor/uuid-b64 |
max_upload_size | |
id | 55078 |
size | 36,151 |
A UUID wrapper that has a base64 display and serialization
A newtype around UUIDs that:
let known_id = Uuid::parse_str("b0c1ee86-6f46-4f1b-8d8b-7849e75dbcee").unwrap();
let as_b64 = UuidB64::from(known_id);
assert_eq!(as_b64.to_string(), "sMHuhm9GTxuNi3hJ51287g");
let parsed_b64: UuidB64 = "sMHuhm9GTxuNi3hJ51287g".parse().unwrap();
assert_eq!(parsed_b64, as_b64);
let raw_id = Uuid::new_v4();
assert_eq!(raw_id.to_string().len(), 36);
let uuidb64 = UuidB64::from(raw_id);
assert_eq!(uuidb64.to_string().len(), 22);
UuidB64::new
creates v4 UUIDs, because... that's what I use. I'm open to
hearing arguments about why this is a ridiculous decision and I should have
made new
be new_v4
.
UUIDs are great:
That said, the standard representation for UUIDs is kind of annoying:
I guess that's it. Base64 is a more human-friendly representation of UUIDs:
That said, there are drawbacks to something like this:
If you store it as a UUID column in a database IDs won't show up in the same way as it does in your application code, meaning you'll (A) maybe want to define a new database type, or B just expect to only ever interact with the DB via you application.
Conversion functions are pretty trivial, this works in postgres (inefficiently, but it's only for interactive queries so whatever):
CREATE FUNCTION b64uuid(encoded TEXT) RETURNS UUID
AS $$
BEGIN
RETURN ENCODE(DECODE(REPLACE(REPLACE(
encoded, '-', '+'), '_', '/') || '==', 'base64'), 'hex')::UUID;
END
$$ LANGUAGE plpgsql;
Just use UuidB64
everywhere you would use Uuid
, and use UuidB64::from
to create one from an existing UUID.
serde
enables serialization/deserialization via Serde.diesel-uuid
enables integration with Diesel's UUID support, this is
only tested on postgres, PRs welcome for other DBs.Most tests are standard: cargo test
or cargo test --features serde
, but if
you want to test the diesel integration (the diesel-uuid
feature) then we
need a running postgres instance. Assuming that you have docker running locally
and are in bash you can do ./run-tests.sh
to execute all tests.
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.