-
Notifications
You must be signed in to change notification settings - Fork 706
/
marshaler_example_test.go
60 lines (49 loc) · 1.09 KB
/
marshaler_example_test.go
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
package ebpf
import (
"encoding"
"fmt"
"strings"
)
// Assert that customEncoding implements the correct interfaces.
var (
_ encoding.BinaryMarshaler = (*customEncoding)(nil)
_ encoding.BinaryUnmarshaler = (*customEncoding)(nil)
)
type customEncoding struct {
data string
}
func (ce *customEncoding) MarshalBinary() ([]byte, error) {
return []byte(strings.ToUpper(ce.data)), nil
}
func (ce *customEncoding) UnmarshalBinary(buf []byte) error {
ce.data = string(buf)
return nil
}
// ExampleMarshaler shows how to use custom encoding with map methods.
func Example_customMarshaler() {
hash, err := NewMap(&MapSpec{
Type: Hash,
KeySize: 5,
ValueSize: 4,
MaxEntries: 10,
})
if err != nil {
panic(err)
}
defer hash.Close()
if err := hash.Put(&customEncoding{"hello"}, uint32(111)); err != nil {
panic(err)
}
var (
key customEncoding
value uint32
entries = hash.Iterate()
)
for entries.Next(&key, &value) {
fmt.Printf("key: %s, value: %d\n", key.data, value)
}
if err := entries.Err(); err != nil {
panic(err)
}
// Output: key: HELLO, value: 111
}