terraform/dag/set.go

73 lines
1.3 KiB
Go
Raw Normal View History

2015-01-24 00:01:58 +01:00
package dag
import (
"sync"
)
// Set is a set data structure.
type Set struct {
m map[interface{}]interface{}
2015-01-24 00:01:58 +01:00
once sync.Once
}
2015-02-13 23:12:23 +01:00
// 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.
2015-02-13 23:12:23 +01:00
type Hashable interface {
Hashcode() interface{}
}
2015-01-24 00:01:58 +01:00
// Add adds an item to the set
func (s *Set) Add(v interface{}) {
2015-01-24 00:01:58 +01:00
s.once.Do(s.init)
s.m[s.code(v)] = v
2015-01-24 00:01:58 +01:00
}
// Delete removes an item from the set.
func (s *Set) Delete(v interface{}) {
2015-01-24 00:01:58 +01:00
s.once.Do(s.init)
delete(s.m, s.code(v))
2015-01-24 00:01:58 +01:00
}
// Include returns true/false of whether a value is in the set.
func (s *Set) Include(v interface{}) bool {
2015-01-24 00:01:58 +01:00
s.once.Do(s.init)
_, ok := s.m[s.code(v)]
2015-01-24 00:01:58 +01:00
return ok
}
// Len is the number of items in the set.
func (s *Set) Len() int {
2015-01-24 00:01:58 +01:00
if s == nil {
return 0
}
return len(s.m)
}
// List returns the list of set elements.
func (s *Set) List() []interface{} {
2015-01-24 00:01:58 +01:00
if s == nil {
return nil
}
r := make([]interface{}, 0, len(s.m))
for _, v := range s.m {
r = append(r, v)
2015-01-24 00:01:58 +01:00
}
return r
}
func (s *Set) code(v interface{}) interface{} {
2015-02-13 23:12:23 +01:00
if h, ok := v.(Hashable); ok {
return h.Hashcode()
}
return v
}
func (s *Set) init() {
s.m = make(map[interface{}]interface{})
2015-01-24 00:01:58 +01:00
}