Debian Codegraph @

pkg/cel/quantity.go

raw
1 /*
2 Copyright 2023 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package cel
18
19 import (
20 "fmt"
21 "reflect"
22
23 "github.com/google/cel-go/cel"
24 "github.com/google/cel-go/checker/decls"
25 "github.com/google/cel-go/common/types"
26 "github.com/google/cel-go/common/types/ref"
27 "k8s.io/apimachinery/pkg/api/resource"
28 )
29
30 var (
31 QuantityObject = decls.NewObjectType("kubernetes.Quantity")
32 quantityTypeValue = types.NewTypeValue("kubernetes.Quantity")
33 QuantityType = cel.ObjectType("kubernetes.Quantity")
34 )
35
36 // Quantity provdes a CEL representation of a resource.Quantity
37 type Quantity struct {
38 *resource.Quantity
39 }
40
41 func (d Quantity) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {
42 if reflect.TypeOf(d.Quantity).AssignableTo(typeDesc) {
43 return d.Quantity, nil
44 }
45 if reflect.TypeOf("").AssignableTo(typeDesc) {
46 return d.Quantity.String(), nil
47 }
48 return nil, fmt.Errorf("type conversion error from 'Quantity' to '%v'", typeDesc)
49 }
50
51 func (d Quantity) ConvertToType(typeVal ref.Type) ref.Val {
52 switch typeVal {
53 case quantityTypeValue:
54 return d
55 case types.TypeType:
56 return quantityTypeValue
57 default:
58 return types.NewErr("type conversion error from '%s' to '%s'", quantityTypeValue, typeVal)
59 }
60 }
61
62 func (d Quantity) Equal(other ref.Val) ref.Val {
63 otherDur, ok := other.(Quantity)
64 if !ok {
65 return types.MaybeNoSuchOverloadErr(other)
66 }
67 return types.Bool(d.Quantity.Equal(*otherDur.Quantity))
68 }
69
70 func (d Quantity) Type() ref.Type {
71 return quantityTypeValue
72 }
73
74 func (d Quantity) Value() interface{} {
75 return d.Quantity
76 }