github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/protoutil/marshal.go (about) 1 // Copyright 2016 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package protoutil 12 13 import "github.com/gogo/protobuf/proto" 14 15 // Message extends the proto.Message interface with the MarshalTo and Size 16 // methods we tell gogoproto to generate for us. 17 type Message interface { 18 proto.Message 19 MarshalTo(data []byte) (int, error) 20 Unmarshal(data []byte) error 21 Size() int 22 } 23 24 // Interceptor will be called with every proto before it is marshaled. 25 // Interceptor is not safe to modify concurrently with calls to Marshal. 26 var Interceptor = func(_ Message) {} 27 28 // Marshal encodes pb into the wire format. It is used throughout the code base 29 // to intercept calls to proto.Marshal. 30 func Marshal(pb Message) ([]byte, error) { 31 dest := make([]byte, pb.Size()) 32 if _, err := MarshalTo(pb, dest); err != nil { 33 return nil, err 34 } 35 return dest, nil 36 } 37 38 // MarshalTo encodes pb into the wire format. It is used throughout the code 39 // base to intercept calls to pb.MarshalTo. 40 func MarshalTo(pb Message, dest []byte) (int, error) { 41 Interceptor(pb) 42 return pb.MarshalTo(dest) 43 } 44 45 // Unmarshal parses the protocol buffer representation in buf and places the 46 // decoded result in pb. If the struct underlying pb does not match the data in 47 // buf, the results can be unpredictable. 48 // 49 // Unmarshal resets pb before starting to unmarshal, so any existing data in pb 50 // is always removed. 51 func Unmarshal(data []byte, pb Message) error { 52 pb.Reset() 53 return pb.Unmarshal(data) 54 }