Joey Armstrong | a6af152 | 2023-01-17 16:06:16 -0500 | [diff] [blame] | 1 | package rand |
| 2 | |
| 3 | import ( |
| 4 | "math/rand" |
| 5 | "sync" |
| 6 | ) |
| 7 | |
| 8 | // Int returns a non-negative pseudo-random int. |
| 9 | func Int() int { return pseudo.Int() } |
| 10 | |
| 11 | // Intn returns, as an int, a non-negative pseudo-random number in [0,n). |
| 12 | // It panics if n <= 0. |
| 13 | func Intn(n int) int { return pseudo.Intn(n) } |
| 14 | |
| 15 | // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). |
| 16 | // It panics if n <= 0. |
| 17 | func Int63n(n int64) int64 { return pseudo.Int63n(n) } |
| 18 | |
| 19 | // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n). |
| 20 | func Perm(n int) []int { return pseudo.Perm(n) } |
| 21 | |
| 22 | // Seed uses the provided seed value to initialize the default Source to a |
| 23 | // deterministic state. If Seed is not called, the generator behaves as if |
| 24 | // seeded by Seed(1). |
| 25 | func Seed(n int64) { pseudo.Seed(n) } |
| 26 | |
| 27 | var pseudo = rand.New(&source{src: rand.NewSource(1)}) |
| 28 | |
| 29 | type source struct { |
| 30 | src rand.Source |
| 31 | mu sync.Mutex |
| 32 | } |
| 33 | |
| 34 | func (s *source) Int63() int64 { |
| 35 | s.mu.Lock() |
| 36 | n := s.src.Int63() |
| 37 | s.mu.Unlock() |
| 38 | return n |
| 39 | } |
| 40 | |
| 41 | func (s *source) Seed(seed int64) { |
| 42 | s.mu.Lock() |
| 43 | s.src.Seed(seed) |
| 44 | s.mu.Unlock() |
| 45 | } |