UUID v7
Go implementation of UUID v7 as defined in RFC4122 with implementation of a monotonicity counter as defined by Method 3.
A UUID v7 is a sucessor to UUID v1 and UUID v6. It utilizes a Unix millisecond timestamp internally, which makes them lexicographically sortable, while maintaining a high level of entropy.
They are well suited for creation of database entry or tracing identifiers.
In cases where maximal randomness is desired, such as in the creation of API keys, a UUID v4 is more suitable, as it contains 122 pseudo-random bits, while a UUID v7 contains 62 pseudo-random bits.
Usage
Generate a new unique identifier:
uniqueID := uuidv7.New()
Print the newly generated UUID v7 as a hyphen delimited string:
str := uniqueID.String()
This value can be used to store in a database or for sorting.
To only print the last 12 characters of the UUID v7:
shortStr := uniqueID.Short()
This can be useful for logging to easily identify different UUIDs and should offer enough randomness for many cases.
You can retrieve the creation time and the sequence number from a generated UUID v7:
creationTime := uniqueID.CreationTime()
sequenceNumber := uniqueID.SequenceNumber()
The creation time has a milli second time resolution. The sequence numbers differentiate between and order UUIDs which were created within one time step.
If you want to quickly check in which order UUIDs were created the following methods can be used:
isNewer := uniqueID.After(anotherUUID)
isOlder := uniqueID.Before(anotherUUID)
To validate if a UUID generated by another package is a valid UUID v7, the validate functions can be used:
isValidByteSlice := uuidv7.IsValid(sketchyUUID)
isValidString := uuidv7.IsValidString(sketchyUUIDString)
Benchmark
Compared to generating a UUID v4 with the commonly used UUID package by Google generating a UUID v7 with this package is around 15% slower, due to the more complex scheme of UUID v7 compared to UUID v4, although this implementation avoids any heap allocations,
BenchmarkUUIDv4-16 1752595 682.6 ns/op 16 B/op 1 allocs/op
BenchmarkUUIDv7-16 1666899 719.5 ns/op 0 B/op 0 allocs/op
The string method is faster, without allocation.
BenchmarkStringV4-16 25060156 43.42 ns/op 48 B/op 1 allocs/op
BenchmarkStringV7-16 66940467 16.96 ns/op 0 B/op 0 allocs/op
All other methods and functions have also been highly optimized and do not cause any heap allocations.
BenchmarkAfter-16 22275807 53.44 ns/op 0 B/op 0 allocs/op
BenchmarkBefore-16 22385337 53.33 ns/op 0 B/op 0 allocs/op
BenchmarkCreationTime-16 67861596 17.43 ns/op 0 B/op 0 allocs/op
BenchmarkSequenceNumber-16 654815791 1.808 ns/op 0 B/op 0 allocs/op
BenchmarkShort-16 245679874 4.262 ns/op 0 B/op 0 allocs/op
BenchmarkIsValid-16 20835577 55.47 ns/op 0 B/op 0 allocs/op
BenchmarkIsValidString-16 7111466 167.0 ns/op 0 B/op 0 allocs/op