-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_map.go
56 lines (51 loc) · 1.61 KB
/
gen_map.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
package fauxrpc
import (
"fmt"
"log/slog"
"google.golang.org/protobuf/reflect/protoreflect"
)
func mapSimple(msg protoreflect.Message, fd protoreflect.FieldDescriptor, opts GenOptions) *protoreflect.Value {
mapVal := msg.NewField(fd)
itemCount := opts.fake().IntRange(0, 4)
for i := 0; i < itemCount; i++ {
v := getFieldValue(fd.MapKey(), opts.nested())
w := getFieldValue(fd.MapValue(), opts.nested())
if v != nil && w != nil {
mapVal.Map().Set((*v).MapKey(), *w)
}
}
return &mapVal
}
// Map returns a fake repeated value given a field descriptor.
func Map(msg protoreflect.Message, fd protoreflect.FieldDescriptor, opts GenOptions) *protoreflect.Value {
if opts.MaxDepth <= 0 {
return nil
}
constraints := getResolver().ResolveFieldConstraints(fd)
if constraints == nil {
return mapSimple(msg, fd, opts)
}
rules := constraints.GetEnum()
if rules == nil {
return mapSimple(msg, fd, opts)
}
min, max := uint64(0), uint64(4)
if constraints.GetMap().MinPairs != nil {
min = constraints.GetMap().GetMinPairs()
}
if constraints.GetMap().MaxPairs != nil {
max = constraints.GetMap().GetMaxPairs()
}
mapVal := msg.NewField(fd)
itemCount := opts.fake().IntRange(int(min), int(max))
for i := 0; i < itemCount; i++ {
v := getFieldValue(fd.MapKey(), opts.nested().withExtraFieldConstraints(constraints.GetMap().Keys))
w := getFieldValue(fd.MapValue(), opts.nested().withExtraFieldConstraints(constraints.GetMap().Values))
if v != nil && w != nil {
mapVal.Map().Set((*v).MapKey(), *w)
} else {
slog.Warn(fmt.Sprintf("Unknown map k/v %s %v", fd.FullName(), fd.Kind()))
}
}
return &mapVal
}