Debian Codegraph @

pkg/cel/ip.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 "math"
22 "net/netip"
23 "reflect"
24
25 "github.com/google/cel-go/cel"
26 "github.com/google/cel-go/common/types"
27 "github.com/google/cel-go/common/types/ref"
28 )
29
30 // IP provides a CEL representation of an IP address.
31 type IP struct {
32 netip.Addr
33 }
34
35 var (
36 IPType = cel.OpaqueType("net.IP")
37 )
38
39 // ConvertToNative implements ref.Val.ConvertToNative.
40 func (d IP) ConvertToNative(typeDesc reflect.Type) (any, error) {
41 if reflect.TypeOf(d.Addr).AssignableTo(typeDesc) {
42 return d.Addr, nil
43 }
44 if reflect.TypeOf("").AssignableTo(typeDesc) {
45 return d.Addr.String(), nil
46 }
47 return nil, fmt.Errorf("type conversion error from 'IP' to '%v'", typeDesc)
48 }
49
50 // ConvertToType implements ref.Val.ConvertToType.
51 func (d IP) ConvertToType(typeVal ref.Type) ref.Val {
52 switch typeVal {
53 case IPType:
54 return d
55 case types.TypeType:
56 return IPType
57 case types.StringType:
58 return types.String(d.Addr.String())
59 }
60 return types.NewErr("type conversion error from '%s' to '%s'", IPType, typeVal)
61 }
62
63 // Equal implements ref.Val.Equal.
64 func (d IP) Equal(other ref.Val) ref.Val {
65 otherD, ok := other.(IP)
66 if !ok {
67 return types.ValOrErr(other, "no such overload")
68 }
69 return types.Bool(d.Addr == otherD.Addr)
70 }
71
72 // Type implements ref.Val.Type.
73 func (d IP) Type() ref.Type {
74 return IPType
75 }
76
77 // Value implements ref.Val.Value.
78 func (d IP) Value() any {
79 return d.Addr
80 }
81
82 // Size returns the size of the IP address in bytes.
83 // Used in the size estimation of the runtime cost.
84 func (d IP) Size() ref.Val {
85 return types.Int(int(math.Ceil(float64(d.Addr.BitLen()) / 8)))
86 }