stringutil.go 1.3 KB

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