2015-01-24 00:01:58 +01:00
|
|
|
package dag
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2015-01-30 21:56:03 +01:00
|
|
|
// 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.
|
2015-01-30 21:56:03 +01:00
|
|
|
// 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 {
|
2015-01-30 21:56:03 +01:00
|
|
|
Hashcode() interface{}
|
|
|
|
}
|
|
|
|
|
2015-01-24 00:01:58 +01:00
|
|
|
// Add adds an item to the set
|
2015-01-30 21:56:03 +01:00
|
|
|
func (s *Set) Add(v interface{}) {
|
2015-01-24 00:01:58 +01:00
|
|
|
s.once.Do(s.init)
|
2015-01-30 21:56:03 +01:00
|
|
|
s.m[s.code(v)] = v
|
2015-01-24 00:01:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Delete removes an item from the set.
|
2015-01-30 21:56:03 +01:00
|
|
|
func (s *Set) Delete(v interface{}) {
|
2015-01-24 00:01:58 +01:00
|
|
|
s.once.Do(s.init)
|
2015-01-30 21:56:03 +01:00
|
|
|
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.
|
2015-01-30 21:56:03 +01:00
|
|
|
func (s *Set) Include(v interface{}) bool {
|
2015-01-24 00:01:58 +01:00
|
|
|
s.once.Do(s.init)
|
2015-01-30 21:56:03 +01:00
|
|
|
_, 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.
|
2015-01-30 21:56:03 +01:00
|
|
|
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.
|
2015-01-30 21:56:03 +01:00
|
|
|
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))
|
2015-01-30 21:56:03 +01:00
|
|
|
for _, v := range s.m {
|
|
|
|
r = append(r, v)
|
2015-01-24 00:01:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
2015-01-30 21:56:03 +01:00
|
|
|
func (s *Set) code(v interface{}) interface{} {
|
2015-02-13 23:12:23 +01:00
|
|
|
if h, ok := v.(Hashable); ok {
|
2015-01-30 21:56:03 +01:00
|
|
|
return h.Hashcode()
|
|
|
|
}
|
|
|
|
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Set) init() {
|
|
|
|
s.m = make(map[interface{}]interface{})
|
2015-01-24 00:01:58 +01:00
|
|
|
}
|