uuid-rs / uuid

Generate and parse UUIDs.
https://www.crates.io/crates/uuid
Other
995 stars 192 forks source link

Add reordering to convert between v1 and v6 UUIDs #648

Closed tgross35 closed 6 months ago

tgross35 commented 1 year ago

Motivation

According to the uuid v6+ draft, v6 UUIDs are just a rearrangement of v1 UUIDs. Being able to easily convert between them would be useful for updating anything that works with both rearranged and non-rearranged versions, plus providing an easy way to sort v1 UUIDs.

Relates to #523

Solution

An API along the lines of the following would be nice:

// rearrange a v1 UUID to v6
.v1_as_v6(&self) -> Self

// rearrange a v6 UUID to v1
.v6_as_v1(&self) -> Self

Alternatives

This is currently possible by manually rearranging the bytes

tgross35 commented 1 year ago

The authors of the v6 spec actually provide some conversion algorithms here: http://gh.peabody.io/uuidv6/ under the "hacks" section

KodrAus commented 1 year ago

Hmm, I'd rather not add methods to Uuid itself that effectively become quiet no-ops depending on the version. In this case, I think we could add a method like fn node_id(&self) -> Option<[u8; 6]> that returns Some for v1 and v6 UUIDs, so that you could then write:

if let (Some(ts), Some(node_id)) = (uuid.timestamp(), uuid.node_id()) {
    Uuid::new_v6(ts, &node_id)
} else {
    uuid
};

to get yourself a sortable UUID. It's a bit verbose, but keeps the scope of the library to constructing and deconstructing UUIDs, and not straying into grab-bag utility territory. That kind of functionality is useful, but it's difficult to gauge what's worth including.