1package set 2 3import ( 4 "fmt" 5) 6 7// Set is an implementation of the concept of a set: a collection where all 8// values are conceptually either in or out of the set, but the members are 9// not ordered. 10// 11// This type primarily exists to be the internal type of sets in cty, but 12// it is considered to be at the same level of abstraction as Go's built in 13// slice and map collection types, and so should make no cty-specific 14// assumptions. 15// 16// Set operations are not thread safe. It is the caller's responsibility to 17// provide mutex guarantees where necessary. 18// 19// Set operations are not optimized to minimize memory pressure. Mutating 20// a set will generally create garbage and so should perhaps be avoided in 21// tight loops where memory pressure is a concern. 22type Set struct { 23 vals map[int][]interface{} 24 rules Rules 25} 26 27// NewSet returns an empty set with the membership rules given. 28func NewSet(rules Rules) Set { 29 return Set{ 30 vals: map[int][]interface{}{}, 31 rules: rules, 32 } 33} 34 35func NewSetFromSlice(rules Rules, vals []interface{}) Set { 36 s := NewSet(rules) 37 for _, v := range vals { 38 s.Add(v) 39 } 40 return s 41} 42 43func sameRules(s1 Set, s2 Set) bool { 44 return s1.rules == s2.rules 45} 46 47func mustHaveSameRules(s1 Set, s2 Set) { 48 if !sameRules(s1, s2) { 49 panic(fmt.Errorf("incompatible set rules: %#v, %#v", s1.rules, s2.rules)) 50 } 51} 52 53// HasRules returns true if and only if the receiving set has the given rules 54// instance as its rules. 55func (s Set) HasRules(rules Rules) bool { 56 return s.rules == rules 57} 58 59// Rules returns the receiving set's rules instance. 60func (s Set) Rules() Rules { 61 return s.rules 62} 63