chore: always safe UUID generation

This commit is contained in:
wwqgtxx committed 2026-04-26 09:46:16 +08:00
1 parent f5f9e5999f
commit 82621cd1bf
2 files changed
+2 -34

No files matched your search

+2 -23
View File
@@ -2,33 +2,12 @@ package utils
import (
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"unsafe"
"github.com/gofrs/uuid/v5"
"github.com/metacubex/randv2"
)
func UnsafeRandRead(p []byte) {
for len(p) > 0 {
v := randv2.Uint64()
if v == 0 {
continue
}
i := copy(p, (*[8]byte)(unsafe.Pointer(&v))[:])
p = p[i:]
}
}
type unsafeRandReader struct{}
func (r *unsafeRandReader) Read(p []byte) (n int, err error) {
UnsafeRandRead(p)
return len(p), nil
}
var UnsafeRandReader = (*unsafeRandReader)(nil)
// NewUUIDV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
func NewUUIDV3(ns uuid.UUID, name string) (u uuid.UUID) {
h := md5.New()
@@ -45,7 +24,7 @@ func NewUUIDV3(ns uuid.UUID, name string) (u uuid.UUID) {
//
// Version 4 UUIDs contain 122 bits of random data.
func NewUUIDV4() (u uuid.UUID) {
UnsafeRandRead(u[:])
rand.Read(u[:])
u.SetVersion(uuid.V4)
u.SetVariant(uuid.VariantRFC9562)
return u
-11
View File
@@ -1,23 +1,12 @@
package utils
import (
"bytes"
"reflect"
"testing"
"github.com/gofrs/uuid/v5"
)
func TestUnsafeRandRead(t *testing.T) {
for i := 1; i < 100; i++ {
data := make([]byte, i)
UnsafeRandRead(data)
if bytes.Equal(data, make([]byte, i)) {
t.Fatal("UnsafeRandRead should not return all zero bytes")
}
}
}
func TestUUIDMap(t *testing.T) {
type args struct {
str string