Skip to content

Commit

Permalink
Avoid panic when calling Elem on a nil map member. (#941)
Browse files Browse the repository at this point in the history
* (M) ygot/struct_validation_map(_test)?.go
   - if a map was received that had a nil value in it, this caused
     a panic to occur since `(reflect.Value).Elem()` does not handle
     these cases cleanly. Add a check whether the value is nil before
     calling Elem.
  • Loading branch information
robshakir authored Dec 12, 2023
1 parent 4dcc65e commit 8efc814
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
4 changes: 4 additions & 0 deletions ygot/struct_validation_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,10 @@ func copyMapField(dstField, srcField reflect.Value, accessPath string, opts ...M
errs.Separator = "\n"
for _, k := range srcField.MapKeys() {
v := srcField.MapIndex(k)
if v.IsNil() {
errs.Add(fmt.Errorf("map key %v, got nil value", k.Interface()))
continue
}
d := reflect.New(v.Elem().Type())
if _, ok := dstKeys[k.Interface()]; ok {
d = dstField.MapIndex(k)
Expand Down
9 changes: 9 additions & 0 deletions ygot/struct_validation_map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1617,6 +1617,15 @@ func TestCopyStruct(t *testing.T) {
wantDst: &copyTest{
StructMap: map[copyMapKey]*copyTest{},
},
}, {
name: "string map with explicit nil value",
inSrc: &copyTest{
StringMap: map[string]*copyTest{
"fish": nil,
},
},
inDst: &copyTest{},
wantErr: true,
}}

for _, tt := range tests {
Expand Down

0 comments on commit 8efc814

Please sign in to comment.