Skip to content

Commit

Permalink
fix clone on invalid values
Browse files Browse the repository at this point in the history
  • Loading branch information
OneOfOne committed Jan 14, 2025
1 parent ed5e4c9 commit c9292af
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func reflectClone(dst, src reflect.Value, keepPrivateFields, checkClone, noMake
}

if !noMake {
dst.Set(reflect.MakeSlice(styp, src.Len(), src.Cap()))
dst.Set(reflect.MakeSlice(styp, 0, src.Cap()))
}
fallthrough

Expand All @@ -62,7 +62,10 @@ func reflectClone(dst, src reflect.Value, keepPrivateFields, checkClone, noMake
simple := isSimple(styp.Elem().Kind())
hasClone := isPtr && isCloner(styp.Elem().Elem()) != math.MaxInt
for i := 0; i < src.Len(); i++ {
dst, src := dst.Index(i), src.Index(i)
src := src.Index(i)
if src.Kind() == reflect.Invalid {
continue
}
if simple {
dst.Set(src)
continue
Expand All @@ -75,7 +78,7 @@ func reflectClone(dst, src reflect.Value, keepPrivateFields, checkClone, noMake
src = src.Elem()
ndst := reflect.New(src.Type())
reflectClone(ndst.Elem(), src, keepPrivateFields, hasClone, false)
dst.Set(ndst)
dst = reflect.Append(dst, ndst)
continue
}

Expand All @@ -86,10 +89,12 @@ func reflectClone(dst, src reflect.Value, keepPrivateFields, checkClone, noMake

src = src.Elem()
if isSimple(src.Kind()) {
dst.Set(src)
dst = reflect.Append(dst, src)
continue
}
dst.Set(maybeCopy(src, keepPrivateFields))
if src.Kind() != reflect.Invalid {
dst = reflect.Append(dst, maybeCopy(src, keepPrivateFields))
}
}

case reflect.Map:
Expand Down Expand Up @@ -184,7 +189,7 @@ func isSimple(k reflect.Kind) bool {
}

func maybeCopy(src reflect.Value, copyPrivate bool) reflect.Value {
if src.IsZero() {
if src.Kind() == reflect.Invalid || src.IsZero() {
return src
}

Expand Down

0 comments on commit c9292af

Please sign in to comment.