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 func EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
28 return DefaultCodec.EncodeMsg(msg, msgID)
30 func DecodeMsg(data []byte, msg api.Message) (err error) {
31 return DefaultCodec.DecodeMsg(data, msg)
33 func DecodeMsgContext(data []byte, msg api.Message) (context uint32, err error) {
34 return DefaultCodec.DecodeMsgContext(data, msg)
37 // MsgCodec provides encoding and decoding functionality of `api.Message` structs into/from
38 // binary format as accepted by VPP.
39 type MsgCodec struct{}
41 func (*MsgCodec) EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
43 return nil, errors.New("nil message passed in")
46 // try to recover panic which might possibly occur
48 if r := recover(); r != nil {
50 if err, ok = r.(error); !ok {
51 err = fmt.Errorf("%v", r)
53 err = fmt.Errorf("panic occurred during encoding message %s: %v", msg.GetMessageName(), err)
57 marshaller, ok := msg.(Marshaler)
59 marshaller = Wrapper{msg}
62 size := marshaller.Size()
63 offset := getOffset(msg)
66 b := make([]byte, size+offset)
67 b[0] = byte(msgID >> 8)
70 data, err = marshaller.Marshal(b[offset:])
75 return b[0:len(b):len(b)], nil
78 func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) (err error) {
80 return errors.New("nil message passed in")
83 // try to recover panic which might possibly occur
85 if r := recover(); r != nil {
87 if err, ok = r.(error); !ok {
88 err = fmt.Errorf("%v", r)
90 err = fmt.Errorf("panic occurred during decoding message %s: %v", msg.GetMessageName(), err)
94 marshaller, ok := msg.(Unmarshaler)
96 marshaller = Wrapper{msg}
99 offset := getOffset(msg)
101 err = marshaller.Unmarshal(data[offset:len(data)])
109 func (*MsgCodec) DecodeMsgContext(data []byte, msg api.Message) (context uint32, err error) {
111 return 0, errors.New("nil message passed in")
114 switch msg.GetMessageType() {
115 case api.RequestMessage:
116 return binary.BigEndian.Uint32(data[6:10]), nil
117 case api.ReplyMessage:
118 return binary.BigEndian.Uint32(data[2:6]), nil
124 func getOffset(msg api.Message) (offset int) {
125 switch msg.GetMessageType() {
126 case api.RequestMessage:
128 case api.ReplyMessage:
130 case api.EventMessage: