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.
21 "git.fd.io/govpp.git/api"
24 var DefaultCodec = new(MsgCodec)
26 // VppRequestHeader struct contains header fields implemented by all VPP requests.
27 type VppRequestHeader struct {
33 // VppReplyHeader struct contains header fields implemented by all VPP replies.
34 type VppReplyHeader struct {
39 // VppEventHeader struct contains header fields implemented by all VPP events.
40 type VppEventHeader struct {
45 // VppOtherHeader struct contains header fields implemented by other VPP messages (not requests nor replies).
46 type VppOtherHeader struct {
50 // MsgCodec provides encoding and decoding functionality of `api.Message` structs into/from
51 // binary format as accepted by VPP.
52 type MsgCodec struct{}
54 func (*MsgCodec) EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
56 return nil, errors.New("nil message passed in")
59 // try to recover panic which might possibly occur
61 if r := recover(); r != nil {
63 if err, ok = r.(error); !ok {
64 err = fmt.Errorf("%v", r)
66 err = fmt.Errorf("panic occurred during encoding message %s: %v", msg.GetMessageName(), err)
70 marshaller, ok := msg.(Marshaler)
72 marshaller = Wrapper{msg}
75 size := marshaller.Size()
76 offset := getOffset(msg)
79 b := make([]byte, size+offset)
80 b[0] = byte(msgID >> 8)
83 data, err = marshaller.Marshal(b[offset:])
88 return b[0:len(b):len(b)], nil
91 func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) (err error) {
93 return errors.New("nil message passed in")
96 // try to recover panic which might possibly occur
98 if r := recover(); r != nil {
100 if err, ok = r.(error); !ok {
101 err = fmt.Errorf("%v", r)
103 err = fmt.Errorf("panic occurred during decoding message %s: %v", msg.GetMessageName(), err)
107 marshaller, ok := msg.(Unmarshaler)
109 marshaller = Wrapper{msg}
112 offset := getOffset(msg)
114 err = marshaller.Unmarshal(data[offset:len(data)])
122 func (*MsgCodec) DecodeMsgContext(data []byte, msg api.Message) (context uint32, err error) {
124 return 0, errors.New("nil message passed in")
127 switch msg.GetMessageType() {
128 case api.RequestMessage:
129 return order.Uint32(data[6:10]), nil
130 case api.ReplyMessage:
131 return order.Uint32(data[2:6]), nil
137 func getOffset(msg api.Message) (offset int) {
138 switch msg.GetMessageType() {
139 case api.RequestMessage:
141 case api.ReplyMessage:
143 case api.EventMessage: