-
Notifications
You must be signed in to change notification settings - Fork 153
/
label_set.go
126 lines (114 loc) · 2.23 KB
/
label_set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package semantic
import "strings"
// LabelSet is a set of string labels.
type LabelSet []string
// allLabels is a sentinal values indicating the set is the infinite set of all possible string labels.
const allLabels = "-all-"
// AllLabels returns a label set that represents the infinite set of all possible string labels.
func AllLabels() LabelSet {
return LabelSet{allLabels}
}
func (s LabelSet) String() string {
if s.isAllLabels() {
return "L"
}
if len(s) == 0 {
return "∅"
}
var builder strings.Builder
builder.WriteString("(")
for i, l := range s {
if i != 0 {
builder.WriteString(", ")
}
builder.WriteString(l)
}
builder.WriteString(")")
return builder.String()
}
func (s LabelSet) isAllLabels() bool {
return len(s) == 1 && s[0] == allLabels
}
func (s LabelSet) contains(l string) bool {
for _, lbl := range s {
if l == lbl {
return true
}
}
return false
}
func (s LabelSet) remove(l string) LabelSet {
filtered := make(LabelSet, 0, len(s))
for _, lbl := range s {
if l != lbl {
filtered = append(filtered, lbl)
}
}
return filtered
}
func (s LabelSet) union(o LabelSet) LabelSet {
if s.isAllLabels() {
return s
}
union := make(LabelSet, len(s), len(s)+len(o))
copy(union, s)
for _, l := range o {
if !union.contains(l) {
union = append(union, l)
}
}
return union
}
func (s LabelSet) intersect(o LabelSet) LabelSet {
if s.isAllLabels() {
return o
}
if o.isAllLabels() {
return s
}
intersect := make(LabelSet, 0, len(s))
for _, l := range s {
if o.contains(l) {
intersect = append(intersect, l)
}
}
return intersect
}
func (a LabelSet) diff(b LabelSet) LabelSet {
if a.isAllLabels() {
return a
}
if b.isAllLabels() {
return nil
}
diff := make(LabelSet, 0, len(a))
for _, l := range a {
if !b.contains(l) {
diff = append(diff, l)
}
}
return diff
}
func (a LabelSet) equal(b LabelSet) bool {
if a.isAllLabels() && b.isAllLabels() {
return true
}
if a.isAllLabels() && !b.isAllLabels() ||
b.isAllLabels() && !a.isAllLabels() {
return false
}
if len(a) != len(b) {
return false
}
for _, l := range a {
if !b.contains(l) {
return false
}
}
return true
}
func (s LabelSet) copy() LabelSet {
c := make(LabelSet, len(s))
copy(c, s)
return c
}