set.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package intmap
  2. import "iter"
  3. // Set is a specialization of Map modelling a set of integers.
  4. // Like Map, methods that read from the set are valid on the nil Set.
  5. // This include Has, Len, and ForEach.
  6. type Set[K IntKey] Map[K, struct{}]
  7. // NewSet creates a new Set with a given initial capacity.
  8. func NewSet[K IntKey](capacity int) *Set[K] {
  9. return (*Set[K])(New[K, struct{}](capacity))
  10. }
  11. // Add an element to the set. Returns true if the element was not already present.
  12. func (s *Set[K]) Add(k K) bool {
  13. _, found := (*Map[K, struct{}])(s).PutIfNotExists(k, struct{}{})
  14. return found
  15. }
  16. // Del deletes a key, returning true iff the key was found
  17. func (s *Set[K]) Del(k K) bool {
  18. return (*Map[K, struct{}])(s).Del(k)
  19. }
  20. // Clear removes all items from the Set, but keeps the internal buffers for reuse.
  21. func (s *Set[K]) Clear() {
  22. (*Map[K, struct{}])(s).Clear()
  23. }
  24. // Has returns true if the key is in the set.
  25. // If the set is nil this method always return false.
  26. func (s *Set[K]) Has(k K) bool {
  27. return (*Map[K, struct{}])(s).Has(k)
  28. }
  29. // Len returns the number of elements in the set.
  30. // If the set is nil this method return 0.
  31. func (s *Set[K]) Len() int {
  32. return (*Map[K, struct{}])(s).Len()
  33. }
  34. // ForEach iterates over the elements in the set while the visit function returns true.
  35. // This method returns immediately if the set is nil.
  36. //
  37. // The iteration order of a Set is not defined, so please avoid relying on it.
  38. func (s *Set[K]) ForEach(visit func(k K) bool) {
  39. (*Map[K, struct{}])(s).ForEach(func(k K, _ struct{}) bool {
  40. return visit(k)
  41. })
  42. }
  43. // All returns an iterator over keys from the set.
  44. // The iterator returns immediately if the set is nil.
  45. //
  46. // The iteration order of a Set is not defined, so please avoid relying on it.
  47. func (s *Set[K]) All() iter.Seq[K] {
  48. return s.ForEach
  49. }