Refactor GoVPP
[govpp.git] / examples / cmd / union-example / union_example.go
1 // Copyright (c) 2018 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 // union-example is an example to show how to use unions in VPP binary API.
16 package main
17
18 import (
19         "bytes"
20         "log"
21
22         "git.fd.io/govpp.git/examples/bin_api/ip"
23         "github.com/lunixbochs/struc"
24 )
25
26 func main() {
27         // create union with IPv4 address
28         var unionIP4 ip.AddressUnion
29         unionIP4.SetIP4(ip.IP4Address{Address: []byte{192, 168, 1, 10}})
30
31         // use it in the Address type
32         addr := &ip.Address{
33                 Af: ip.ADDRESS_IP4,
34                 Un: unionIP4,
35         }
36         log.Printf("encoding union IPv4: %v", addr.Un.GetIP4())
37
38         // encode the address with union
39         data := encode(addr)
40         // decode the address with union
41         addr2 := decode(data)
42
43         log.Printf("decoded union IPv4: %v", addr2.Un.GetIP4())
44 }
45
46 func encode(addr *ip.Address) []byte {
47         log.Printf("encoding address: %#v", addr)
48         buf := new(bytes.Buffer)
49         if err := struc.Pack(buf, addr); err != nil {
50                 panic(err)
51         }
52         return buf.Bytes()
53 }
54
55 func decode(data []byte) *ip.Address {
56         addr := new(ip.Address)
57         buf := bytes.NewReader(data)
58         if err := struc.Unpack(buf, addr); err != nil {
59                 panic(err)
60         }
61         log.Printf("decoded address: %#v", addr)
62         return addr
63 }