Skip to content

Commit

Permalink
added source to enable concurrent reproducible usage
Browse files Browse the repository at this point in the history
  • Loading branch information
trabetti committed Feb 20, 2019
1 parent 9b3b1e0 commit 005951d
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
40 changes: 40 additions & 0 deletions uuid_source.go
Original file line number Diff line number Diff line change
@@ -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 changes: 55 additions & 0 deletions uuid_source_test.go
Original file line number Diff line number Diff line change
@@ -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!")
}

}

0 comments on commit 005951d

Please sign in to comment.