github.com/uber/kraken@v0.1.4/utils/randutil/randutil.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package randutil 15 16 import ( 17 "fmt" 18 "io" 19 "io/ioutil" 20 "math/rand" 21 "time" 22 ) 23 24 func init() { 25 rand.Seed(time.Now().UnixNano()) 26 } 27 28 func choose(n uint64, choices string) []byte { 29 b := make([]byte, n) 30 for i := range b { 31 c := choices[rand.Intn(len(choices))] 32 b[i] = byte(c) 33 } 34 return b 35 } 36 37 const text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" 38 39 // Text returns randomly generated alphanumeric text of length n. 40 func Text(n uint64) []byte { 41 return choose(n, text) 42 } 43 44 // Blob returns randomly generated blob data of length n. 45 func Blob(n uint64) []byte { 46 r := rand.New(rand.NewSource(time.Now().UnixNano())) 47 48 lr := io.LimitReader(r, int64(n)) 49 b, _ := ioutil.ReadAll(lr) 50 51 return b 52 } 53 54 const hex = "0123456789abcdef" 55 56 // Hex returns randomly generated hexadecimal string of length n. 57 func Hex(n uint64) string { 58 return string(choose(n, hex)) 59 } 60 61 // IP returns a randomly generated ip address. 62 func IP() string { 63 return fmt.Sprintf( 64 "%d.%d.%d.%d", 65 rand.Intn(256), 66 rand.Intn(256), 67 rand.Intn(256), 68 rand.Intn(256)) 69 } 70 71 // Port returns a randomly generated port. 72 func Port() int { 73 return rand.Intn(65535) + 1 74 } 75 76 // Addr returns a random address in ip:port format. 77 func Addr() string { 78 return fmt.Sprintf("%s:%d", IP(), Port()) 79 } 80 81 // ShuffleInts shuffles the values of xs in place. 82 func ShuffleInts(xs []int) { 83 for i := range xs { 84 j := rand.Intn(i + 1) 85 xs[i], xs[j] = xs[j], xs[i] 86 } 87 } 88 89 // ShuffleInt64s shuffles the values of xs in place. 90 func ShuffleInt64s(xs []int64) { 91 for i := range xs { 92 j := rand.Intn(i + 1) 93 xs[i], xs[j] = xs[j], xs[i] 94 } 95 } 96 97 // Bools returns a list of randomly generated bools of length n. 98 func Bools(n int) []bool { 99 b := make([]bool, n) 100 for i := range b { 101 b[i] = rand.Intn(2) == 1 102 } 103 return b 104 } 105 106 // Duration returns a random duration below limit. 107 func Duration(limit time.Duration) time.Duration { 108 return time.Duration(rand.Int63n(int64(limit))) 109 }