stringutil.go 1.4 KB

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