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