mirror of
https://github.com/google/uuid.git
synced 2024-11-24 08:32:23 +02:00
added source to enable concurrent reproducible usage
This commit is contained in:
parent
9b3b1e0f5f
commit
005951d400
40
uuid_source.go
Normal file
40
uuid_source.go
Normal file
@ -0,0 +1,40 @@
|
||||
package uuid
|
||||
|
||||
import (
|
||||
"io"
|
||||
"crypto/rand"
|
||||
)
|
||||
|
||||
type UuidSource struct {
|
||||
rander io.Reader
|
||||
}
|
||||
|
||||
func NewSource(r io.Reader) UuidSource {
|
||||
var uuidSource UuidSource
|
||||
uuidSource.SetRand(r)
|
||||
return uuidSource
|
||||
|
||||
}
|
||||
|
||||
func (uuidSource *UuidSource) SetRand(r io.Reader) {
|
||||
if r == nil {
|
||||
uuidSource.rander = rand.Reader
|
||||
return
|
||||
}
|
||||
uuidSource.rander = r
|
||||
}
|
||||
|
||||
func (uuidSource UuidSource) NewRandom() (UUID, error) {
|
||||
var uuid UUID
|
||||
_, err := io.ReadFull(uuidSource.rander, uuid[:])
|
||||
if err != nil {
|
||||
return Nil, err
|
||||
}
|
||||
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
|
||||
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
|
||||
return uuid, nil
|
||||
}
|
||||
|
||||
func (uuidSource UuidSource) New() UUID {
|
||||
return Must(uuidSource.NewRandom())
|
||||
}
|
55
uuid_source_test.go
Normal file
55
uuid_source_test.go
Normal file
@ -0,0 +1,55 @@
|
||||
package uuid
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"fmt"
|
||||
"strings"
|
||||
"math/rand"
|
||||
|
||||
)
|
||||
|
||||
func TestUuidSources(t *testing.T) {
|
||||
|
||||
uuidSourceA := NewSource(rand.New(rand.NewSource(34576)))
|
||||
uuidSourceB := NewSource(rand.New(rand.NewSource(34576)))
|
||||
|
||||
var uuidStrA, uuidStrB string
|
||||
fmt.Printf("Random values: ")
|
||||
for i := 0; i < 10; i++ {
|
||||
uuidStrA += uuidSourceA.New().String() + "."
|
||||
}
|
||||
fmt.Printf("%v\n", uuidStrA)
|
||||
|
||||
fmt.Printf("Random values: ")
|
||||
for i := 0; i < 10; i++ {
|
||||
uuidStrB += uuidSourceB.New().String() + "."
|
||||
}
|
||||
fmt.Printf("%v\n", uuidStrB)
|
||||
|
||||
if !strings.EqualFold(uuidStrA, uuidStrB) {
|
||||
t.Error("Uuid values are not reproducaible!")
|
||||
}
|
||||
|
||||
uuidSourceA = NewSource(rand.New(rand.NewSource(66)))
|
||||
uuidSourceB = NewSource(rand.New(rand.NewSource(77)))
|
||||
|
||||
|
||||
uuidStrA = ""
|
||||
uuidStrB = ""
|
||||
fmt.Printf("Random values: ")
|
||||
for i := 0; i < 10; i++ {
|
||||
uuidStrA += uuidSourceA.New().String() + "."
|
||||
}
|
||||
fmt.Printf("%v\n", uuidStrA)
|
||||
|
||||
fmt.Printf("Random values: ")
|
||||
for i := 0; i < 10; i++ {
|
||||
uuidStrB += uuidSourceB.New().String() + "."
|
||||
}
|
||||
fmt.Printf("%v\n", uuidStrB)
|
||||
|
||||
if strings.EqualFold(uuidStrA, uuidStrB) {
|
||||
t.Error("Uuid values should not be reproducaible!")
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user