Skip to content

Commit

Permalink
avoid data races in RandomString
Browse files Browse the repository at this point in the history
  • Loading branch information
kmulvey committed May 16, 2024
1 parent 6b03ce8 commit a9a165c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
15 changes: 6 additions & 9 deletions random_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,15 @@ import (
"time"
)

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
var randomSource *rand.Rand

func init() {
//nolint:gosec
randomSource = rand.New(rand.NewSource(time.Now().UnixNano()))
}

// RandomString returns a cases sensitive random string of the given length. The randonSource and
// character array are in the function to avoid data races. At this time its overkill to store them
// in a type but this can be done in the future if necessary.
func RandomString(n int) string {
//nolint:gosec
var randomSource = rand.New(rand.NewSource(time.Now().UnixNano()))
s := make([]rune, n)
for i := range s {
s[i] = letters[randomSource.Intn(len(letters))]
s[i] = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")[randomSource.Intn(52)]
}
return string(s)
}
19 changes: 19 additions & 0 deletions random_string_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package goutils

import (
"sync"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -17,3 +18,21 @@ func TestRandomString(t *testing.T) {

assert.NotEqual(t, a, b)
}

// make sure there is no data race
func TestRandomStringParallel(t *testing.T) {
t.Parallel()

var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func(wg *sync.WaitGroup) {
for i := 0; i < 1000; i++ {
var a = RandomString(10)
assert.Equal(t, 10, len(a))
}
wg.Done()
}(&wg)
}
wg.Wait()
}

0 comments on commit a9a165c

Please sign in to comment.