[转]GO UUID
发布时间:2020-12-16 19:00:49 所属栏目:大数据 来源:网络整理
导读:Here is a simple UUID generator,it uses version 4,Pseudo Random,as described in RFC 4122 uuid.go package uuidimport ( "encoding/hex" "crypto/rand")func GenUUID() (string,error) { uuid := make([]byte,16) n,err := rand.Read(uuid) if n != len
|
Here is a simple UUID generator,it uses version 4,Pseudo Random,as described inRFC 4122 uuid.go package uuid
import (
"encoding/hex"
"crypto/rand"
)
func GenUUID() (string,error) {
uuid := make([]byte,16)
n,err := rand.Read(uuid)
if n != len(uuid) || err != nil {
return "",err
}
// TODO: verify the two lines implement RFC 4122 correctly
uuid[8] = 0x80 // variant bits see page 5
uuid[4] = 0x40 // version 4 Pseudo Random,see page 7
return hex.EncodeToString(uuid),nil
}
uuid_test.go
package uuid
import (
"testing"
)
func TestUUID(t *testing.T) {
uuid,err := GenUUID()
if err != nil {
t.Fatalf("GenUUID error %s",err)
}
t.Logf("uuid[%s]n",uuid)
}
func BenchmarkUUID(b *testing.B) {
m := make(map[string]int,1000)
for i := 0; i < b.N; i++ {
uuid,err := GenUUID()
if err != nil {
b.Fatalf("GenUUID error %s",err)
}
b.StopTimer()
c := m[uuid]
if c > 0 {
b.Fatalf("duplicate uuid[%s] count %d",uuid,c )
}
m[uuid] = c+1
b.StartTimer()
}
}
command to build uuid.go
go build uuid.go
command to run test & benchmark:
go test -v -bench=".*UUID" uuid.go uuid_test.go The source code of uuid.go and uuid_test.go are attached below. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
