set.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package set contains set types.
  4. package set
  5. import (
  6. "encoding/json"
  7. "maps"
  8. )
  9. // Set is a set of T.
  10. type Set[T comparable] map[T]struct{}
  11. // SetOf returns a new set constructed from the elements in slice.
  12. func SetOf[T comparable](slice []T) Set[T] {
  13. return Of(slice...)
  14. }
  15. // Of returns a new set constructed from the elements in slice.
  16. func Of[T comparable](slice ...T) Set[T] {
  17. s := make(Set[T])
  18. s.AddSlice(slice)
  19. return s
  20. }
  21. // Clone returns a new set cloned from the elements in s.
  22. func (s Set[T]) Clone() Set[T] {
  23. return maps.Clone(s)
  24. }
  25. // Add adds e to s.
  26. func (s Set[T]) Add(e T) { s[e] = struct{}{} }
  27. // AddSlice adds each element of es to s.
  28. func (s Set[T]) AddSlice(es []T) {
  29. for _, e := range es {
  30. s.Add(e)
  31. }
  32. }
  33. // AddSet adds each element of es to s.
  34. func (s Set[T]) AddSet(es Set[T]) {
  35. for e := range es {
  36. s.Add(e)
  37. }
  38. }
  39. // Make lazily initializes the map pointed to by s to be non-nil.
  40. func (s *Set[T]) Make() {
  41. if *s == nil {
  42. *s = make(Set[T])
  43. }
  44. }
  45. // Slice returns the elements of the set as a slice. The elements will not be
  46. // in any particular order.
  47. func (s Set[T]) Slice() []T {
  48. es := make([]T, 0, s.Len())
  49. for k := range s {
  50. es = append(es, k)
  51. }
  52. return es
  53. }
  54. // Delete removes e from the set.
  55. func (s Set[T]) Delete(e T) { delete(s, e) }
  56. // Contains reports whether s contains e.
  57. func (s Set[T]) Contains(e T) bool {
  58. _, ok := s[e]
  59. return ok
  60. }
  61. // Len reports the number of items in s.
  62. func (s Set[T]) Len() int { return len(s) }
  63. // Equal reports whether s is equal to other.
  64. func (s Set[T]) Equal(other Set[T]) bool {
  65. return maps.Equal(s, other)
  66. }
  67. func (s Set[T]) MarshalJSON() ([]byte, error) {
  68. return json.Marshal(s.Slice())
  69. }
  70. func (s *Set[T]) UnmarshalJSON(buf []byte) error {
  71. var ss []T
  72. if err := json.Unmarshal(buf, &ss); err != nil {
  73. return err
  74. }
  75. *s = SetOf(ss)
  76. return nil
  77. }