github.com/graywolf-at-work-2/terraform-vendor@v1.4.5/internal/dag/set.go (about) 1 package dag 2 3 // Set is a set data structure. 4 type Set map[interface{}]interface{} 5 6 // Hashable is the interface used by set to get the hash code of a value. 7 // If this isn't given, then the value of the item being added to the set 8 // itself is used as the comparison value. 9 type Hashable interface { 10 Hashcode() interface{} 11 } 12 13 // hashcode returns the hashcode used for set elements. 14 func hashcode(v interface{}) interface{} { 15 if h, ok := v.(Hashable); ok { 16 return h.Hashcode() 17 } 18 19 return v 20 } 21 22 // Add adds an item to the set 23 func (s Set) Add(v interface{}) { 24 s[hashcode(v)] = v 25 } 26 27 // Delete removes an item from the set. 28 func (s Set) Delete(v interface{}) { 29 delete(s, hashcode(v)) 30 } 31 32 // Include returns true/false of whether a value is in the set. 33 func (s Set) Include(v interface{}) bool { 34 _, ok := s[hashcode(v)] 35 return ok 36 } 37 38 // Intersection computes the set intersection with other. 39 func (s Set) Intersection(other Set) Set { 40 result := make(Set) 41 if s == nil || other == nil { 42 return result 43 } 44 // Iteration over a smaller set has better performance. 45 if other.Len() < s.Len() { 46 s, other = other, s 47 } 48 for _, v := range s { 49 if other.Include(v) { 50 result.Add(v) 51 } 52 } 53 return result 54 } 55 56 // Difference returns a set with the elements that s has but 57 // other doesn't. 58 func (s Set) Difference(other Set) Set { 59 if other == nil || other.Len() == 0 { 60 return s.Copy() 61 } 62 63 result := make(Set) 64 for k, v := range s { 65 if _, ok := other[k]; !ok { 66 result.Add(v) 67 } 68 } 69 70 return result 71 } 72 73 // Filter returns a set that contains the elements from the receiver 74 // where the given callback returns true. 75 func (s Set) Filter(cb func(interface{}) bool) Set { 76 result := make(Set) 77 78 for _, v := range s { 79 if cb(v) { 80 result.Add(v) 81 } 82 } 83 84 return result 85 } 86 87 // Len is the number of items in the set. 88 func (s Set) Len() int { 89 return len(s) 90 } 91 92 // List returns the list of set elements. 93 func (s Set) List() []interface{} { 94 if s == nil { 95 return nil 96 } 97 98 r := make([]interface{}, 0, len(s)) 99 for _, v := range s { 100 r = append(r, v) 101 } 102 103 return r 104 } 105 106 // Copy returns a shallow copy of the set. 107 func (s Set) Copy() Set { 108 c := make(Set, len(s)) 109 for k, v := range s { 110 c[k] = v 111 } 112 return c 113 }