istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/framework/label/instance.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package label 16 17 import ( 18 "sort" 19 "strings" 20 ) 21 22 // Instance is a label instance. 23 type Instance string 24 25 // Set is a set of labels 26 type Set map[Instance]struct{} 27 28 // NewSet returns a new label set. 29 func NewSet(labels ...Instance) Set { 30 s := make(map[Instance]struct{}) 31 for _, l := range labels { 32 s[l] = struct{}{} 33 } 34 35 return s 36 } 37 38 // Add adds the given labels and returns a new, combined set 39 func (l Set) Add(labels ...Instance) Set { 40 c := l.Clone() 41 for _, label := range labels { 42 c[label] = struct{}{} 43 } 44 45 return c 46 } 47 48 // Merge returns a set that is merging of l and s. 49 func (l Set) Merge(s Set) Set { 50 c := l.Clone() 51 for k, v := range s { 52 c[k] = v 53 } 54 55 return c 56 } 57 58 // Clone this set of labels 59 func (l Set) Clone() Set { 60 s := make(map[Instance]struct{}) 61 for k, v := range l { 62 s[k] = v 63 } 64 65 return s 66 } 67 68 // All returns all labels in this set. 69 func (l Set) All() []Instance { 70 r := make([]Instance, 0, len(l)) 71 for label := range l { 72 r = append(r, label) 73 } 74 75 sort.Slice(r, func(i, j int) bool { 76 return strings.Compare(string(r[i]), string(r[j])) < 0 77 }) 78 return r 79 } 80 81 func (l Set) contains(label Instance) bool { 82 _, found := l[label] 83 return found 84 } 85 86 func (l Set) containsAny(other Set) bool { 87 for l2 := range other { 88 if l.contains(l2) { 89 return true 90 } 91 } 92 93 return false 94 } 95 96 func (l Set) containsAll(other Set) bool { 97 for l2 := range other { 98 if l.contains(l2) { 99 continue 100 } 101 return false 102 } 103 104 return true 105 }