3 * Copyright 2014 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
25 "github.com/golang/protobuf/proto"
28 // Codec defines the interface gRPC uses to encode and decode messages.
29 // Note that implementations of this interface must be thread safe;
30 // a Codec's methods can be called from concurrent goroutines.
31 type Codec interface {
32 // Marshal returns the wire format of v.
33 Marshal(v interface{}) ([]byte, error)
34 // Unmarshal parses the wire format into v.
35 Unmarshal(data []byte, v interface{}) error
36 // String returns the name of the Codec implementation. The returned
37 // string will be used as part of content type in transmission.
41 // protoCodec is a Codec implementation with protobuf. It is the default codec for gRPC.
42 type protoCodec struct {
45 type cachedProtoBuffer struct {
46 lastMarshaledSize uint32
50 func capToMaxInt32(val int) uint32 {
51 if val > math.MaxInt32 {
52 return uint32(math.MaxInt32)
57 func (p protoCodec) marshal(v interface{}, cb *cachedProtoBuffer) ([]byte, error) {
58 protoMsg := v.(proto.Message)
59 newSlice := make([]byte, 0, cb.lastMarshaledSize)
63 if err := cb.Marshal(protoMsg); err != nil {
67 cb.lastMarshaledSize = capToMaxInt32(len(out))
71 func (p protoCodec) Marshal(v interface{}) ([]byte, error) {
72 cb := protoBufferPool.Get().(*cachedProtoBuffer)
73 out, err := p.marshal(v, cb)
75 // put back buffer and lose the ref to the slice
77 protoBufferPool.Put(cb)
81 func (p protoCodec) Unmarshal(data []byte, v interface{}) error {
82 cb := protoBufferPool.Get().(*cachedProtoBuffer)
84 v.(proto.Message).Reset()
85 err := cb.Unmarshal(v.(proto.Message))
87 protoBufferPool.Put(cb)
91 func (protoCodec) String() string {
95 var protoBufferPool = &sync.Pool{
96 New: func() interface{} {
97 return &cachedProtoBuffer{
98 Buffer: proto.Buffer{},
99 lastMarshaledSize: 16,