Debian Codegraph @

common/types/map.go

raw symbols SCIP
1 // Copyright 2018 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package types
16
17 import (
18 "fmt"
19 "reflect"
20 "sort"
21 "strings"
22 "unicode"
23
24 "google.golang.org/protobuf/proto"
25 "google.golang.org/protobuf/reflect/protoreflect"
26
27 "github.com/google/cel-go/common/types/pb"
28 "github.com/google/cel-go/common/types/ref"
29 "github.com/google/cel-go/common/types/traits"
30
31 anypb "google.golang.org/protobuf/types/known/anypb"
32 structpb "google.golang.org/protobuf/types/known/structpb"
33 )
34
35 // NewDynamicMap returns a traits.Mapper value with dynamic key, value pairs.
36 func NewDynamicMap(adapter Adapter, value any) traits.Mapper {
37 refValue := reflect.ValueOf(value)
38 return &baseMap{
39 Adapter: adapter,
40 mapAccessor: newReflectMapAccessor(adapter, refValue),
41 value: value,
42 size: refValue.Len(),
43 }
44 }
45
46 // NewJSONStruct creates a traits.Mapper implementation backed by a JSON struct that has been
47 // encoded in protocol buffer form.
48 //
49 // The `adapter` argument provides type adaptation capabilities from proto to CEL.
50 func NewJSONStruct(adapter Adapter, value *structpb.Struct) traits.Mapper {
51 fields := value.GetFields()
52 return &baseMap{
53 Adapter: adapter,
54 mapAccessor: newJSONStructAccessor(adapter, fields),
55 value: value,
56 size: len(fields),
57 }
58 }
59
60 // NewRefValMap returns a specialized traits.Mapper with CEL valued keys and values.
61 func NewRefValMap(adapter Adapter, value map[ref.Val]ref.Val) traits.Mapper {
62 return &baseMap{
63 Adapter: adapter,
64 mapAccessor: newRefValMapAccessor(value),
65 value: value,
66 size: len(value),
67 }
68 }
69
70 // NewStringInterfaceMap returns a specialized traits.Mapper with string keys and interface values.
71 func NewStringInterfaceMap(adapter Adapter, value map[string]any) traits.Mapper {
72 return &baseMap{
73 Adapter: adapter,
74 mapAccessor: newStringIfaceMapAccessor(adapter, value),
75 value: value,
76 size: len(value),
77 }
78 }
79
80 // NewStringStringMap returns a specialized traits.Mapper with string keys and values.
81 func NewStringStringMap(adapter Adapter, value map[string]string) traits.Mapper {
82 return &baseMap{
83 Adapter: adapter,
84 mapAccessor: newStringMapAccessor(value),
85 value: value,
86 size: len(value),
87 }
88 }
89
90 // NewProtoMap returns a specialized traits.Mapper for handling protobuf map values.
91 func NewProtoMap(adapter Adapter, value *pb.Map) traits.Mapper {
92 return &protoMap{
93 Adapter: adapter,
94 value: value,
95 }
96 }
97
98 // NewMutableMap constructs a mutable map from an adapter and a set of map values.
99 func NewMutableMap(adapter Adapter, mutableValues map[ref.Val]ref.Val) traits.MutableMapper {
100 mutableCopy := make(map[ref.Val]ref.Val, len(mutableValues))
101 for k, v := range mutableValues {
102 mutableCopy[k] = v
103 }
104 m := &mutableMap{
105 baseMap: &baseMap{
106 Adapter: adapter,
107 mapAccessor: newRefValMapAccessor(mutableCopy),
108 value: mutableCopy,
109 size: len(mutableCopy),
110 },
111 mutableValues: mutableCopy,
112 }
113 return m
114 }
115
116 // mapAccessor is a private interface for finding values within a map and iterating over the keys.
117 // This interface implements portions of the API surface area required by the traits.Mapper
118 // interface.
119 type mapAccessor interface {
120 // Find returns a value, if one exists, for the input key.
121 //
122 // If the key is not found the function returns (nil, false).
123 Find(ref.Val) (ref.Val, bool)
124
125 // Iterator returns an Iterator over the map key set.
126 Iterator() traits.Iterator
127
128 // Fold calls the FoldEntry method for each (key, value) pair in the map.
129 Fold(traits.Folder)
130 }
131
132 // baseMap is a reflection based map implementation designed to handle a variety of map-like types.
133 //
134 // Since CEL is side-effect free, the base map represents an immutable object.
135 type baseMap struct {
136 // TypeAdapter used to convert keys and values accessed within the map.
137 Adapter
138
139 // mapAccessor interface implementation used to find and iterate over map keys.
140 mapAccessor
141
142 // value is the native Go value upon which the map type operators.
143 value any
144
145 // size is the number of entries in the map.
146 size int
147 }
148
149 // Contains implements the traits.Container interface method.
150 func (m *baseMap) Contains(index ref.Val) ref.Val {
151 _, found := m.Find(index)
152 return Bool(found)
153 }
154
155 // ConvertToNative implements the ref.Val interface method.
156 func (m *baseMap) ConvertToNative(typeDesc reflect.Type) (any, error) {
157 // If the map is already assignable to the desired type return it, e.g. interfaces and
158 // maps with the same key value types.
159 if typeDesc == reflect.TypeFor[any]() {
160 typeDesc = reflect.TypeFor[map[any]any]()
161 }
162 if reflect.TypeOf(m.value).AssignableTo(typeDesc) {
163 return m.value, nil
164 }
165 if reflect.TypeOf(m).AssignableTo(typeDesc) {
166 return m, nil
167 }
168 switch typeDesc {
169 case anyValueType:
170 json, err := m.ConvertToNative(JSONStructType)
171 if err != nil {
172 return nil, err
173 }
174 return anypb.New(json.(proto.Message))
175 case JSONValueType, JSONStructType:
176 jsonEntries, err :=
177 m.ConvertToNative(reflect.TypeOf(map[string]*structpb.Value{}))
178 if err != nil {
179 return nil, err
180 }
181 jsonMap := &structpb.Struct{Fields: jsonEntries.(map[string]*structpb.Value)}
182 if typeDesc == JSONStructType {
183 return jsonMap, nil
184 }
185 return structpb.NewStructValue(jsonMap), nil
186 }
187
188 // Unwrap pointers, but track their use.
189 isPtr := false
190 if typeDesc.Kind() == reflect.Ptr {
191 tk := typeDesc
192 typeDesc = typeDesc.Elem()
193 if typeDesc.Kind() == reflect.Ptr {
194 return nil, fmt.Errorf("unsupported type conversion to '%v'", tk)
195 }
196 isPtr = true
197 }
198 switch typeDesc.Kind() {
199 // Map conversion.
200 case reflect.Map:
201 otherKey := typeDesc.Key()
202 otherElem := typeDesc.Elem()
203 nativeMap := reflect.MakeMapWithSize(typeDesc, m.size)
204 it := m.Iterator()
205 for it.HasNext() == True {
206 key := it.Next()
207 refKeyValue, err := key.ConvertToNative(otherKey)
208 if err != nil {
209 return nil, err
210 }
211 refElemValue, err := m.Get(key).ConvertToNative(otherElem)
212 if err != nil {
213 return nil, err
214 }
215 nativeMap.SetMapIndex(reflect.ValueOf(refKeyValue), reflect.ValueOf(refElemValue))
216 }
217 return nativeMap.Interface(), nil
218 case reflect.Struct:
219 nativeStructPtr := reflect.New(typeDesc)
220 nativeStruct := nativeStructPtr.Elem()
221 it := m.Iterator()
222 for it.HasNext() == True {
223 key := it.Next()
224 // Ensure the field name being referenced is exported.
225 // Only exported (public) field names can be set by reflection, where the name
226 // must be at least one character in length and start with an upper-case letter.
227 fieldName := key.ConvertToType(StringType)
228 if IsError(fieldName) {
229 return nil, fieldName.(*Err)
230 }
231 name := string(fieldName.(String))
232 name = upperCamelCase(name)
233 fieldRef := nativeStruct.FieldByName(name)
234 if !fieldRef.IsValid() {
235 return nil, fmt.Errorf("type conversion error, no such field '%s' in type '%v'", name, typeDesc)
236 }
237 fieldValue, err := m.Get(key).ConvertToNative(fieldRef.Type())
238 if err != nil {
239 return nil, err
240 }
241 fieldRef.Set(reflect.ValueOf(fieldValue))
242 }
243 if isPtr {
244 return nativeStructPtr.Interface(), nil
245 }
246 return nativeStruct.Interface(), nil
247 }
248 return nil, fmt.Errorf("type conversion error from map to '%v'", typeDesc)
249 }
250
251 // ConvertToType implements the ref.Val interface method.
252 func (m *baseMap) ConvertToType(typeVal ref.Type) ref.Val {
253 switch typeVal {
254 case MapType:
255 return m
256 case TypeType:
257 return MapType
258 }
259 return NewErr("type conversion error from '%s' to '%s'", MapType, typeVal)
260 }
261
262 // Equal implements the ref.Val interface method.
263 func (m *baseMap) Equal(other ref.Val) ref.Val {
264 otherMap, ok := other.(traits.Mapper)
265 if !ok {
266 return False
267 }
268 if m.Size() != otherMap.Size() {
269 return False
270 }
271 it := m.Iterator()
272 for it.HasNext() == True {
273 key := it.Next()
274 thisVal, _ := m.Find(key)
275 otherVal, found := otherMap.Find(key)
276 if !found {
277 return False
278 }
279 valEq := Equal(thisVal, otherVal)
280 if valEq == False {
281 return False
282 }
283 }
284 return True
285 }
286
287 // Get implements the traits.Indexer interface method.
288 func (m *baseMap) Get(key ref.Val) ref.Val {
289 v, found := m.Find(key)
290 if !found {
291 return ValOrErr(v, "no such key: %v", key)
292 }
293 return v
294 }
295
296 // IsZeroValue returns true if the map is empty.
297 func (m *baseMap) IsZeroValue() bool {
298 return m.size == 0
299 }
300
301 // Size implements the traits.Sizer interface method.
302 func (m *baseMap) Size() ref.Val {
303 return Int(m.size)
304 }
305
306 // String converts the map into a human-readable string.
307 func (m *baseMap) String() string {
308 var sb strings.Builder
309 sb.WriteString("{")
310 it := m.Iterator()
311 i := 0
312 for it.HasNext() == True {
313 k := it.Next()
314 v, _ := m.Find(k)
315 sb.WriteString(fmt.Sprintf("%v: %v", k, v))
316 if i != m.size-1 {
317 sb.WriteString(", ")
318 }
319 i++
320 }
321 sb.WriteString("}")
322 return sb.String()
323 }
324
325 type baseMapEntry struct {
326 key string
327 val string
328 }
329
330 func formatMap(m traits.Mapper, sb *strings.Builder) {
331 it := m.Iterator()
332 var ents []baseMapEntry
333 if s, ok := m.Size().(Int); ok {
334 ents = make([]baseMapEntry, 0, int(s))
335 }
336 for it.HasNext() == True {
337 k := it.Next()
338 v, _ := m.Find(k)
339 ents = append(ents, baseMapEntry{Format(k), Format(v)})
340 }
341 sort.SliceStable(ents, func(i, j int) bool {
342 return ents[i].key < ents[j].key
343 })
344 sb.WriteString("{")
345 for i, ent := range ents {
346 if i > 0 {
347 sb.WriteString(", ")
348 }
349 sb.WriteString(ent.key)
350 sb.WriteString(": ")
351 sb.WriteString(ent.val)
352 }
353 sb.WriteString("}")
354 }
355
356 func (m *baseMap) format(sb *strings.Builder) {
357 formatMap(m, sb)
358 }
359
360 // Type implements the ref.Val interface method.
361 func (m *baseMap) Type() ref.Type {
362 return MapType
363 }
364
365 // Value implements the ref.Val interface method.
366 func (m *baseMap) Value() any {
367 return m.value
368 }
369
370 // mutableMap holds onto a set of mutable values which are used for intermediate computations.
371 type mutableMap struct {
372 *baseMap
373 mutableValues map[ref.Val]ref.Val
374 }
375
376 // Insert implements the traits.MutableMapper interface method, returning true if the key insertion
377 // succeeds.
378 func (m *mutableMap) Insert(k, v ref.Val) ref.Val {
379 if _, found := m.Find(k); found {
380 return NewErr("insert failed: key %v already exists", k)
381 }
382 m.mutableValues[k] = v
383 return m
384 }
385
386 // ToImmutableMap implements the traits.MutableMapper interface method, converting a mutable map
387 // an immutable map implementation.
388 func (m *mutableMap) ToImmutableMap() traits.Mapper {
389 return NewRefValMap(m.Adapter, m.mutableValues)
390 }
391
392 func newJSONStructAccessor(adapter Adapter, st map[string]*structpb.Value) mapAccessor {
393 return &jsonStructAccessor{
394 Adapter: adapter,
395 st: st,
396 }
397 }
398
399 type jsonStructAccessor struct {
400 Adapter
401 st map[string]*structpb.Value
402 }
403
404 // Find searches the json struct field map for the input key value and returns (value, true) if
405 // found.
406 //
407 // If the key is not found the function returns (nil, false).
408 func (a *jsonStructAccessor) Find(key ref.Val) (ref.Val, bool) {
409 strKey, ok := key.(String)
410 if !ok {
411 return nil, false
412 }
413 keyVal, found := a.st[string(strKey)]
414 if !found {
415 return nil, false
416 }
417 return a.NativeToValue(keyVal), true
418 }
419
420 // Iterator creates a new traits.Iterator from the set of JSON struct field names.
421 func (a *jsonStructAccessor) Iterator() traits.Iterator {
422 // Copy the keys to make their order stable.
423 mapKeys := make([]string, len(a.st))
424 i := 0
425 for k := range a.st {
426 mapKeys[i] = k
427 i++
428 }
429 return &stringKeyIterator{
430 mapKeys: mapKeys,
431 len: len(mapKeys),
432 }
433 }
434
435 // Fold calls the FoldEntry method for each (key, value) pair in the map.
436 func (a *jsonStructAccessor) Fold(f traits.Folder) {
437 for k, v := range a.st {
438 if !f.FoldEntry(k, v) {
439 break
440 }
441 }
442 }
443
444 func newReflectMapAccessor(adapter Adapter, value reflect.Value) mapAccessor {
445 keyType := value.Type().Key()
446 return &reflectMapAccessor{
447 Adapter: adapter,
448 refValue: value,
449 keyType: keyType,
450 }
451 }
452
453 type reflectMapAccessor struct {
454 Adapter
455 refValue reflect.Value
456 keyType reflect.Type
457 }
458
459 // Find converts the input key to a native Golang type and then uses reflection to find the key,
460 // returning (value, true) if present.
461 //
462 // If the key is not found the function returns (nil, false).
463 func (m *reflectMapAccessor) Find(key ref.Val) (ref.Val, bool) {
464 if m.refValue.Len() == 0 {
465 return nil, false
466 }
467 if keyVal, found := m.findInternal(key); found {
468 return keyVal, true
469 }
470 switch k := key.(type) {
471 // Double is not a valid proto map key type, so check for the key as an int or uint.
472 case Double:
473 if ik, ok := doubleToInt64Lossless(float64(k)); ok {
474 if keyVal, found := m.findInternal(Int(ik)); found {
475 return keyVal, true
476 }
477 }
478 if uk, ok := doubleToUint64Lossless(float64(k)); ok {
479 return m.findInternal(Uint(uk))
480 }
481 // map keys of type double are not supported.
482 case Int:
483 if uk, ok := int64ToUint64Lossless(int64(k)); ok {
484 return m.findInternal(Uint(uk))
485 }
486 case Uint:
487 if ik, ok := uint64ToInt64Lossless(uint64(k)); ok {
488 return m.findInternal(Int(ik))
489 }
490 }
491 return nil, false
492 }
493
494 // findInternal attempts to convert the incoming key to the map's internal native type
495 // and then returns the value, if found.
496 func (m *reflectMapAccessor) findInternal(key ref.Val) (ref.Val, bool) {
497 k, err := key.ConvertToNative(m.keyType)
498 if err != nil {
499 return nil, false
500 }
501 refKey := reflect.ValueOf(k)
502 val := m.refValue.MapIndex(refKey)
503 if val.IsValid() {
504 return m.NativeToValue(val.Interface()), true
505 }
506 return nil, false
507 }
508
509 // Iterator creates a Golang reflection based traits.Iterator.
510 func (m *reflectMapAccessor) Iterator() traits.Iterator {
511 return &mapIterator{
512 Adapter: m.Adapter,
513 mapKeys: m.refValue.MapRange(),
514 len: m.refValue.Len(),
515 }
516 }
517
518 // Fold calls the FoldEntry method for each (key, value) pair in the map.
519 func (m *reflectMapAccessor) Fold(f traits.Folder) {
520 mapRange := m.refValue.MapRange()
521 for mapRange.Next() {
522 if !f.FoldEntry(mapRange.Key().Interface(), mapRange.Value().Interface()) {
523 break
524 }
525 }
526 }
527
528 func newRefValMapAccessor(mapVal map[ref.Val]ref.Val) mapAccessor {
529 return &refValMapAccessor{mapVal: mapVal}
530 }
531
532 type refValMapAccessor struct {
533 mapVal map[ref.Val]ref.Val
534 }
535
536 // Find uses native map accesses to find the key, returning (value, true) if present.
537 //
538 // If the key is not found the function returns (nil, false).
539 func (a *refValMapAccessor) Find(key ref.Val) (ref.Val, bool) {
540 if len(a.mapVal) == 0 {
541 return nil, false
542 }
543 if keyVal, found := a.mapVal[key]; found {
544 return keyVal, true
545 }
546 switch k := key.(type) {
547 case Double:
548 if ik, ok := doubleToInt64Lossless(float64(k)); ok {
549 if keyVal, found := a.mapVal[Int(ik)]; found {
550 return keyVal, found
551 }
552 }
553 if uk, ok := doubleToUint64Lossless(float64(k)); ok {
554 keyVal, found := a.mapVal[Uint(uk)]
555 return keyVal, found
556 }
557 // map keys of type double are not supported.
558 case Int:
559 if uk, ok := int64ToUint64Lossless(int64(k)); ok {
560 keyVal, found := a.mapVal[Uint(uk)]
561 return keyVal, found
562 }
563 case Uint:
564 if ik, ok := uint64ToInt64Lossless(uint64(k)); ok {
565 keyVal, found := a.mapVal[Int(ik)]
566 return keyVal, found
567 }
568 }
569 return nil, false
570 }
571
572 // Iterator produces a new traits.Iterator which iterates over the map keys via Golang reflection.
573 func (a *refValMapAccessor) Iterator() traits.Iterator {
574 return &mapIterator{
575 Adapter: DefaultTypeAdapter,
576 mapKeys: reflect.ValueOf(a.mapVal).MapRange(),
577 len: len(a.mapVal),
578 }
579 }
580
581 // Fold calls the FoldEntry method for each (key, value) pair in the map.
582 func (a *refValMapAccessor) Fold(f traits.Folder) {
583 for k, v := range a.mapVal {
584 if !f.FoldEntry(k, v) {
585 break
586 }
587 }
588 }
589
590 func newStringMapAccessor(strMap map[string]string) mapAccessor {
591 return &stringMapAccessor{mapVal: strMap}
592 }
593
594 type stringMapAccessor struct {
595 mapVal map[string]string
596 }
597
598 // Find uses native map accesses to find the key, returning (value, true) if present.
599 //
600 // If the key is not found the function returns (nil, false).
601 func (a *stringMapAccessor) Find(key ref.Val) (ref.Val, bool) {
602 strKey, ok := key.(String)
603 if !ok {
604 return nil, false
605 }
606 keyVal, found := a.mapVal[string(strKey)]
607 if !found {
608 return nil, false
609 }
610 return String(keyVal), true
611 }
612
613 // Iterator creates a new traits.Iterator from the string key set of the map.
614 func (a *stringMapAccessor) Iterator() traits.Iterator {
615 // Copy the keys to make their order stable.
616 mapKeys := make([]string, len(a.mapVal))
617 i := 0
618 for k := range a.mapVal {
619 mapKeys[i] = k
620 i++
621 }
622 return &stringKeyIterator{
623 mapKeys: mapKeys,
624 len: len(mapKeys),
625 }
626 }
627
628 // Fold calls the FoldEntry method for each (key, value) pair in the map.
629 func (a *stringMapAccessor) Fold(f traits.Folder) {
630 for k, v := range a.mapVal {
631 if !f.FoldEntry(k, v) {
632 break
633 }
634 }
635 }
636
637 func newStringIfaceMapAccessor(adapter Adapter, mapVal map[string]any) mapAccessor {
638 return &stringIfaceMapAccessor{
639 Adapter: adapter,
640 mapVal: mapVal,
641 }
642 }
643
644 type stringIfaceMapAccessor struct {
645 Adapter
646 mapVal map[string]any
647 }
648
649 // Find uses native map accesses to find the key, returning (value, true) if present.
650 //
651 // If the key is not found the function returns (nil, false).
652 func (a *stringIfaceMapAccessor) Find(key ref.Val) (ref.Val, bool) {
653 strKey, ok := key.(String)
654 if !ok {
655 return nil, false
656 }
657 keyVal, found := a.mapVal[string(strKey)]
658 if !found {
659 return nil, false
660 }
661 return a.NativeToValue(keyVal), true
662 }
663
664 // Iterator creates a new traits.Iterator from the string key set of the map.
665 func (a *stringIfaceMapAccessor) Iterator() traits.Iterator {
666 // Copy the keys to make their order stable.
667 mapKeys := make([]string, len(a.mapVal))
668 i := 0
669 for k := range a.mapVal {
670 mapKeys[i] = k
671 i++
672 }
673 return &stringKeyIterator{
674 mapKeys: mapKeys,
675 len: len(mapKeys),
676 }
677 }
678
679 // Fold calls the FoldEntry method for each (key, value) pair in the map.
680 func (a *stringIfaceMapAccessor) Fold(f traits.Folder) {
681 for k, v := range a.mapVal {
682 if !f.FoldEntry(k, v) {
683 break
684 }
685 }
686 }
687
688 // protoMap is a specialized, separate implementation of the traits.Mapper interfaces tailored to
689 // accessing protoreflect.Map values.
690 type protoMap struct {
691 Adapter
692 value *pb.Map
693 }
694
695 // Contains returns whether the map contains the given key.
696 func (m *protoMap) Contains(key ref.Val) ref.Val {
697 _, found := m.Find(key)
698 return Bool(found)
699 }
700
701 // ConvertToNative implements the ref.Val interface method.
702 //
703 // Note, assignment to Golang struct types is not yet supported.
704 func (m *protoMap) ConvertToNative(typeDesc reflect.Type) (any, error) {
705 // If the map is already assignable to the desired type return it, e.g. interfaces and
706 // maps with the same key value types.
707 switch typeDesc {
708 case anyValueType:
709 json, err := m.ConvertToNative(JSONStructType)
710 if err != nil {
711 return nil, err
712 }
713 return anypb.New(json.(proto.Message))
714 case JSONValueType, JSONStructType:
715 jsonEntries, err :=
716 m.ConvertToNative(reflect.TypeOf(map[string]*structpb.Value{}))
717 if err != nil {
718 return nil, err
719 }
720 jsonMap := &structpb.Struct{
721 Fields: jsonEntries.(map[string]*structpb.Value)}
722 if typeDesc == JSONStructType {
723 return jsonMap, nil
724 }
725 return structpb.NewStructValue(jsonMap), nil
726 }
727 switch typeDesc.Kind() {
728 case reflect.Struct, reflect.Ptr:
729 if reflect.TypeOf(m.value).AssignableTo(typeDesc) {
730 return m.value, nil
731 }
732 if reflect.TypeOf(m).AssignableTo(typeDesc) {
733 return m, nil
734 }
735 }
736 if typeDesc.Kind() != reflect.Map {
737 return nil, fmt.Errorf("unsupported type conversion: %v to map", typeDesc)
738 }
739
740 keyType := m.value.KeyType.ReflectType()
741 valType := m.value.ValueType.ReflectType()
742 otherKeyType := typeDesc.Key()
743 otherValType := typeDesc.Elem()
744 mapVal := reflect.MakeMapWithSize(typeDesc, m.value.Len())
745 var err error
746 m.value.Range(func(key protoreflect.MapKey, val protoreflect.Value) bool {
747 ntvKey := key.Interface()
748 ntvVal := val.Interface()
749 switch pv := ntvVal.(type) {
750 case protoreflect.Message:
751 ntvVal = pv.Interface()
752 }
753 if keyType == otherKeyType && valType == otherValType {
754 mapVal.SetMapIndex(reflect.ValueOf(ntvKey), reflect.ValueOf(ntvVal))
755 return true
756 }
757 celKey := m.NativeToValue(ntvKey)
758 celVal := m.NativeToValue(ntvVal)
759 ntvKey, err = celKey.ConvertToNative(otherKeyType)
760 if err != nil {
761 // early terminate the range loop.
762 return false
763 }
764 ntvVal, err = celVal.ConvertToNative(otherValType)
765 if err != nil {
766 // early terminate the range loop.
767 return false
768 }
769 mapVal.SetMapIndex(reflect.ValueOf(ntvKey), reflect.ValueOf(ntvVal))
770 return true
771 })
772 if err != nil {
773 return nil, err
774 }
775 return mapVal.Interface(), nil
776 }
777
778 // ConvertToType implements the ref.Val interface method.
779 func (m *protoMap) ConvertToType(typeVal ref.Type) ref.Val {
780 switch typeVal {
781 case MapType:
782 return m
783 case TypeType:
784 return MapType
785 }
786 return NewErr("type conversion error from '%s' to '%s'", MapType, typeVal)
787 }
788
789 // Equal implements the ref.Val interface method.
790 func (m *protoMap) Equal(other ref.Val) ref.Val {
791 otherMap, ok := other.(traits.Mapper)
792 if !ok {
793 return False
794 }
795 if m.value.Map.Len() != int(otherMap.Size().(Int)) {
796 return False
797 }
798 var retVal ref.Val = True
799 m.value.Range(func(key protoreflect.MapKey, val protoreflect.Value) bool {
800 keyVal := m.NativeToValue(key.Interface())
801 valVal := m.NativeToValue(val)
802 otherVal, found := otherMap.Find(keyVal)
803 if !found {
804 retVal = False
805 return false
806 }
807 valEq := Equal(valVal, otherVal)
808 if valEq != True {
809 retVal = valEq
810 return false
811 }
812 return true
813 })
814 return retVal
815 }
816
817 // Find returns whether the protoreflect.Map contains the input key.
818 //
819 // If the key is not found the function returns (nil, false).
820 func (m *protoMap) Find(key ref.Val) (ref.Val, bool) {
821 if keyVal, found := m.findInternal(key); found {
822 return keyVal, true
823 }
824 switch k := key.(type) {
825 // Double is not a valid proto map key type, so check for the key as an int or uint.
826 case Double:
827 if ik, ok := doubleToInt64Lossless(float64(k)); ok {
828 if keyVal, found := m.findInternal(Int(ik)); found {
829 return keyVal, true
830 }
831 }
832 if uk, ok := doubleToUint64Lossless(float64(k)); ok {
833 return m.findInternal(Uint(uk))
834 }
835 // map keys of type double are not supported.
836 case Int:
837 if uk, ok := int64ToUint64Lossless(int64(k)); ok {
838 return m.findInternal(Uint(uk))
839 }
840 case Uint:
841 if ik, ok := uint64ToInt64Lossless(uint64(k)); ok {
842 return m.findInternal(Int(ik))
843 }
844 }
845 return nil, false
846 }
847
848 // findInternal attempts to convert the incoming key to the map's internal native type
849 // and then returns the value, if found.
850 func (m *protoMap) findInternal(key ref.Val) (ref.Val, bool) {
851 // Convert the input key to the expected protobuf key type.
852 ntvKey, err := key.ConvertToNative(m.value.KeyType.ReflectType())
853 if err != nil {
854 return nil, false
855 }
856 // Use protoreflection to get the key value.
857 val := m.value.Get(protoreflect.ValueOf(ntvKey).MapKey())
858 if !val.IsValid() {
859 return nil, false
860 }
861 // Perform nominal type unwrapping from the input value.
862 switch v := val.Interface().(type) {
863 case protoreflect.List, protoreflect.Map:
864 // Maps do not support list or map values
865 return nil, false
866 default:
867 return m.NativeToValue(v), true
868 }
869 }
870
871 // Get implements the traits.Indexer interface method.
872 func (m *protoMap) Get(key ref.Val) ref.Val {
873 v, found := m.Find(key)
874 if !found {
875 return ValOrErr(v, "no such key: %v", key)
876 }
877 return v
878 }
879
880 // IsZeroValue returns true if the map is empty.
881 func (m *protoMap) IsZeroValue() bool {
882 return m.value.Len() == 0
883 }
884
885 // Iterator implements the traits.Iterable interface method.
886 func (m *protoMap) Iterator() traits.Iterator {
887 // Copy the keys to make their order stable.
888 mapKeys := make([]protoreflect.MapKey, 0, m.value.Len())
889 m.value.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
890 mapKeys = append(mapKeys, k)
891 return true
892 })
893 return &protoMapIterator{
894 Adapter: m.Adapter,
895 mapKeys: mapKeys,
896 len: m.value.Len(),
897 }
898 }
899
900 // Fold calls the FoldEntry method for each (key, value) pair in the map.
901 func (m *protoMap) Fold(f traits.Folder) {
902 m.value.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
903 return f.FoldEntry(k.Interface(), v.Interface())
904 })
905 }
906
907 // Size returns the number of entries in the protoreflect.Map.
908 func (m *protoMap) Size() ref.Val {
909 return Int(m.value.Len())
910 }
911
912 // Type implements the ref.Val interface method.
913 func (m *protoMap) Type() ref.Type {
914 return MapType
915 }
916
917 // Value implements the ref.Val interface method.
918 func (m *protoMap) Value() any {
919 return m.value
920 }
921
922 type mapIterator struct {
923 *baseIterator
924 Adapter
925 mapKeys *reflect.MapIter
926 cursor int
927 len int
928 }
929
930 // HasNext implements the traits.Iterator interface method.
931 func (it *mapIterator) HasNext() ref.Val {
932 return Bool(it.cursor < it.len)
933 }
934
935 // Next implements the traits.Iterator interface method.
936 func (it *mapIterator) Next() ref.Val {
937 if it.HasNext() == True && it.mapKeys.Next() {
938 it.cursor++
939 refKey := it.mapKeys.Key()
940 return it.NativeToValue(refKey.Interface())
941 }
942 return nil
943 }
944
945 type protoMapIterator struct {
946 *baseIterator
947 Adapter
948 mapKeys []protoreflect.MapKey
949 cursor int
950 len int
951 }
952
953 // HasNext implements the traits.Iterator interface method.
954 func (it *protoMapIterator) HasNext() ref.Val {
955 return Bool(it.cursor < it.len)
956 }
957
958 // Next implements the traits.Iterator interface method.
959 func (it *protoMapIterator) Next() ref.Val {
960 if it.HasNext() == True {
961 index := it.cursor
962 it.cursor++
963 refKey := it.mapKeys[index]
964 return it.NativeToValue(refKey.Interface())
965 }
966 return nil
967 }
968
969 type stringKeyIterator struct {
970 *baseIterator
971 mapKeys []string
972 cursor int
973 len int
974 }
975
976 // HasNext implements the traits.Iterator interface method.
977 func (it *stringKeyIterator) HasNext() ref.Val {
978 return Bool(it.cursor < it.len)
979 }
980
981 // Next implements the traits.Iterator interface method.
982 func (it *stringKeyIterator) Next() ref.Val {
983 if it.HasNext() == True {
984 index := it.cursor
985 it.cursor++
986 return String(it.mapKeys[index])
987 }
988 return nil
989 }
990
991 // ToFoldableMap will create a Foldable version of a map suitable for key-value pair iteration.
992 //
993 // For values which are already Foldable, this call is a no-op. For all other values, the fold
994 // is driven via the Iterator HasNext() and Next() calls as well as the map's Get() method
995 // which means that the folding will function, but take a performance hit.
996 func ToFoldableMap(m traits.Mapper) traits.Foldable {
997 if f, ok := m.(traits.Foldable); ok {
998 return f
999 }
1000 return interopFoldableMap{Mapper: m}
1001 }
1002
1003 type interopFoldableMap struct {
1004 traits.Mapper
1005 }
1006
1007 func (m interopFoldableMap) Fold(f traits.Folder) {
1008 it := m.Iterator()
1009 for it.HasNext() == True {
1010 k := it.Next()
1011 if !f.FoldEntry(k, m.Get(k)) {
1012 break
1013 }
1014 }
1015 }
1016
1017 // InsertMapKeyValue inserts a key, value pair into the target map if the target map does not
1018 // already contain the given key.
1019 //
1020 // If the map is mutable, it is modified in-place per the MutableMapper contract.
1021 // If the map is not mutable, a copy containing the new key, value pair is made.
1022 func InsertMapKeyValue(m traits.Mapper, k, v ref.Val) ref.Val {
1023 if mutable, ok := m.(traits.MutableMapper); ok {
1024 return mutable.Insert(k, v)
1025 }
1026
1027 // Otherwise perform the slow version of the insertion which makes a copy of the incoming map.
1028 if _, found := m.Find(k); !found {
1029 size := m.Size().(Int)
1030 copy := make(map[ref.Val]ref.Val, size+1)
1031 copy[k] = v
1032 it := m.Iterator()
1033 for it.HasNext() == True {
1034 nextK := it.Next()
1035 nextV := m.Get(nextK)
1036 copy[nextK] = nextV
1037 }
1038 return DefaultTypeAdapter.NativeToValue(copy)
1039 }
1040 return NewErr("insert failed: key %v already exists", k)
1041 }
1042
1043 func upperCamelCase(s string) string {
1044 var newStr strings.Builder
1045 s = strings.TrimSpace(s)
1046 var prev rune
1047 for _, curr := range s {
1048 if prev == 0 || isDelim(prev) {
1049 if !isDelim(curr) {
1050 newStr.WriteRune(unicode.ToUpper(curr))
1051 }
1052 } else if !isDelim(curr) {
1053 if isLower(prev) {
1054 newStr.WriteRune(curr)
1055 } else {
1056 newStr.WriteRune(unicode.ToLower(curr))
1057 }
1058 }
1059 prev = curr
1060 }
1061 return newStr.String()
1062 }
1063
1064 func isDelim(r rune) bool {
1065 return r == '_' || r == '-'
1066 }
1067
1068 func isLower(r rune) bool {
1069 return r >= 'a' && r <= 'z'
1070 }