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:
2025-02-28 02:16:32 +00:00
committed by GitHub
parent e87d9c4726
commit fe4308607c
16 changed files with 1077 additions and 36 deletions

View File

@@ -7,6 +7,8 @@ import (
"fmt"
"math/big"
"unicode"
"github.com/jimeh/rands/uuid"
)
const (
@@ -18,7 +20,6 @@ const (
alphabeticChars = upperChars + lowerChars
alphanumericChars = alphabeticChars + numericChars
dnsLabelChars = lowerNumericChars + "-"
uuidHyphen = byte('-')
)
var (
@@ -237,27 +238,33 @@ func DNSLabel(n int) (string, error) {
// UUID returns a random UUID v4 in string format as defined by RFC 4122,
// section 4.4.
func UUID() (string, error) {
b, err := Bytes(16)
uuid, err := uuid.NewRandom()
if err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40 // Version: 4 (random)
b[8] = (b[8] & 0x3f) | 0x80 // Variant: RFC 4122
return uuid.String(), nil
}
// Construct a UUID v4 string according to RFC 4122 specifications.
dst := make([]byte, 36)
hex.Encode(dst[0:8], b[0:4]) // time-low
dst[8] = uuidHyphen
hex.Encode(dst[9:13], b[4:6]) // time-mid
dst[13] = uuidHyphen
hex.Encode(dst[14:18], b[6:8]) // time-high-and-version
dst[18] = uuidHyphen
hex.Encode(dst[19:23], b[8:10]) // clock-seq-and-reserved, clock-seq-low
dst[23] = uuidHyphen
hex.Encode(dst[24:], b[10:]) // node
// UUIDv7 returns a time-ordered UUID v7 in string format.
//
// The UUID v7 format 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
//
//nolint:lll
func UUIDv7() (string, error) {
uuid, err := uuid.NewV7()
if err != nil {
return "", err
}
return string(dst), nil
return uuid.String(), nil
}
func isASCII(s string) bool {