go.etcd.io/etcd@v3.3.27+incompatible/pkg/stringutil/stringutil.go (about) 1 // Copyright 2016 The etcd Authors 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 15 // Package stringutil exports string utility functions. 16 package stringutil 17 18 import "math/rand" 19 20 const ( 21 chars = "abcdefghijklmnopqrstuvwxyz0123456789" 22 ) 23 24 // UniqueStrings returns a slice of randomly generated unique strings. 25 func UniqueStrings(maxlen uint, n int) []string { 26 exist := make(map[string]bool) 27 ss := make([]string, 0) 28 29 for len(ss) < n { 30 s := randomString(maxlen) 31 if !exist[s] { 32 exist[s] = true 33 ss = append(ss, s) 34 } 35 } 36 37 return ss 38 } 39 40 // RandomStrings returns a slice of randomly generated strings. 41 func RandomStrings(maxlen uint, n int) []string { 42 ss := make([]string, 0) 43 for i := 0; i < n; i++ { 44 ss = append(ss, randomString(maxlen)) 45 } 46 return ss 47 } 48 49 func randomString(l uint) string { 50 s := make([]byte, l) 51 for i := 0; i < int(l); i++ { 52 s[i] = chars[rand.Intn(len(chars))] 53 } 54 return string(s) 55 }