rand.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2018 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. package stringutil
  15. import (
  16. "math/rand"
  17. "time"
  18. )
  19. // UniqueStrings returns a slice of randomly generated unique strings.
  20. func UniqueStrings(slen uint, n int) (ss []string) {
  21. exist := make(map[string]struct{})
  22. ss = make([]string, 0, n)
  23. for len(ss) < n {
  24. s := randString(slen)
  25. if _, ok := exist[s]; !ok {
  26. ss = append(ss, s)
  27. exist[s] = struct{}{}
  28. }
  29. }
  30. return ss
  31. }
  32. // RandomStrings returns a slice of randomly generated strings.
  33. func RandomStrings(slen uint, n int) (ss []string) {
  34. ss = make([]string, 0, n)
  35. for i := 0; i < n; i++ {
  36. ss = append(ss, randString(slen))
  37. }
  38. return ss
  39. }
  40. const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  41. func randString(l uint) string {
  42. rand.Seed(time.Now().UnixNano())
  43. s := make([]byte, l)
  44. for i := 0; i < int(l); i++ {
  45. s[i] = chars[rand.Intn(len(chars))]
  46. }
  47. return string(s)
  48. }