github.com/rmenn/terraform@v0.3.8-0.20150225065417-fc84b3a78802/dag/set.go (about)

     1  package dag
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  // Set is a set data structure.
     8  type Set struct {
     9  	m    map[interface{}]interface{}
    10  	once sync.Once
    11  }
    12  
    13  // Hashable is the interface used by set to get the hash code of a value.
    14  // If this isn't given, then the value of the item being added to the set
    15  // itself is used as the comparison value.
    16  type Hashable interface {
    17  	Hashcode() interface{}
    18  }
    19  
    20  // Add adds an item to the set
    21  func (s *Set) Add(v interface{}) {
    22  	s.once.Do(s.init)
    23  	s.m[s.code(v)] = v
    24  }
    25  
    26  // Delete removes an item from the set.
    27  func (s *Set) Delete(v interface{}) {
    28  	s.once.Do(s.init)
    29  	delete(s.m, s.code(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  	s.once.Do(s.init)
    35  	_, ok := s.m[s.code(v)]
    36  	return ok
    37  }
    38  
    39  // Len is the number of items in the set.
    40  func (s *Set) Len() int {
    41  	if s == nil {
    42  		return 0
    43  	}
    44  
    45  	return len(s.m)
    46  }
    47  
    48  // List returns the list of set elements.
    49  func (s *Set) List() []interface{} {
    50  	if s == nil {
    51  		return nil
    52  	}
    53  
    54  	r := make([]interface{}, 0, len(s.m))
    55  	for _, v := range s.m {
    56  		r = append(r, v)
    57  	}
    58  
    59  	return r
    60  }
    61  
    62  func (s *Set) code(v interface{}) interface{} {
    63  	if h, ok := v.(Hashable); ok {
    64  		return h.Hashcode()
    65  	}
    66  
    67  	return v
    68  }
    69  
    70  func (s *Set) init() {
    71  	s.m = make(map[interface{}]interface{})
    72  }