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