File: example_attributeencoder_test.go

package info (click to toggle)
golang-github-mdlayher-netlink 1.7.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 368 kB
  • sloc: makefile: 5
file content (96 lines) | stat: -rw-r--r-- 2,234 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package netlink_test

import (
	"fmt"
	"log"

	"github.com/mdlayher/netlink"
)

// encodeNested is a nested structure within out.
type encodeNested struct {
	A, B uint32
}

// encodeOut is an example structure we will use to pack netlink attributes.
type encodeOut struct {
	Number uint16
	String string
	Nested encodeNested
}

// encode is an example function used to adapt the ae.Nested method
// to encode an arbitrary structure.
func (n encodeNested) encode(ae *netlink.AttributeEncoder) error {
	// Encode the fields of the nested structure.
	ae.Uint32(1, n.A)
	ae.Uint32(2, n.B)
	return nil
}

func ExampleAttributeEncoder_encode() {
	// Create a netlink.AttributeEncoder that encodes to the same message
	// as that decoded by the netlink.AttributeDecoder example.
	ae := netlink.NewAttributeEncoder()

	o := encodeOut{
		Number: 1,
		String: "hello world",
		Nested: encodeNested{
			A: 2,
			B: 3,
		},
	}

	// Encode the Number attribute as a uint16.
	ae.Uint16(1, o.Number)
	// Encode the String attribute as a string.
	ae.String(2, o.String)
	// Nested is a nested structure, so we will use the encodeNested type's
	// encode method with ae.Nested to encode it in a concise way.
	ae.Nested(3, o.Nested.encode)

	// Any errors encountered during encoding (including any errors from
	// encoding nested attributes) will be returned here.
	b, err := ae.Encode()
	if err != nil {
		log.Fatalf("failed to encode attributes: %v", err)
	}

	// Now decode the attributes again to verify the contents.
	ad, err := netlink.NewAttributeDecoder(b)
	if err != nil {
		log.Fatalf("failed to decode attributes: %v", err)
	}

	// Walk the attributes and print each out.
	for ad.Next() {
		switch ad.Type() {
		case 1:
			fmt.Println("uint16:", ad.Uint16())
		case 2:
			fmt.Println("string:", ad.String())
		case 3:
			fmt.Println("nested:")

			// Nested attributes use their own nested decoder.
			ad.Nested(func(nad *netlink.AttributeDecoder) error {
				for nad.Next() {
					switch nad.Type() {
					case 1:
						fmt.Println("  - A:", nad.Uint32())
					case 2:
						fmt.Println("  - B:", nad.Uint32())
					}
				}
				return nil
			})
		}
	}

	// Output: uint16: 1
	// string: hello world
	// nested:
	//   - A: 2
	//   - B: 3
}