Marshal is basically the same as https://github.com/grpc/grpc-go/blob/d2e836604b36400a54fbf04af495d12b38fa1e3a/encoding/proto/proto.go#L43-L67 but it uses gogo proto methods where applicable.
(v any)
| 40 | // Marshal is basically the same as https://github.com/grpc/grpc-go/blob/d2e836604b36400a54fbf04af495d12b38fa1e3a/encoding/proto/proto.go#L43-L67 |
| 41 | // but it uses gogo proto methods where applicable. |
| 42 | func (c *cortexCodec) Marshal(v any) (data mem.BufferSlice, err error) { |
| 43 | vv := messageV2Of(v) |
| 44 | if vv == nil { |
| 45 | return nil, fmt.Errorf("proto: failed to marshal, message is %T, want proto.Message", v) |
| 46 | } |
| 47 | |
| 48 | var size int |
| 49 | if sizer, ok := v.(gogoproto.Sizer); ok { |
| 50 | size = sizer.Size() |
| 51 | } else { |
| 52 | size = proto.Size(vv) |
| 53 | } |
| 54 | |
| 55 | if mem.IsBelowBufferPoolingThreshold(size) { |
| 56 | var buf mem.SliceBuffer |
| 57 | |
| 58 | // If v implements MarshalToSizedBuffer we should use it as it is more optimized |
| 59 | if m, ok := v.(GogoProtoMessage); ok { |
| 60 | buf = make([]byte, size) |
| 61 | if _, err := m.MarshalToSizedBuffer(buf[:size]); err != nil { |
| 62 | return nil, err |
| 63 | } |
| 64 | } else { |
| 65 | buf, err = proto.Marshal(vv) |
| 66 | if err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | data = append(data, buf) |
| 72 | } else { |
| 73 | pool := c.defaultBufferPool |
| 74 | buf := pool.Get(size) |
| 75 | |
| 76 | // If v implements MarshalToSizedBuffer we should use it as it is more optimized |
| 77 | if m, ok := v.(GogoProtoMessage); ok { |
| 78 | if _, err := m.MarshalToSizedBuffer((*buf)[:size]); err != nil { |
| 79 | pool.Put(buf) |
| 80 | return nil, err |
| 81 | } |
| 82 | } else { |
| 83 | if _, err := (proto.MarshalOptions{}).MarshalAppend((*buf)[:0], vv); err != nil { |
| 84 | pool.Put(buf) |
| 85 | return nil, err |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | data = append(data, mem.NewBuffer(buf, pool)) |
| 90 | } |
| 91 | |
| 92 | return data, nil |
| 93 | } |
| 94 | |
| 95 | // Unmarshal Copied from https://github.com/grpc/grpc-go/blob/d2e836604b36400a54fbf04af495d12b38fa1e3a/encoding/proto/proto.go#L69-L81 |
| 96 | // but without releasing the buffer |