Avoid copying unused slice capacity
This commit is contained in:
@@ -47,7 +47,7 @@ func cloneTrustedReflect(value reflect.Value, active map[cloneReference]reflect.
|
||||
case reflect.Map:
|
||||
out = reflect.MakeMapWithSize(value.Type(), value.Len())
|
||||
case reflect.Slice:
|
||||
out = reflect.MakeSlice(value.Type(), value.Len(), value.Cap())
|
||||
out = reflect.MakeSlice(value.Type(), value.Len(), value.Len())
|
||||
}
|
||||
active[key] = out
|
||||
defer delete(active, key)
|
||||
|
||||
@@ -8,6 +8,28 @@ import (
|
||||
|
||||
type trustedNamed string
|
||||
|
||||
func TestCloneTrustedDoesNotCopySpareCapacity(t *testing.T) {
|
||||
type namedSlice []string
|
||||
for name, original := range map[string]any{
|
||||
"any": make([]any, 1, 64),
|
||||
"empty": make([]any, 0, 64),
|
||||
"strings": make([]string, 1, 64),
|
||||
"bytes": make([]byte, 1, 64),
|
||||
"named": make(namedSlice, 1, 64),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
copied := CloneTrusted(original)
|
||||
if !reflect.DeepEqual(copied, original) {
|
||||
t.Fatalf("copy changed slice contents or type: %#v", copied)
|
||||
}
|
||||
value := reflect.ValueOf(copied)
|
||||
if value.Cap() != value.Len() {
|
||||
t.Fatalf("copy reserves unused storage: len=%d cap=%d", value.Len(), value.Cap())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneTrustedPreservesTypesAndDetaches(t *testing.T) {
|
||||
named := trustedNamed("value")
|
||||
original := map[string]any{"": map[string]any{"number": json.Number("9007199254740993")}, "typed": []string{"original"}, "pointer": &named, "nilmap": map[string]any(nil), "nilslice": []string(nil), "empty": []any{}}
|
||||
|
||||
Reference in New Issue
Block a user