1/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17// Package rand provides utilities related to randomization.
18package rand
19
20import (
21	"math/rand"
22	"sync"
23	"time"
24)
25
26var rng = struct {
27	sync.Mutex
28	rand *rand.Rand
29}{
30	rand: rand.New(rand.NewSource(time.Now().UnixNano())),
31}
32
33// Int returns a non-negative pseudo-random int.
34func Int() int {
35	rng.Lock()
36	defer rng.Unlock()
37	return rng.rand.Int()
38}
39
40// Intn generates an integer in range [0,max).
41// By design this should panic if input is invalid, <= 0.
42func Intn(max int) int {
43	rng.Lock()
44	defer rng.Unlock()
45	return rng.rand.Intn(max)
46}
47
48// IntnRange generates an integer in range [min,max).
49// By design this should panic if input is invalid, <= 0.
50func IntnRange(min, max int) int {
51	rng.Lock()
52	defer rng.Unlock()
53	return rng.rand.Intn(max-min) + min
54}
55
56// IntnRange generates an int64 integer in range [min,max).
57// By design this should panic if input is invalid, <= 0.
58func Int63nRange(min, max int64) int64 {
59	rng.Lock()
60	defer rng.Unlock()
61	return rng.rand.Int63n(max-min) + min
62}
63
64// Seed seeds the rng with the provided seed.
65func Seed(seed int64) {
66	rng.Lock()
67	defer rng.Unlock()
68
69	rng.rand = rand.New(rand.NewSource(seed))
70}
71
72// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
73// from the default Source.
74func Perm(n int) []int {
75	rng.Lock()
76	defer rng.Unlock()
77	return rng.rand.Perm(n)
78}
79
80const (
81	// We omit vowels from the set of available characters to reduce the chances
82	// of "bad words" being formed.
83	alphanums = "bcdfghjklmnpqrstvwxz2456789"
84	// No. of bits required to index into alphanums string.
85	alphanumsIdxBits = 5
86	// Mask used to extract last alphanumsIdxBits of an int.
87	alphanumsIdxMask = 1<<alphanumsIdxBits - 1
88	// No. of random letters we can extract from a single int63.
89	maxAlphanumsPerInt = 63 / alphanumsIdxBits
90)
91
92// String generates a random alphanumeric string, without vowels, which is n
93// characters long.  This will panic if n is less than zero.
94// How the random string is created:
95// - we generate random int63's
96// - from each int63, we are extracting multiple random letters by bit-shifting and masking
97// - if some index is out of range of alphanums we neglect it (unlikely to happen multiple times in a row)
98func String(n int) string {
99	b := make([]byte, n)
100	rng.Lock()
101	defer rng.Unlock()
102
103	randomInt63 := rng.rand.Int63()
104	remaining := maxAlphanumsPerInt
105	for i := 0; i < n; {
106		if remaining == 0 {
107			randomInt63, remaining = rng.rand.Int63(), maxAlphanumsPerInt
108		}
109		if idx := int(randomInt63 & alphanumsIdxMask); idx < len(alphanums) {
110			b[i] = alphanums[idx]
111			i++
112		}
113		randomInt63 >>= alphanumsIdxBits
114		remaining--
115	}
116	return string(b)
117}
118
119// SafeEncodeString encodes s using the same characters as rand.String. This reduces the chances of bad words and
120// ensures that strings generated from hash functions appear consistent throughout the API.
121func SafeEncodeString(s string) string {
122	r := make([]byte, len(s))
123	for i, b := range []rune(s) {
124		r[i] = alphanums[(int(b) % len(alphanums))]
125	}
126	return string(r)
127}
128