...
1
2
3
4
5 package proto
6
7 import (
8 "google.golang.org/protobuf/reflect/protoreflect"
9 )
10
11
12
13 func HasExtension(m Message, xt protoreflect.ExtensionType) bool {
14
15
16 if m == nil || xt == nil {
17 return false
18 }
19
20
21
22 mr := m.ProtoReflect()
23 xd := xt.TypeDescriptor()
24 if mr.Descriptor() != xd.ContainingMessage() {
25 return false
26 }
27
28 return mr.Has(xd)
29 }
30
31
32
33
34 func ClearExtension(m Message, xt protoreflect.ExtensionType) {
35 m.ProtoReflect().Clear(xt.TypeDescriptor())
36 }
37
38
39
40
41
42 func GetExtension(m Message, xt protoreflect.ExtensionType) interface{} {
43
44 if m == nil {
45 return xt.InterfaceOf(xt.Zero())
46 }
47
48 return xt.InterfaceOf(m.ProtoReflect().Get(xt.TypeDescriptor()))
49 }
50
51
52
53
54 func SetExtension(m Message, xt protoreflect.ExtensionType, v interface{}) {
55 xd := xt.TypeDescriptor()
56 pv := xt.ValueOf(v)
57
58
59 isValid := true
60 switch {
61 case xd.IsList():
62 isValid = pv.List().IsValid()
63 case xd.IsMap():
64 isValid = pv.Map().IsValid()
65 case xd.Message() != nil:
66 isValid = pv.Message().IsValid()
67 }
68 if !isValid {
69 m.ProtoReflect().Clear(xd)
70 return
71 }
72
73 m.ProtoReflect().Set(xd, pv)
74 }
75
76
77
78
79
80
81 func RangeExtensions(m Message, f func(protoreflect.ExtensionType, interface{}) bool) {
82
83 if m == nil {
84 return
85 }
86
87 m.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
88 if fd.IsExtension() {
89 xt := fd.(protoreflect.ExtensionTypeDescriptor).Type()
90 vi := xt.InterfaceOf(v)
91 return f(xt, vi)
92 }
93 return true
94 })
95 }
96
View as plain text