Skip to content

Commit 2bbba08

Browse files
adrianchirisaboch
authored andcommitted
Add ParseRouteAttrAsMap helper function
This will allow to parse nl attributes, returning a map for easy access to each attribute. Signed-off-by: adrianc <[email protected]>
1 parent 51f9bba commit 2bbba08

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

nl/nl_linux.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -910,6 +910,22 @@ func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) {
910910
return attrs, nil
911911
}
912912

913+
// ParseRouteAttrAsMap parses provided buffer that contains raw RtAttrs and returns a map of parsed
914+
// atttributes indexed by attribute type or error if occured.
915+
func ParseRouteAttrAsMap(b []byte) (map[uint16]syscall.NetlinkRouteAttr, error) {
916+
attrMap := make(map[uint16]syscall.NetlinkRouteAttr)
917+
918+
attrs, err := ParseRouteAttr(b)
919+
if err != nil {
920+
return nil, err
921+
}
922+
923+
for _, attr := range attrs {
924+
attrMap[attr.Attr.Type] = attr
925+
}
926+
return attrMap, nil
927+
}
928+
913929
func netlinkRouteAttrAndValue(b []byte) (*unix.RtAttr, []byte, int, error) {
914930
a := (*unix.RtAttr)(unsafe.Pointer(&b[0]))
915931
if int(a.Len) < unix.SizeofRtAttr || int(a.Len) > len(b) {

nl/nl_linux_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,25 @@ func TestCnMsgOpDeserializeSerialize(t *testing.T) {
130130
msg := DeserializeCnMsgOp(orig)
131131
testDeserializeSerialize(t, orig, safemsg, msg)
132132
}
133+
134+
func TestParseRouteAttrAsMap(t *testing.T) {
135+
attr1 := NewRtAttr(0x1, ZeroTerminated("foo"))
136+
attr2 := NewRtAttr(0x2, ZeroTerminated("bar"))
137+
raw := make([]byte, 0)
138+
raw = append(raw, attr1.Serialize()...)
139+
raw = append(raw, attr2.Serialize()...)
140+
attrs, err := ParseRouteAttrAsMap(raw)
141+
if err != nil {
142+
t.Errorf("failed to parse route attributes %s", err)
143+
}
144+
145+
attr, ok := attrs[0x1]
146+
if !ok || BytesToString(attr.Value) != "foo" {
147+
t.Error("missing/incorrect \"foo\" attribute")
148+
}
149+
150+
attr, ok = attrs[0x2]
151+
if !ok || BytesToString(attr.Value) != "bar" {
152+
t.Error("missing/incorrect \"bar\" attribute")
153+
}
154+
}

0 commit comments

Comments
 (0)