|
| 1 | +/* |
| 2 | +Copyright 2015 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// Package rand provides utilities related to randomization. |
| 18 | +package util |
| 19 | + |
| 20 | +import ( |
| 21 | + "math/rand" |
| 22 | + "sync" |
| 23 | + "time" |
| 24 | +) |
| 25 | + |
| 26 | +var rng = struct { |
| 27 | + sync.Mutex |
| 28 | + rand *rand.Rand |
| 29 | +}{ |
| 30 | + rand: rand.New(rand.NewSource(time.Now().UnixNano())), |
| 31 | +} |
| 32 | + |
| 33 | +const ( |
| 34 | + // We omit vowels from the set of available characters to reduce the chances |
| 35 | + // of "bad words" being formed. |
| 36 | + alphanums = "bcdfghjklmnpqrstvwxz2456789" |
| 37 | + // No. of bits required to index into alphanums string. |
| 38 | + alphanumsIdxBits = 5 |
| 39 | + // Mask used to extract last alphanumsIdxBits of an int. |
| 40 | + alphanumsIdxMask = 1<<alphanumsIdxBits - 1 |
| 41 | + // No. of random letters we can extract from a single int63. |
| 42 | + maxAlphanumsPerInt = 63 / alphanumsIdxBits |
| 43 | +) |
| 44 | + |
| 45 | +// String generates a random alphanumeric string, without vowels, which is n |
| 46 | +// characters long. This will panic if n is less than zero. |
| 47 | +// How the random string is created: |
| 48 | +// - we generate random int63's |
| 49 | +// - from each int63, we are extracting multiple random letters by bit-shifting and masking |
| 50 | +// - if some index is out of range of alphanums we neglect it (unlikely to happen multiple times in a row) |
| 51 | +func String(n int) string { |
| 52 | + b := make([]byte, n) |
| 53 | + rng.Lock() |
| 54 | + defer rng.Unlock() |
| 55 | + |
| 56 | + randomInt63 := rng.rand.Int63() |
| 57 | + remaining := maxAlphanumsPerInt |
| 58 | + for i := 0; i < n; { |
| 59 | + if remaining == 0 { |
| 60 | + randomInt63, remaining = rng.rand.Int63(), maxAlphanumsPerInt |
| 61 | + } |
| 62 | + if idx := int(randomInt63 & alphanumsIdxMask); idx < len(alphanums) { |
| 63 | + b[i] = alphanums[idx] |
| 64 | + i++ |
| 65 | + } |
| 66 | + randomInt63 >>= alphanumsIdxBits |
| 67 | + remaining-- |
| 68 | + } |
| 69 | + return string(b) |
| 70 | +} |
0 commit comments