Skip to content

Commit

Permalink
CR fixes
Browse files Browse the repository at this point in the history
Signed-off-by: Alun Evans <[email protected]>
  • Loading branch information
alxn committed Nov 15, 2023
1 parent 84abd93 commit 119bf0d
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
13 changes: 9 additions & 4 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,13 @@ func ensurePerCPUSlice(sliceOrPtr any, elemLength int) (any, error) {
return nil, fmt.Errorf("per-cpu slice is incorrect length, expected %d, got %d",
possibleCPUs, sliceValue.Len())
}
if sliceOrPtrType.Elem().Kind() == reflect.Pointer {
for i := 0; i < sliceValue.Len(); i++ {
if !sliceValue.Index(i).Elem().CanAddr() {
return nil, fmt.Errorf("per-cpu slice elements cannot be nil")
}
}
}
return sliceValue.Interface(), nil
}

Expand All @@ -717,10 +724,8 @@ func ensurePerCPUSlice(sliceOrPtr any, elemLength int) (any, error) {
sliceElemType = sliceElemType.Elem()

for i := 0; i < possibleCPUs; i++ {
if sliceElemIsPointer {
newElem := reflect.New(sliceElemType)
slice.Index(i).Set(newElem)
}
newElem := reflect.New(sliceElemType)
slice.Index(i).Set(newElem)
}

return slice.Interface(), nil
Expand Down
3 changes: 3 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1350,6 +1350,9 @@ func TestPerCPUMarshaling(t *testing.T) {

// Make sure unmarshaling works on slices containing pointers
retrievedVal := make([]*customEncoding, numCPU)
if err := arr.Lookup(uint32(0), retrievedVal); err == nil {
t.Fatal("Slices with nil values should generate error")
}
for i := range retrievedVal {
retrievedVal[i] = &customEncoding{}
}
Expand Down
9 changes: 7 additions & 2 deletions marshalers.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func marshalPerCPUValue(slice any, elemLength int) (sys.Pointer, error) {
// unmarshalPerCPUValue decodes a buffer into a slice containing one value per
// possible CPU.
//
// slicePtr must be a pointer to a slice.
// slice must be a literal slice and not a pointer.
func unmarshalPerCPUValue(slice any, elemLength int, buf []byte) error {
sliceType := reflect.TypeOf(slice)
if sliceType.Kind() != reflect.Slice {
Expand All @@ -97,7 +97,12 @@ func unmarshalPerCPUValue(slice any, elemLength int, buf []byte) error {
}

sliceValue := reflect.ValueOf(slice)

if sliceValue.Len() < possibleCPUs {
// Should be impossible here from ensurePerCPUSlice(),
// but avoid a panic in the loop.
return fmt.Errorf("per-cpu value slice len %q is less than possibleCPU %q",
sliceValue.Len(), possibleCPUs)
}
sliceElemType := sliceType.Elem()
sliceElemIsPointer := sliceElemType.Kind() == reflect.Ptr
stride := internal.Align(elemLength, 8)
Expand Down

0 comments on commit 119bf0d

Please sign in to comment.