set.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /*
  2. Copyright 2022 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 sets
  14. import (
  15. "sort"
  16. )
  17. // Set is a set of the same type elements, implemented via map[comparable]struct{} for minimal memory consumption.
  18. type Set[T comparable] map[T]Empty
  19. // cast transforms specified set to generic Set[T].
  20. func cast[T comparable](s map[T]Empty) Set[T] { return s }
  21. // New creates a Set from a list of values.
  22. // NOTE: type param must be explicitly instantiated if given items are empty.
  23. func New[T comparable](items ...T) Set[T] {
  24. ss := make(Set[T], len(items))
  25. ss.Insert(items...)
  26. return ss
  27. }
  28. // KeySet creates a Set from a keys of a map[comparable](? extends interface{}).
  29. // If the value passed in is not actually a map, this will panic.
  30. func KeySet[T comparable, V any](theMap map[T]V) Set[T] {
  31. ret := Set[T]{}
  32. for keyValue := range theMap {
  33. ret.Insert(keyValue)
  34. }
  35. return ret
  36. }
  37. // Insert adds items to the set.
  38. func (s Set[T]) Insert(items ...T) Set[T] {
  39. for _, item := range items {
  40. s[item] = Empty{}
  41. }
  42. return s
  43. }
  44. func Insert[T comparable](set Set[T], items ...T) Set[T] {
  45. return set.Insert(items...)
  46. }
  47. // Delete removes all items from the set.
  48. func (s Set[T]) Delete(items ...T) Set[T] {
  49. for _, item := range items {
  50. delete(s, item)
  51. }
  52. return s
  53. }
  54. // Clear empties the set.
  55. // It is preferable to replace the set with a newly constructed set,
  56. // but not all callers can do that (when there are other references to the map).
  57. // In some cases the set *won't* be fully cleared, e.g. a Set[float32] containing NaN
  58. // can't be cleared because NaN can't be removed.
  59. // For sets containing items of a type that is reflexive for ==,
  60. // this is optimized to a single call to runtime.mapclear().
  61. func (s Set[T]) Clear() Set[T] {
  62. for key := range s {
  63. delete(s, key)
  64. }
  65. return s
  66. }
  67. // Has returns true if and only if item is contained in the set.
  68. func (s Set[T]) Has(item T) bool {
  69. _, contained := s[item]
  70. return contained
  71. }
  72. // HasAll returns true if and only if all items are contained in the set.
  73. func (s Set[T]) HasAll(items ...T) bool {
  74. for _, item := range items {
  75. if !s.Has(item) {
  76. return false
  77. }
  78. }
  79. return true
  80. }
  81. // HasAny returns true if any items are contained in the set.
  82. func (s Set[T]) HasAny(items ...T) bool {
  83. for _, item := range items {
  84. if s.Has(item) {
  85. return true
  86. }
  87. }
  88. return false
  89. }
  90. // Clone returns a new set which is a copy of the current set.
  91. func (s Set[T]) Clone() Set[T] {
  92. result := make(Set[T], len(s))
  93. for key := range s {
  94. result.Insert(key)
  95. }
  96. return result
  97. }
  98. // Difference returns a set of objects that are not in s2.
  99. // For example:
  100. // s1 = {a1, a2, a3}
  101. // s2 = {a1, a2, a4, a5}
  102. // s1.Difference(s2) = {a3}
  103. // s2.Difference(s1) = {a4, a5}
  104. func (s1 Set[T]) Difference(s2 Set[T]) Set[T] {
  105. result := New[T]()
  106. for key := range s1 {
  107. if !s2.Has(key) {
  108. result.Insert(key)
  109. }
  110. }
  111. return result
  112. }
  113. // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.
  114. // For example:
  115. // s1 = {a1, a2, a3}
  116. // s2 = {a1, a2, a4, a5}
  117. // s1.SymmetricDifference(s2) = {a3, a4, a5}
  118. // s2.SymmetricDifference(s1) = {a3, a4, a5}
  119. func (s1 Set[T]) SymmetricDifference(s2 Set[T]) Set[T] {
  120. return s1.Difference(s2).Union(s2.Difference(s1))
  121. }
  122. // Union returns a new set which includes items in either s1 or s2.
  123. // For example:
  124. // s1 = {a1, a2}
  125. // s2 = {a3, a4}
  126. // s1.Union(s2) = {a1, a2, a3, a4}
  127. // s2.Union(s1) = {a1, a2, a3, a4}
  128. func (s1 Set[T]) Union(s2 Set[T]) Set[T] {
  129. result := s1.Clone()
  130. for key := range s2 {
  131. result.Insert(key)
  132. }
  133. return result
  134. }
  135. // Intersection returns a new set which includes the item in BOTH s1 and s2
  136. // For example:
  137. // s1 = {a1, a2}
  138. // s2 = {a2, a3}
  139. // s1.Intersection(s2) = {a2}
  140. func (s1 Set[T]) Intersection(s2 Set[T]) Set[T] {
  141. var walk, other Set[T]
  142. result := New[T]()
  143. if s1.Len() < s2.Len() {
  144. walk = s1
  145. other = s2
  146. } else {
  147. walk = s2
  148. other = s1
  149. }
  150. for key := range walk {
  151. if other.Has(key) {
  152. result.Insert(key)
  153. }
  154. }
  155. return result
  156. }
  157. // IsSuperset returns true if and only if s1 is a superset of s2.
  158. func (s1 Set[T]) IsSuperset(s2 Set[T]) bool {
  159. for item := range s2 {
  160. if !s1.Has(item) {
  161. return false
  162. }
  163. }
  164. return true
  165. }
  166. // Equal returns true if and only if s1 is equal (as a set) to s2.
  167. // Two sets are equal if their membership is identical.
  168. // (In practice, this means same elements, order doesn't matter)
  169. func (s1 Set[T]) Equal(s2 Set[T]) bool {
  170. return len(s1) == len(s2) && s1.IsSuperset(s2)
  171. }
  172. type sortableSliceOfGeneric[T ordered] []T
  173. func (g sortableSliceOfGeneric[T]) Len() int { return len(g) }
  174. func (g sortableSliceOfGeneric[T]) Less(i, j int) bool { return less[T](g[i], g[j]) }
  175. func (g sortableSliceOfGeneric[T]) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
  176. // List returns the contents as a sorted T slice.
  177. //
  178. // This is a separate function and not a method because not all types supported
  179. // by Generic are ordered and only those can be sorted.
  180. func List[T ordered](s Set[T]) []T {
  181. res := make(sortableSliceOfGeneric[T], 0, len(s))
  182. for key := range s {
  183. res = append(res, key)
  184. }
  185. sort.Sort(res)
  186. return res
  187. }
  188. // UnsortedList returns the slice with contents in random order.
  189. func (s Set[T]) UnsortedList() []T {
  190. res := make([]T, 0, len(s))
  191. for key := range s {
  192. res = append(res, key)
  193. }
  194. return res
  195. }
  196. // PopAny returns a single element from the set.
  197. func (s Set[T]) PopAny() (T, bool) {
  198. for key := range s {
  199. s.Delete(key)
  200. return key, true
  201. }
  202. var zeroValue T
  203. return zeroValue, false
  204. }
  205. // Len returns the size of the set.
  206. func (s Set[T]) Len() int {
  207. return len(s)
  208. }
  209. func less[T ordered](lhs, rhs T) bool {
  210. return lhs < rhs
  211. }