Skip to content

Commit

Permalink
fix: copy nil slices correctly in DeepCopy (#3944)
Browse files Browse the repository at this point in the history
  • Loading branch information
jvmakine authored Jan 8, 2025
1 parent d7895a1 commit 33abdd2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
10 changes: 5 additions & 5 deletions common/reflect/reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func copyAny(src any, ptrs map[uintptr]any, copyConf *copyConfig) (dst any) {
reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64,
reflect.Complex64, reflect.Complex128, reflect.Func:
dst = copyPremitive(src, ptrs, copyConf)
dst = copyPrimitive(src, ptrs, copyConf)
case reflect.String:
dst = strings.Clone(src.(string))
case reflect.Slice:
Expand All @@ -167,9 +167,6 @@ func copyAny(src any, ptrs map[uintptr]any, copyConf *copyConfig) (dst any) {
}

func copyList(src *list.List, ptrs map[uintptr]any, copyConf *copyConfig) *list.List {
if src == nil {
return nil
}
dst := list.New()
for e := src.Front(); e != nil; e = e.Next() {
copiedValue := copyAny(e.Value, ptrs, copyConf)
Expand All @@ -178,7 +175,7 @@ func copyList(src *list.List, ptrs map[uintptr]any, copyConf *copyConfig) *list.
return dst
}

func copyPremitive(src any, ptr map[uintptr]any, copyConf *copyConfig) (dst any) {
func copyPrimitive(src any, ptr map[uintptr]any, copyConf *copyConfig) (dst any) {
kind := reflect.ValueOf(src).Kind()
switch kind {
case reflect.Array, reflect.Chan, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice, reflect.Struct, reflect.UnsafePointer:
Expand All @@ -194,6 +191,9 @@ func copySlice(x any, ptrs map[uintptr]any, copyConf *copyConfig) any {
if kind != reflect.Slice {
panic(fmt.Sprintf("reflect: internal error: type %v is not a slice", kind))
}
if v.IsNil() {
return x
}

size := v.Len()
t := reflect.TypeOf(x)
Expand Down
6 changes: 6 additions & 0 deletions common/reflect/reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ func TestCopyStructOfPointers(t *testing.T) {
}
}

func TestNilTypeCopyIsNil(t *testing.T) {
assert.Assert(t, DeepCopy([]int(nil)) == nil)
// TODO: fix map, and all "panic: assignment to entry in nil map" failures this fix will cause
// assert.Assert(t, DeepCopy(map[string]int(nil)) == nil)
}

func testEqualityOfStruct(t *testing.T, expected, actual *structOfPointers) {
t.Helper()
if expected == nil || actual == nil {
Expand Down

0 comments on commit 33abdd2

Please sign in to comment.