f4b6a3 / uuid-creator

UUID Creator is a Java library for generating Universally Unique Identifiers.
MIT License
410 stars 44 forks source link

UUID Comparators (feature request) #62

Closed agentgt closed 2 years ago

agentgt commented 2 years ago

I was switching from Fasterxmls JUG UUID library to this library and found some places where we are using UUIDComparator.

We used this to sort old v1 which plain Java UUID does not do correctly as its byte by byte comparison (we now use v6 for new ids but we have old ones all over the place.

The comparator also has a point about java.util.UUID comparing signed longs.

So I thought it might be useful to add something like it to this library.

Of course it does bring a whole bunch of questions like what happens when you compare v6 vs v7,v8 where the time granularity is different. Or what happens when compare with other versions of UUID that are not time based but I think what does now is a reasonable default (ie sort on v1 using timestamp all others are byte by byte comparison).

fabiolimace commented 2 years ago

Hi, @agentgt! Thank you for your interest in this library.

Added UuidComparator for comparing and sorting UUIDs.

It has two static methods:

  1. The default static method compares two time-based UUIDs by comparing the timestamps first and then comparing the least significant bits as unsigned 64-bit integers. If both UUIDs are not time-based then it compares them as unsigned 128-bit integers.

  2. The opaque static method compares two UUIDs as unsigned 128-bit integers. It's the same as lexicographic sorting of UUID canonical strings. It's referred to as "opaque" just because it works like a "blind byte-to-byte comparison".

These are the ways you can use it:

    UUID uuid1 = UUID.randomUUID();
    UUID uuid2 = UUID.randomUUID();

    // using instance methods
    (new UuidComparator()).compare(uuid1, uuid2);
    UuidComparator.getDefaultInstance().compare(uuid1, uuid2);
    UuidComparator.getOpaqueInstance().compare(uuid1, uuid2);

    // using static methods
    UuidComparator.defaultCompare(uuid1, uuid2);
    UuidComparator.opaqueCompare(uuid1, uuid2);
fabiolimace commented 2 years ago

Released version v4.6.0.