aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/go-faker/faker/v4/random_source.go
blob: 96b7a1573950efb7d6b24b851731d0bb9414bca0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package faker

import (
	"io"
	mathrand "math/rand"
	"sync"
)

var (
	rand   *mathrand.Rand
	crypto io.Reader
)

type safeSource struct {
	mx sync.Mutex
	mathrand.Source
}

func (s *safeSource) Int63() int64 {
	s.mx.Lock()
	defer s.mx.Unlock()

	return s.Source.Int63()
}

// NewSafeSource wraps an unsafe rand.Source with a mutex to guard the random source
// against concurrent access.
func NewSafeSource(in mathrand.Source) mathrand.Source {
	return &safeSource{
		Source: in,
	}
}

// SetRandomSource sets a new random source at the package level.
//
// To use a concurrent-safe source, you may wrap it with NewSafeSource,
// e.g. SetRandomSource(NewSafeSource(mysource)).
//
// The default is the global, concurrent-safe source provided by math/rand.
func SetRandomSource(in mathrand.Source) {
	rand = mathrand.New(in)
}

// SetCryptoSource sets a new reader for functions using a cryptographically-safe random generator (e.g. UUID).
//
// The default is the global source provided by crypto/rand.
func SetCryptoSource(in io.Reader) {
	crypto = in
}