-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathmap_value.go
More file actions
352 lines (312 loc) · 9.14 KB
/
map_value.go
File metadata and controls
352 lines (312 loc) · 9.14 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright 2023-2026 Buf Technologies, Inc.
//
// 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 protovalidate
import (
"errors"
"fmt"
"math"
"reflect"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/common/types/traits"
"google.golang.org/protobuf/reflect/protoreflect"
)
// protoMap wraps a protoreflect.Map to implement ref.Val and traits.Mapper,
// allowing lazy access to map entries without copying the entire map upfront.
// This provides significant performance improvements when validating map fields.
type protoMap struct {
adapter types.Adapter
m protoreflect.Map
keyDesc protoreflect.FieldDescriptor
valDesc protoreflect.FieldDescriptor
}
// newProtoMap creates a new protoMap wrapper around the given protoreflect.Map.
// The adapter is used to convert native values to CEL values. The keyDesc and
// valDesc are the field descriptors for the map's key and value types.
func newProtoMap(
adapter types.Adapter,
mapVal protoreflect.Map,
keyDesc protoreflect.FieldDescriptor,
valDesc protoreflect.FieldDescriptor,
) *protoMap {
return &protoMap{
adapter: adapter,
m: mapVal,
keyDesc: keyDesc,
valDesc: valDesc,
}
}
// ref.Val implementation
func (m *protoMap) ConvertToNative(typeDesc reflect.Type) (any, error) {
switch typeDesc.Kind() {
case reflect.Map:
nativeMap := reflect.MakeMapWithSize(typeDesc, m.m.Len())
var convErr error
m.m.Range(func(key protoreflect.MapKey, val protoreflect.Value) bool {
nativeKey, err := m.adapter.NativeToValue(key.Interface()).ConvertToNative(typeDesc.Key())
if err != nil {
convErr = err
return false
}
nativeVal, err := m.nativeValue(val).ConvertToNative(typeDesc.Elem())
if err != nil {
convErr = err
return false
}
nativeMap.SetMapIndex(reflect.ValueOf(nativeKey), reflect.ValueOf(nativeVal))
return true
})
if convErr != nil {
return nil, convErr
}
return nativeMap.Interface(), nil
case reflect.Interface:
if reflect.TypeFor[*protoMap]().Implements(typeDesc) {
return m, nil
}
if reflect.TypeOf(m.m).Implements(typeDesc) {
return m.m, nil
}
}
return nil, fmt.Errorf("unsupported type conversion: %v to %v", m.Type(), typeDesc)
}
func (m *protoMap) ConvertToType(typeVal ref.Type) ref.Val {
switch typeVal {
case types.MapType:
return m
case types.TypeType:
return types.MapType
}
return types.NewErr("type conversion error from '%s' to '%s'", types.MapType, typeVal)
}
func (m *protoMap) Equal(other ref.Val) ref.Val {
otherMap, ok := other.(traits.Mapper)
if !ok {
return types.False
}
otherSize, ok := otherMap.Size().(types.Int)
if !ok || m.m.Len() != int(otherSize) {
return types.False
}
var result ref.Val = types.True
m.m.Range(func(key protoreflect.MapKey, val protoreflect.Value) bool {
celKey := m.adapter.NativeToValue(m.toCelKey(key))
otherVal, found := otherMap.Find(celKey)
if !found {
result = types.False
return false
}
celVal := m.nativeValue(val)
eq := celVal.Equal(otherVal)
if eq != types.True {
result = eq
return false
}
return true
})
return result
}
func (m *protoMap) Type() ref.Type {
return types.MapType
}
func (m *protoMap) Value() any {
return m.m
}
// traits.Container implementation
func (m *protoMap) Contains(key ref.Val) ref.Val {
_, found := m.Find(key)
return types.Bool(found)
}
// traits.Indexer implementation
func (m *protoMap) Get(key ref.Val) ref.Val {
val, found := m.Find(key)
if !found {
return types.ValOrErr(val, "no such key: %v", key)
}
return val
}
// traits.Iterable implementation
func (m *protoMap) Iterator() traits.Iterator {
keys := make([]protoreflect.MapKey, 0, m.m.Len())
m.m.Range(func(key protoreflect.MapKey, _ protoreflect.Value) bool {
keys = append(keys, key)
return true
})
return &protoMapIterator{
adapter: m.adapter,
parent: m,
keys: keys,
}
}
// traits.Sizer implementation
func (m *protoMap) Size() ref.Val {
return types.Int(m.m.Len())
}
// traits.Mapper implementation
func (m *protoMap) Find(key ref.Val) (ref.Val, bool) {
if val, found := m.findInternal(key); found {
return val, true
}
// Handle numeric type coercion - CEL uses 64-bit integers
switch celKey := key.(type) {
case types.Double:
if intKey, ok := doubleToInt64Lossless(float64(celKey)); ok {
if val, found := m.findInternal(types.Int(intKey)); found {
return val, true
}
}
if uintKey, ok := doubleToUint64Lossless(float64(celKey)); ok {
return m.findInternal(types.Uint(uintKey))
}
case types.Int:
if uintKey, ok := int64ToUint64Lossless(int64(celKey)); ok {
return m.findInternal(types.Uint(uintKey))
}
case types.Uint:
if intKey, ok := uint64ToInt64Lossless(uint64(celKey)); ok {
return m.findInternal(types.Int(intKey))
}
}
return nil, false
}
func (m *protoMap) findInternal(key ref.Val) (ref.Val, bool) {
nativeKey, err := m.toNativeKey(key)
if err != nil {
return nil, false
}
protoKey := protoreflect.ValueOf(nativeKey).MapKey()
val := m.m.Get(protoKey)
if !val.IsValid() {
return nil, false
}
return m.nativeValue(val), true
}
// toNativeKey converts a CEL key value to the appropriate native Go type for
// map lookup based on the map's key field descriptor.
func (m *protoMap) toNativeKey(key ref.Val) (any, error) {
switch m.keyDesc.Kind() {
case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
if keyVal, ok := key.Value().(int64); ok {
if keyVal < math.MinInt32 || keyVal > math.MaxInt32 {
return nil, fmt.Errorf("int64 key %d out of int32 range", keyVal)
}
return int32(keyVal), nil
}
case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
if keyVal, ok := key.Value().(int64); ok {
return keyVal, nil
}
case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
if keyVal, ok := key.Value().(uint64); ok {
if keyVal > math.MaxUint32 {
return nil, fmt.Errorf("uint64 key %d out of uint32 range", keyVal)
}
return uint32(keyVal), nil
}
case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
if keyVal, ok := key.Value().(uint64); ok {
return keyVal, nil
}
case protoreflect.BoolKind:
if keyVal, ok := key.Value().(bool); ok {
return keyVal, nil
}
case protoreflect.StringKind:
if keyVal, ok := key.Value().(string); ok {
return keyVal, nil
}
}
return nil, fmt.Errorf("unsupported map key type: %v", m.keyDesc.Kind())
}
// toCelKey converts a protoreflect.MapKey to the appropriate CEL type.
// CEL uses 64-bit integers, so 32-bit integer types are widened.
func (m *protoMap) toCelKey(key protoreflect.MapKey) any {
switch m.keyDesc.Kind() {
case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
return key.Int()
case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
return key.Uint()
default:
return key.Interface()
}
}
// nativeValue converts a protoreflect.Value to a CEL ref.Val.
func (m *protoMap) nativeValue(val protoreflect.Value) ref.Val {
v := val.Interface()
// For message values, val.Interface() returns proto.Message (not
// protoreflect.Message), so NativeToValue handles it directly.
return m.adapter.NativeToValue(v)
}
var (
_ ref.Val = (*protoMap)(nil)
_ traits.Mapper = (*protoMap)(nil)
)
// protoMapIterator iterates over the keys of a protoMap.
type protoMapIterator struct {
adapter types.Adapter
parent *protoMap
keys []protoreflect.MapKey
idx int
}
func (it *protoMapIterator) ConvertToNative(_ reflect.Type) (any, error) {
return nil, errors.New("type conversion on iterators not supported")
}
func (it *protoMapIterator) ConvertToType(_ ref.Type) ref.Val {
return types.NoSuchOverloadErr()
}
func (it *protoMapIterator) Equal(_ ref.Val) ref.Val {
return types.NoSuchOverloadErr()
}
func (it *protoMapIterator) Type() ref.Type {
return types.IteratorType
}
func (it *protoMapIterator) Value() any {
return nil
}
func (it *protoMapIterator) HasNext() ref.Val {
return types.Bool(it.idx < len(it.keys))
}
func (it *protoMapIterator) Next() ref.Val {
if it.idx < len(it.keys) {
key := it.keys[it.idx]
it.idx++
return it.adapter.NativeToValue(it.parent.toCelKey(key))
}
return nil
}
var _ traits.Iterator = (*protoMapIterator)(nil)
// Numeric conversion helpers (borrowed from cel-go)
func doubleToInt64Lossless(v float64) (int64, bool) {
i := int64(v)
return i, float64(i) == v
}
func doubleToUint64Lossless(v float64) (uint64, bool) {
if v < 0 {
return 0, false
}
u := uint64(v)
return u, float64(u) == v
}
func int64ToUint64Lossless(v int64) (uint64, bool) {
if v < 0 {
return 0, false
}
return uint64(v), true
}
func uint64ToInt64Lossless(v uint64) (int64, bool) {
if v > math.MaxInt64 {
return 0, false
}
return int64(v), true
}