-
Notifications
You must be signed in to change notification settings - Fork 214
/
int.go
303 lines (280 loc) · 8.65 KB
/
int.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"fmt"
"math"
"reflect"
"strconv"
"time"
"github.com/google/cel-go/common/types/ref"
anypb "google.golang.org/protobuf/types/known/anypb"
structpb "google.golang.org/protobuf/types/known/structpb"
wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
)
// Int type that implements ref.Val as well as comparison and math operators.
type Int int64
// Int constants used for comparison results.
const (
// IntZero is the zero-value for Int
IntZero = Int(0)
IntOne = Int(1)
IntNegOne = Int(-1)
)
var (
// int32WrapperType reflected type for protobuf int32 wrapper type.
int32WrapperType = reflect.TypeOf(&wrapperspb.Int32Value{})
// int64WrapperType reflected type for protobuf int64 wrapper type.
int64WrapperType = reflect.TypeOf(&wrapperspb.Int64Value{})
)
// Add implements traits.Adder.Add.
func (i Int) Add(other ref.Val) ref.Val {
otherInt, ok := other.(Int)
if !ok {
return MaybeNoSuchOverloadErr(other)
}
val, err := addInt64Checked(int64(i), int64(otherInt))
if err != nil {
return WrapErr(err)
}
return Int(val)
}
// Compare implements traits.Comparer.Compare.
func (i Int) Compare(other ref.Val) ref.Val {
switch ov := other.(type) {
case Double:
if math.IsNaN(float64(ov)) {
return NewErr("NaN values cannot be ordered")
}
return compareIntDouble(i, ov)
case Int:
return compareInt(i, ov)
case Uint:
return compareIntUint(i, ov)
default:
return MaybeNoSuchOverloadErr(other)
}
}
// ConvertToNative implements ref.Val.ConvertToNative.
func (i Int) ConvertToNative(typeDesc reflect.Type) (any, error) {
switch typeDesc.Kind() {
case reflect.Int, reflect.Int32:
// Enums are also mapped as int32 derivations.
// Note, the code doesn't convert to the enum value directly since this is not known, but
// the net effect with respect to proto-assignment is handled correctly by the reflection
// Convert method.
v, err := int64ToInt32Checked(int64(i))
if err != nil {
return nil, err
}
return reflect.ValueOf(v).Convert(typeDesc).Interface(), nil
case reflect.Int8:
v, err := int64ToInt8Checked(int64(i))
if err != nil {
return nil, err
}
return reflect.ValueOf(v).Convert(typeDesc).Interface(), nil
case reflect.Int16:
v, err := int64ToInt16Checked(int64(i))
if err != nil {
return nil, err
}
return reflect.ValueOf(v).Convert(typeDesc).Interface(), nil
case reflect.Int64:
return reflect.ValueOf(i).Convert(typeDesc).Interface(), nil
case reflect.Ptr:
switch typeDesc {
case anyValueType:
// Primitives must be wrapped before being set on an Any field.
return anypb.New(wrapperspb.Int64(int64(i)))
case int32WrapperType:
// Convert the value to a wrapperspb.Int32Value, error on overflow.
v, err := int64ToInt32Checked(int64(i))
if err != nil {
return nil, err
}
return wrapperspb.Int32(v), nil
case int64WrapperType:
// Convert the value to a wrapperspb.Int64Value.
return wrapperspb.Int64(int64(i)), nil
case jsonValueType:
// The proto-to-JSON conversion rules would convert all 64-bit integer values to JSON
// decimal strings. Because CEL ints might come from the automatic widening of 32-bit
// values in protos, the JSON type is chosen dynamically based on the value.
//
// - Integers -2^53-1 < n < 2^53-1 are encoded as JSON numbers.
// - Integers outside this range are encoded as JSON strings.
//
// The integer to float range represents the largest interval where such a conversion
// can round-trip accurately. Thus, conversions from a 32-bit source can expect a JSON
// number as with protobuf. Those consuming JSON from a 64-bit source must be able to
// handle either a JSON number or a JSON decimal string. To handle these cases safely
// the string values must be explicitly converted to int() within a CEL expression;
// however, it is best to simply stay within the JSON number range when building JSON
// objects in CEL.
if i.isJSONSafe() {
return structpb.NewNumberValue(float64(i)), nil
}
// Proto3 to JSON conversion requires string-formatted int64 values
// since the conversion to floating point would result in truncation.
return structpb.NewStringValue(strconv.FormatInt(int64(i), 10)), nil
}
switch typeDesc.Elem().Kind() {
case reflect.Int32:
// Convert the value to a wrapperspb.Int32Value, error on overflow.
v, err := int64ToInt32Checked(int64(i))
if err != nil {
return nil, err
}
p := reflect.New(typeDesc.Elem())
p.Elem().Set(reflect.ValueOf(v).Convert(typeDesc.Elem()))
return p.Interface(), nil
case reflect.Int64:
v := int64(i)
p := reflect.New(typeDesc.Elem())
p.Elem().Set(reflect.ValueOf(v).Convert(typeDesc.Elem()))
return p.Interface(), nil
}
case reflect.Interface:
iv := i.Value()
if reflect.TypeOf(iv).Implements(typeDesc) {
return iv, nil
}
if reflect.TypeOf(i).Implements(typeDesc) {
return i, nil
}
}
return nil, fmt.Errorf("unsupported type conversion from 'int' to %v", typeDesc)
}
// ConvertToType implements ref.Val.ConvertToType.
func (i Int) ConvertToType(typeVal ref.Type) ref.Val {
switch typeVal {
case IntType:
return i
case UintType:
u, err := int64ToUint64Checked(int64(i))
if err != nil {
return WrapErr(err)
}
return Uint(u)
case DoubleType:
return Double(i)
case StringType:
return String(fmt.Sprintf("%d", int64(i)))
case TimestampType:
// The maximum positive value that can be passed to time.Unix is math.MaxInt64 minus the number
// of seconds between year 1 and year 1970. See comments on unixToInternal.
if int64(i) < minUnixTime || int64(i) > maxUnixTime {
return celErrTimestampOverflow
}
return timestampOf(time.Unix(int64(i), 0).UTC())
case TypeType:
return IntType
}
return NewErr("type conversion error from '%s' to '%s'", IntType, typeVal)
}
// Divide implements traits.Divider.Divide.
func (i Int) Divide(other ref.Val) ref.Val {
otherInt, ok := other.(Int)
if !ok {
return MaybeNoSuchOverloadErr(other)
}
val, err := divideInt64Checked(int64(i), int64(otherInt))
if err != nil {
return WrapErr(err)
}
return Int(val)
}
// Equal implements ref.Val.Equal.
func (i Int) Equal(other ref.Val) ref.Val {
switch ov := other.(type) {
case Double:
if math.IsNaN(float64(ov)) {
return False
}
return Bool(compareIntDouble(i, ov) == 0)
case Int:
return Bool(i == ov)
case Uint:
return Bool(compareIntUint(i, ov) == 0)
default:
return False
}
}
// IsZeroValue returns true if integer is equal to 0
func (i Int) IsZeroValue() bool {
return i == IntZero
}
// Modulo implements traits.Modder.Modulo.
func (i Int) Modulo(other ref.Val) ref.Val {
otherInt, ok := other.(Int)
if !ok {
return MaybeNoSuchOverloadErr(other)
}
val, err := moduloInt64Checked(int64(i), int64(otherInt))
if err != nil {
return WrapErr(err)
}
return Int(val)
}
// Multiply implements traits.Multiplier.Multiply.
func (i Int) Multiply(other ref.Val) ref.Val {
otherInt, ok := other.(Int)
if !ok {
return MaybeNoSuchOverloadErr(other)
}
val, err := multiplyInt64Checked(int64(i), int64(otherInt))
if err != nil {
return WrapErr(err)
}
return Int(val)
}
// Negate implements traits.Negater.Negate.
func (i Int) Negate() ref.Val {
val, err := negateInt64Checked(int64(i))
if err != nil {
return WrapErr(err)
}
return Int(val)
}
// Subtract implements traits.Subtractor.Subtract.
func (i Int) Subtract(subtrahend ref.Val) ref.Val {
subtraInt, ok := subtrahend.(Int)
if !ok {
return MaybeNoSuchOverloadErr(subtrahend)
}
val, err := subtractInt64Checked(int64(i), int64(subtraInt))
if err != nil {
return WrapErr(err)
}
return Int(val)
}
// Type implements ref.Val.Type.
func (i Int) Type() ref.Type {
return IntType
}
// Value implements ref.Val.Value.
func (i Int) Value() any {
return int64(i)
}
// isJSONSafe indicates whether the int is safely representable as a floating point value in JSON.
func (i Int) isJSONSafe() bool {
return i >= minIntJSON && i <= maxIntJSON
}
const (
// maxIntJSON is defined as the Number.MAX_SAFE_INTEGER value per EcmaScript 6.
maxIntJSON = 1<<53 - 1
// minIntJSON is defined as the Number.MIN_SAFE_INTEGER value per EcmaScript 6.
minIntJSON = -maxIntJSON
)