[转]GO UUID

2013/05/13 10:55
阅读数 637

Here is a simple UUID generator, it uses version 4, Pseudo Random, as described in RFC 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.


展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部