Change module name to go.fd.io/govpp
[govpp.git] / codec / marshaler.go
1 //  Copyright (c) 2020 Cisco and/or its affiliates.
2 //
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:
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package codec
16
17 import (
18         "bytes"
19         "reflect"
20
21         "github.com/lunixbochs/struc"
22
23         "go.fd.io/govpp/api"
24 )
25
26 // Marshaler is the interface implemented by the binary API messages that can
27 // marshal itself into binary form for the wire.
28 type Marshaler interface {
29         Size() int
30         Marshal([]byte) ([]byte, error)
31 }
32
33 // Unmarshaler is the interface implemented by the binary API messages that can
34 // unmarshal a binary representation of itself from the wire.
35 type Unmarshaler interface {
36         Unmarshal([]byte) error
37 }
38
39 type Wrapper struct {
40         api.Message
41 }
42
43 func (w Wrapper) Size() int {
44         if size, err := struc.Sizeof(w.Message); err != nil {
45                 return 0
46         } else {
47                 return size
48         }
49 }
50
51 func (w Wrapper) Marshal(b []byte) ([]byte, error) {
52         buf := new(bytes.Buffer)
53         if reflect.TypeOf(w.Message).Elem().NumField() > 0 {
54                 if err := struc.Pack(buf, w.Message); err != nil {
55                         return nil, err
56                 }
57         }
58         if b != nil {
59                 copy(b, buf.Bytes())
60         }
61         return buf.Bytes(), nil
62 }
63
64 func (w Wrapper) Unmarshal(data []byte) error {
65         buf := bytes.NewReader(data)
66         if err := struc.Unpack(buf, w.Message); err != nil {
67                 return err
68         }
69         return nil
70 }