...

Source file src/github.com/cilium/ebpf/marshaler_example_test.go

Documentation: github.com/cilium/ebpf

     1  package ebpf
     2  
     3  import (
     4  	"encoding"
     5  	"fmt"
     6  	"strings"
     7  )
     8  
     9  // Assert that customEncoding implements the correct interfaces.
    10  var (
    11  	_ encoding.BinaryMarshaler   = (*customEncoding)(nil)
    12  	_ encoding.BinaryUnmarshaler = (*customEncoding)(nil)
    13  )
    14  
    15  type customEncoding struct {
    16  	data string
    17  }
    18  
    19  func (ce *customEncoding) MarshalBinary() ([]byte, error) {
    20  	return []byte(strings.ToUpper(ce.data)), nil
    21  }
    22  
    23  func (ce *customEncoding) UnmarshalBinary(buf []byte) error {
    24  	ce.data = string(buf)
    25  	return nil
    26  }
    27  
    28  // ExampleMarshaler shows how to use custom encoding with map methods.
    29  func Example_customMarshaler() {
    30  	hash := createHash()
    31  	defer hash.Close()
    32  
    33  	if err := hash.Put(&customEncoding{"hello"}, uint32(111)); err != nil {
    34  		panic(err)
    35  	}
    36  
    37  	var (
    38  		key     customEncoding
    39  		value   uint32
    40  		entries = hash.Iterate()
    41  	)
    42  
    43  	for entries.Next(&key, &value) {
    44  		fmt.Printf("key: %s, value: %d\n", key.data, value)
    45  	}
    46  
    47  	if err := entries.Err(); err != nil {
    48  		panic(err)
    49  	}
    50  
    51  	// Output: key: HELLO, value: 111
    52  }
    53  

View as plain text