Skip to content

Commit

Permalink
misc - commented out io.ReadFull and replaced it with random bytes ge…
Browse files Browse the repository at this point in the history
…nerated off the faker struct
  • Loading branch information
brianvoe committed Aug 24, 2023
1 parent c427aa5 commit 8a31ee0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
12 changes: 9 additions & 3 deletions misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package gofakeit

import (
"encoding/hex"
"io"
"math/rand"
"reflect"

Expand All @@ -22,13 +21,20 @@ func boolFunc(r *rand.Rand) bool { return randIntRange(r, 0, 1) == 1 }
func UUID() string { return uuid(globalFaker.Rand) }

// UUID (version 4) will generate a random unique identifier based upon random numbers
// Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 8-4-4-4-12
func (f *Faker) UUID() string { return uuid(f.Rand) }

func uuid(r *rand.Rand) string {
version := byte(4)
uuid := make([]byte, 16)
io.ReadFull(r, uuid[:])

// Commented out due to io.ReadFull not being race condition safe
// io.ReadFull(r, uuid[:])

// Read 16 random bytes
for i := 0; i < 16; i++ {
uuid[i] = byte(r.Intn(256))
}

// Set version
uuid[6] = (uuid[6] & 0x0f) | (version << 4)
Expand Down
12 changes: 10 additions & 2 deletions misc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,28 @@ func TestUUID(t *testing.T) {
id := UUID()

if len(id) != 36 {
t.Error(id)
t.Error("unique length does not equal requested length")
}

// Checking for race conditions, need to run --race
for i := 0; i < 10000; i++ {
go func() {
_ = UUID()
}()
}
}

func ExampleUUID() {
Seed(11)
fmt.Println(UUID())
// Output: 590c1440-9888-45b0-bd51-a817ee07c3f2
// Output: 98173564-6619-4557-888e-65b16bb5def5
}

func ExampleFaker_UUID() {
f := New(11)
fmt.Println(f.UUID())
// Output: 590c1440-9888-45b0-bd51-a817ee07c3f2
// Output: 98173564-6619-4557-888e-65b16bb5def5
}

func BenchmarkUUID(b *testing.B) {
Expand Down

0 comments on commit 8a31ee0

Please sign in to comment.