How can I implement a function increment(uuid) that given version 1 TimeUUID A produces a valid version 1 TimeUUID B where:
- B > A
- There exists NO C where B > C > A
And the same for decrement(uuid) that given version 1 TimeUUID A produces a valid version 1 TimeUUID B where:
- B < A
- There exists NO C where B < C < A
Version 1 uuid sequencing is represented in the timestamp and clock sequence fields. The timestamp is a 60-bit date stamp (representing 100-nanosecond time increments, fwiw), and the clock sequence is a 14-bit counter that guarantees uuids generated during a given clock cycle are unique. Thus, you can think of v1 uuids as having a 74-bit sequence number, with the timestamp being the high-order bits, and the clock sequence being the low-order ones. So to atomically increment a UUID by one, you need only …
Note that step #1 and #4 are slightly complicated by the fact that the two octets that contain the clock sequence, also contain the uuid variant, so you’ll need to do a bit of bitwise juggling to extract/set just the 14-bits of the clockseq.
To decrement the uuid, just repeat the above, except in steps 2 & 3, if the clock sequence is zero, set it to 2^^14-1, and decrement the timestamp by one.
Finally, you’ll have to decide for yourself what you want to do if the 60-bit timestamp over/underflows. Given that a timestamp of 0 implies the UUID was generated around the time Shakespeare got married (1582 A.D.), and a timestamp of 2^^60-1 means it was generated by your (great^^150)-grandchild in year 5238 A.D… I expect this isn’t too much of a concern.