slice.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package slice provides utility methods for common operations on slices.
  14. package slice
  15. import (
  16. "sort"
  17. utilrand "k8s.io/kubernetes/pkg/util/rand"
  18. )
  19. // CopyStrings copies the contents of the specified string slice
  20. // into a new slice.
  21. func CopyStrings(s []string) []string {
  22. c := make([]string, len(s))
  23. copy(c, s)
  24. return c
  25. }
  26. // SortStrings sorts the specified string slice in place. It returns the same
  27. // slice that was provided in order to facilitate method chaining.
  28. func SortStrings(s []string) []string {
  29. sort.Strings(s)
  30. return s
  31. }
  32. // ShuffleStrings copies strings from the specified slice into a copy in random
  33. // order. It returns a new slice.
  34. func ShuffleStrings(s []string) []string {
  35. shuffled := make([]string, len(s))
  36. perm := utilrand.Perm(len(s))
  37. for i, j := range perm {
  38. shuffled[j] = s[i]
  39. }
  40. return shuffled
  41. }
  42. // Int64Slice attaches the methods of Interface to []int64,
  43. // sorting in increasing order.
  44. type Int64Slice []int64
  45. func (p Int64Slice) Len() int { return len(p) }
  46. func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] }
  47. func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  48. // Sorts []int64 in increasing order
  49. func SortInts64(a []int64) { sort.Sort(Int64Slice(a)) }