github.com/dylandreimerink/gobpfld@v0.6.1-0.20220205171531-e79c330ad608/cmd/examples/map_iterator/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/dylandreimerink/gobpfld" 8 "github.com/dylandreimerink/gobpfld/bpfsys" 9 "github.com/dylandreimerink/gobpfld/bpftypes" 10 ) 11 12 const mapSize = 10 13 14 func main() { 15 testMap := &gobpfld.ArrayMap{ 16 AbstractMap: gobpfld.AbstractMap{ 17 Name: gobpfld.MustNewObjName("xdp_stats_map"), 18 Definition: gobpfld.BPFMapDef{ 19 Type: bpftypes.BPF_MAP_TYPE_ARRAY, 20 KeySize: 4, // SizeOf(uint32) 21 ValueSize: 8, // SizeOf(uint64) 22 MaxEntries: mapSize + 1, 23 }, 24 }, 25 } 26 var ( 27 key uint32 28 value uint64 29 ) 30 31 err := testMap.Load() 32 if err != nil { 33 fmt.Fprintf(os.Stderr, "error while loading map: %s\n", err.Error()) 34 os.Exit(1) 35 } 36 37 for i := uint32(1); i <= mapSize; i++ { 38 val := uint64(i * 10) 39 err = testMap.Set(i, &val, bpfsys.BPFMapElemAny) 40 if err != nil { 41 fmt.Fprintf(os.Stderr, "error while setting to map: %s\n", err.Error()) 42 os.Exit(1) 43 } 44 } 45 46 fmt.Println("[iterator foreach pointers]") 47 fmt.Println("------------------------") 48 49 iter := testMap.Iterator() 50 err = gobpfld.MapIterForEach(iter, &key, &value, func(_, _ interface{}) error { 51 fmt.Printf("key: %d, value: %d\n", key, value) 52 return nil 53 }) 54 if err != nil { 55 fmt.Fprintf(os.Stderr, "foreach ptr: %s\n", err.Error()) 56 os.Exit(1) 57 } 58 59 fmt.Println("\n[iterator foreach values]") 60 fmt.Println("------------------------") 61 62 iter = testMap.Iterator() 63 err = gobpfld.MapIterForEach(iter, uint32(0), uint64(0), func(k, v interface{}) error { 64 kp := k.(*uint32) 65 vp := v.(*uint64) 66 fmt.Printf("key: %d, value: %d\n", *kp, *vp) 67 return nil 68 }) 69 if err != nil { 70 fmt.Fprintf(os.Stderr, "foreach value: %s\n", err.Error()) 71 os.Exit(1) 72 } 73 74 fmt.Println("\n[iterator init + next]") 75 fmt.Println("------------------------") 76 77 iter = testMap.Iterator() 78 err = iter.Init(&key, &value) 79 if err != nil { 80 fmt.Fprintf(os.Stderr, "error iter init: %s\n", err.Error()) 81 os.Exit(1) 82 } 83 84 var updated bool 85 for updated, err = iter.Next(); updated && err == nil; updated, err = iter.Next() { 86 fmt.Printf("key: %v, value: %v\n", key, value) 87 } 88 if err != nil { 89 fmt.Fprintf(os.Stderr, "error iter next: %s\n", err.Error()) 90 os.Exit(1) 91 } 92 93 }