github.com/anchore/syft@v1.38.2/internal/set.go (about) 1 package internal 2 3 import ( 4 "fmt" 5 "sort" 6 ) 7 8 // Set represents a generic set type. 9 type Set[T comparable] map[T]struct{} 10 11 // NewSet creates a new empty Set. 12 func NewSet[T comparable](start ...T) Set[T] { 13 ret := make(Set[T]) 14 for _, v := range start { 15 ret.Add(v) 16 } 17 return ret 18 } 19 20 // Add adds elements to the set. 21 func (s Set[T]) Add(elements ...T) { 22 for _, e := range elements { 23 s[e] = struct{}{} 24 } 25 } 26 27 // Remove removes an element from the set. 28 func (s Set[T]) Remove(element T) { 29 delete(s, element) 30 } 31 32 // Contains checks if an element is in the set. 33 func (s Set[T]) Contains(element T) bool { 34 _, ok := s[element] 35 return ok 36 } 37 38 // ToSlice returns a sorted slice of elements in the set. 39 func (s Set[T]) ToSlice() []T { 40 ret := make([]T, len(s)) 41 idx := 0 42 for v := range s { 43 ret[idx] = v 44 idx++ 45 } 46 sort.Slice(ret, func(i, j int) bool { 47 return fmt.Sprintf("%v", ret[i]) < fmt.Sprintf("%v", ret[j]) 48 }) 49 return ret 50 } 51 52 // Equals checks if two sets are equal. 53 func (s Set[T]) Equals(o Set[T]) bool { 54 if len(s) != len(o) { 55 return false 56 } 57 for k := range s { 58 if !o.Contains(k) { 59 return false 60 } 61 } 62 return true 63 } 64 65 // Empty checks if the set is empty. 66 func (s Set[T]) Empty() bool { 67 return len(s) == 0 68 }