Add ParseRouteAttrAsMap helper function

This will allow to parse nl attributes, returning a map
for easy access to each attribute.

Signed-off-by: adrianc <adrianc@nvidia.com>
This commit is contained in:
adrianc 2023-11-13 18:10:29 +02:00 committed by Alessandro Boch
parent 51f9bba1cd
commit 2bbba08be2
2 changed files with 38 additions and 0 deletions

View File

@ -910,6 +910,22 @@ func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) {
return attrs, nil 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) { func netlinkRouteAttrAndValue(b []byte) (*unix.RtAttr, []byte, int, error) {
a := (*unix.RtAttr)(unsafe.Pointer(&b[0])) a := (*unix.RtAttr)(unsafe.Pointer(&b[0]))
if int(a.Len) < unix.SizeofRtAttr || int(a.Len) > len(b) { if int(a.Len) < unix.SizeofRtAttr || int(a.Len) > len(b) {

View File

@ -130,3 +130,25 @@ func TestCnMsgOpDeserializeSerialize(t *testing.T) {
msg := DeserializeCnMsgOp(orig) msg := DeserializeCnMsgOp(orig)
testDeserializeSerialize(t, orig, safemsg, msg) 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")
}
}