...
1
18
19
20
21 package proto
22
23 import (
24 "fmt"
25
26 "google.golang.org/grpc/encoding"
27 "google.golang.org/protobuf/proto"
28 "google.golang.org/protobuf/protoadapt"
29 )
30
31
32 const Name = "proto"
33
34 func init() {
35 encoding.RegisterCodec(codec{})
36 }
37
38
39 type codec struct{}
40
41 func (codec) Marshal(v any) ([]byte, error) {
42 vv := messageV2Of(v)
43 if vv == nil {
44 return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
45 }
46
47 return proto.Marshal(vv)
48 }
49
50 func (codec) Unmarshal(data []byte, v any) error {
51 vv := messageV2Of(v)
52 if vv == nil {
53 return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v)
54 }
55
56 return proto.Unmarshal(data, vv)
57 }
58
59 func messageV2Of(v any) proto.Message {
60 switch v := v.(type) {
61 case protoadapt.MessageV1:
62 return protoadapt.MessageV2Of(v)
63 case protoadapt.MessageV2:
64 return v
65 }
66
67 return nil
68 }
69
70 func (codec) Name() string {
71 return Name
72 }
73
View as plain text