-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.go
47 lines (38 loc) · 1.41 KB
/
random.go
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
// Package random contains different random generators.
package random
import (
"bytes"
"math/rand"
"time"
)
// Random generates a random int between min and max, inclusive.
func Random(min int, max int) int {
return newRand().Intn(max-min+1) + min
}
// RandomInt picks a random element in the slice of ints.
func RandomInt(elements []int) int {
index := Random(0, len(elements)-1)
return elements[index]
}
// RandomString picks a random element in the slice of string.
func RandomString(elements []string) string {
index := Random(0, len(elements)-1)
return elements[index]
}
const base62chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const uniqueIDLength = 6 // Should be good for 62^6 = 56+ billion combinations
// UniqueId returns a unique (ish) id we can attach to resources and tfstate files so they don't conflict with each other
// Uses base 62 to generate a 6 character string that's unlikely to collide with the handful of tests we run in
// parallel. Based on code here: http://stackoverflow.com/a/9543797/483528
func UniqueId() string {
var out bytes.Buffer
generator := newRand()
for i := 0; i < uniqueIDLength; i++ {
out.WriteByte(base62chars[generator.Intn(len(base62chars))])
}
return out.String()
}
// newRand creates a new random number generator, seeding it with the current system time.
func newRand() *rand.Rand {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}