forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
87 lines (71 loc) · 1.55 KB
/
set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package dag
import (
"sync"
)
// Set is a set data structure.
type Set struct {
m map[interface{}]interface{}
once sync.Once
}
// Hashable is the interface used by set to get the hash code of a value.
// If this isn't given, then the value of the item being added to the set
// itself is used as the comparison value.
type Hashable interface {
Hashcode() interface{}
}
// hashcode returns the hashcode used for set elements.
func hashcode(v interface{}) interface{} {
if h, ok := v.(Hashable); ok {
return h.Hashcode()
}
return v
}
// Add adds an item to the set
func (s *Set) Add(v interface{}) {
s.once.Do(s.init)
s.m[hashcode(v)] = v
}
// Delete removes an item from the set.
func (s *Set) Delete(v interface{}) {
s.once.Do(s.init)
delete(s.m, hashcode(v))
}
// Include returns true/false of whether a value is in the set.
func (s *Set) Include(v interface{}) bool {
s.once.Do(s.init)
_, ok := s.m[hashcode(v)]
return ok
}
// Intersection computes the set intersection with other.
func (s *Set) Intersection(other *Set) *Set {
result := new(Set)
if other != nil {
for _, v := range s.m {
if other.Include(v) {
result.Add(v)
}
}
}
return result
}
// Len is the number of items in the set.
func (s *Set) Len() int {
if s == nil {
return 0
}
return len(s.m)
}
// List returns the list of set elements.
func (s *Set) List() []interface{} {
if s == nil {
return nil
}
r := make([]interface{}, 0, len(s.m))
for _, v := range s.m {
r = append(r, v)
}
return r
}
func (s *Set) init() {
s.m = make(map[interface{}]interface{})
}