-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarshal.go
55 lines (45 loc) · 1.25 KB
/
marshal.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
package fastproto
import "google.golang.org/protobuf/proto"
type Marshaler interface {
MarshalTo(data []byte) (n int, err error)
Marshal() ([]byte, error)
AppendToSizedBuffer(data []byte) ([]byte, error)
}
// type MarshalOptions struct {
// }
// func (opt MarshalOptions) Marshal(m Marshaler) ([]byte, error) {
// return m.Marshal()
// }
// func (opt MarshalOptions) MarshalTo(data []byte, m Marshaler) (int, error) {
// return m.MarshalTo(data)
// }
func Marshal(m proto.Message) ([]byte, error) {
if mm, ok := m.(Marshaler); ok {
return mm.Marshal()
}
return proto.Marshal(m)
}
// data must have enough space for message which means cap(data) >= msg.Size(), or else it would return error
// the return int indicate how many bytes of data is used.
// data[:n] is encoded message.
func MarshalTo(data []byte, m proto.Message) (int, error) {
if mm, ok := m.(Marshaler); ok {
return mm.MarshalTo(data)
}
b, err := proto.Marshal(m)
if err != nil {
return 0, err
}
copy(data[:], b)
return len(b), nil
}
func AppendToSizedBuffer(data []byte, m proto.Message) ([]byte, error) {
if mm, ok := m.(Marshaler); ok {
return mm.AppendToSizedBuffer(data)
}
b, err := proto.Marshal(m)
if err != nil {
return data, err
}
return append(data, b...), nil
}