mirror of
https://github.com/jimeh/rands.git
synced 2026-02-19 11:26:38 +00:00
feat(strings/uuidv7): add UUIDv7 generation (#10)
The UUID v7 format is a time-ordered random UUID. It uses a timestamp with millisecond precision in the most significant bits, followed by random data. This provides both uniqueness and chronological ordering, making it ideal for database primary keys and situations where sorting by creation time is desired. References: - https://uuid7.com/ - https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-04.html#name-uuid-version-7
This commit is contained in:
39
uuid/random_test.go
Normal file
39
uuid/random_test.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package uuid
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewRandom(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
m := regexp.MustCompile(
|
||||
`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`,
|
||||
)
|
||||
|
||||
seen := make(map[string]struct{})
|
||||
|
||||
for i := 0; i < 10000; i++ {
|
||||
got, err := NewRandom()
|
||||
require.NoError(t, err)
|
||||
require.Regexp(t, m, got.String())
|
||||
|
||||
if _, ok := seen[got.String()]; ok {
|
||||
require.FailNow(t, "duplicate UUID")
|
||||
}
|
||||
|
||||
seen[got.String()] = struct{}{}
|
||||
|
||||
require.Equal(t, 4, int(got[6]>>4), "version is not 4")
|
||||
require.Equal(t, byte(0x80), got[8]&0xc0, "variant is not RFC 4122")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNewRandom(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
_, _ = NewRandom()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user