1 // Copyright (c) 2017 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
22 "git.fd.io/govpp.git/api"
25 var DefaultCodec = new(MsgCodec)
27 // MsgCodec provides encoding and decoding functionality of `api.Message` structs into/from
28 // binary format as accepted by VPP.
29 type MsgCodec struct{}
31 func (*MsgCodec) EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
33 return nil, errors.New("nil message passed in")
36 // try to recover panic which might possibly occur
38 if r := recover(); r != nil {
40 if err, ok = r.(error); !ok {
41 err = fmt.Errorf("%v", r)
43 err = fmt.Errorf("panic occurred during encoding message %s: %v", msg.GetMessageName(), err)
47 marshaller, ok := msg.(Marshaler)
49 marshaller = Wrapper{msg}
52 size := marshaller.Size()
53 offset := getOffset(msg)
56 b := make([]byte, size+offset)
57 b[0] = byte(msgID >> 8)
60 data, err = marshaller.Marshal(b[offset:])
65 return b[0:len(b):len(b)], nil
68 func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) (err error) {
70 return errors.New("nil message passed in")
73 // try to recover panic which might possibly occur
75 if r := recover(); r != nil {
77 if err, ok = r.(error); !ok {
78 err = fmt.Errorf("%v", r)
80 err = fmt.Errorf("panic occurred during decoding message %s: %v", msg.GetMessageName(), err)
84 marshaller, ok := msg.(Unmarshaler)
86 marshaller = Wrapper{msg}
89 offset := getOffset(msg)
91 err = marshaller.Unmarshal(data[offset:len(data)])
99 func (*MsgCodec) DecodeMsgContext(data []byte, msg api.Message) (context uint32, err error) {
101 return 0, errors.New("nil message passed in")
104 switch msg.GetMessageType() {
105 case api.RequestMessage:
106 return binary.BigEndian.Uint32(data[6:10]), nil
107 case api.ReplyMessage:
108 return binary.BigEndian.Uint32(data[2:6]), nil
114 func getOffset(msg api.Message) (offset int) {
115 switch msg.GetMessageType() {
116 case api.RequestMessage:
118 case api.ReplyMessage:
120 case api.EventMessage: