/
labels.go
96 lines (77 loc) · 2.04 KB
/
labels.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package resource
import (
"fmt"
"slices"
"github.com/siderolabs/go-pointer"
"github.com/cosi-project/runtime/pkg/resource/internal/compare"
"github.com/cosi-project/runtime/pkg/resource/internal/kv"
)
// Labels is a set free-form of key-value pairs.
//
// Order of keys is not guaranteed.
//
// Labels support copy-on-write semantics, so metadata copies share common labels as long as possible.
// Labels support querying with LabelTerm.
type Labels struct {
kv.KV
}
// Equal checks labels for equality.
func (labels Labels) Equal(other Labels) bool {
return labels.KV.Equal(other.KV)
}
// Matches if labels match the LabelTerm.
func (labels Labels) Matches(term LabelTerm) bool {
matches := labels.matches(term)
if matches == nil {
return false
}
m := *matches
if term.Invert {
return !m
}
return m
}
func (labels Labels) matches(term LabelTerm) *bool {
if labels.KV.Empty() && term.Op == LabelOpExists {
return pointer.To(false)
}
value, ok := labels.Get(term.Key)
if !ok {
if term.Op.isComparison() {
return nil
}
return pointer.To(false)
}
if term.Op != LabelOpExists && len(term.Value) == 0 {
return pointer.To(false)
}
switch term.Op {
case LabelOpExists:
return pointer.To(true)
case LabelOpEqual:
return pointer.To(value == term.Value[0])
case LabelOpIn:
return pointer.To(slices.Contains(term.Value, value))
case LabelOpLTE:
return pointer.To(value <= term.Value[0])
case LabelOpLT:
return pointer.To(value < term.Value[0])
case LabelOpLTNumeric:
left, right, ok := compare.GetNumbers(value, term.Value[0])
if !ok {
return nil
}
return pointer.To(left < right)
case LabelOpLTENumeric:
left, right, ok := compare.GetNumbers(value, term.Value[0])
if !ok {
return nil
}
return pointer.To(left <= right)
default:
panic(fmt.Sprintf("unsupported label term operator: %v", term.Op))
}
}