Skip to content

Commit

Permalink
Add ParseRouteAttrAsMap helper function
Browse files Browse the repository at this point in the history
This will allow to parse nl attributes, returning a map
for easy access to each attribute.

Signed-off-by: adrianc <[email protected]>
  • Loading branch information
adrianchiris committed Jan 22, 2024
1 parent 51f9bba commit 1047a30
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
16 changes: 16 additions & 0 deletions nl/nl_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,22 @@ func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) {
return attrs, nil
}

// ParseRouteAttrAsMap parses provided buffer that contains raw RtAttrs and returns a map of parsed
// atttributes indexed by attribute type or error if occured.
func ParseRouteAttrAsMap(b []byte) (map[uint16]syscall.NetlinkRouteAttr, error) {
attrMap := make(map[uint16]syscall.NetlinkRouteAttr)

attrs, err := ParseRouteAttr(b)
if err != nil {
return nil, err
}

for _, attr := range attrs {
attrMap[attr.Attr.Type] = attr
}
return attrMap, nil
}

func netlinkRouteAttrAndValue(b []byte) (*unix.RtAttr, []byte, int, error) {
a := (*unix.RtAttr)(unsafe.Pointer(&b[0]))
if int(a.Len) < unix.SizeofRtAttr || int(a.Len) > len(b) {
Expand Down
22 changes: 22 additions & 0 deletions nl/nl_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,25 @@ func TestCnMsgOpDeserializeSerialize(t *testing.T) {
msg := DeserializeCnMsgOp(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}

func TestParseRouteAttrAsMap(t *testing.T) {
attr1 := NewRtAttr(0x1, ZeroTerminated("foo"))
attr2 := NewRtAttr(0x2, ZeroTerminated("bar"))
raw := make([]byte, 0)
raw = append(raw, attr1.Serialize()...)
raw = append(raw, attr2.Serialize()...)
attrs, err := ParseRouteAttrAsMap(raw)
if err != nil {
t.Errorf("failed to parse route attributes %s", err)
}

attr, ok := attrs[0x1]
if !ok || BytesToString(attr.Value) != "foo" {
t.Error("missing/incorrect \"foo\" attribute")
}

attr, ok = attrs[0x2]
if !ok || BytesToString(attr.Value) != "bar" {
t.Error("missing/incorrect \"bar\" attribute")
}
}

0 comments on commit 1047a30

Please sign in to comment.