Files
rands/uuid/random.go
Jim Myhrberg fe4308607c 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
2025-02-28 02:16:32 +00:00

25 lines
479 B
Go

package uuid
import (
"crypto/rand"
)
// NewRandom returns a random UUID v4 in string format as defined by RFC 4122,
// section 4.4.
func NewRandom() (UUID, error) {
var u UUID
// Fill the entire UUID with random bytes.
_, err := rand.Read(u[:])
if err != nil {
// This should never happen.
return u, err
}
// Set the version and variant bits.
u[6] = (u[6] & 0x0f) | 0x40 // Version: 4 (random)
u[8] = (u[8] & 0x3f) | 0x80 // Variant: RFC 4122
return u, nil
}