-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathcodec.go
More file actions
79 lines (70 loc) · 2.1 KB
/
codec.go
File metadata and controls
79 lines (70 loc) · 2.1 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package grpc
import (
"github.com/pkg/errors"
"google.golang.org/grpc/encoding"
"google.golang.org/grpc/encoding/proto"
"google.golang.org/grpc/mem"
)
type vtprotoMessage interface {
MarshalToSizedBufferVT(data []byte) (int, error)
UnmarshalVT([]byte) error
SizeVT() int
}
type codec struct {
// similar to customMarshaler we fall back to original implementation when message is not supported
encoding.CodecV2
}
func (c *codec) Name() string { return c.CodecV2.Name() }
var defaultBufferPool = mem.DefaultBufferPool()
func (c *codec) Marshal(v any) (mem.BufferSlice, error) {
m, ok := v.(vtprotoMessage)
if !ok {
out, fallBackError := c.CodecV2.Marshal(v)
return out, errors.Wrapf(fallBackError, "codec failed: type %T does not support VT; fallback failed", v)
}
vt, err := c.marshalVT(m)
if err != nil {
out, fallBackError := c.CodecV2.Marshal(v)
return out, errors.Wrapf(fallBackError, "codec failed: %s; fallback failed", err)
}
return vt, nil
}
func (c *codec) marshalVT(m vtprotoMessage) (mem.BufferSlice, error) {
size := m.SizeVT()
if mem.IsBelowBufferPoolingThreshold(size) {
buf := make([]byte, size)
_, err := m.MarshalToSizedBufferVT(buf)
if err != nil {
return nil, err
}
return mem.BufferSlice{mem.SliceBuffer(buf)}, nil
}
buf := defaultBufferPool.Get(size)
_, err := m.MarshalToSizedBufferVT(*buf)
if err != nil {
defaultBufferPool.Put(buf)
return nil, err
}
return mem.BufferSlice{mem.NewBuffer(buf, defaultBufferPool)}, nil
}
func (c *codec) Unmarshal(data mem.BufferSlice, v any) error {
m, ok := v.(vtprotoMessage)
if !ok {
fallbackErr := c.CodecV2.Unmarshal(data, v)
return errors.Wrapf(fallbackErr, "type %T does not support VT; fallback failed", v)
}
buf := data.MaterializeToBuffer(defaultBufferPool)
defer buf.Free()
err := m.UnmarshalVT(buf.ReadOnlyData())
if err != nil {
fallbackErr := c.CodecV2.Unmarshal(data, v)
return errors.Wrapf(fallbackErr, "codec failed: %s; fallback failed", err)
}
return nil
}
func init() {
// Replace the original codec with vt wrapper.
encoding.RegisterCodecV2(&codec{
CodecV2: encoding.GetCodecV2(proto.Name),
})
}