diff --git a/README.md b/README.md index f0d0eb9..6304260 100644 --- a/README.md +++ b/README.md @@ -40,13 +40,14 @@ func (r *Request) Reset() { | Field | Reset | |---|---| -| slice | `clear(s); s = s[:0]` — the backing array is kept | -| pointer, map, chan, interface, func | `nil` | +| slice | `clear(s); s = s[:0]` — the backing array is kept; when the elements hold pointers, `clear(s[:cap(s)])`, so the array keeps nothing alive | +| pointer, `unsafe.Pointer`, map, chan, interface, func | `nil` (an interface too when its methods include `Reset()`) | | numbers, bool, string, arrays, plain structs | zero value | | value with its own `Reset()` | `r.F.Reset()` | | pointer with its own `Reset()` | kept; `r.F.Reset()` when not nil | -| `atomic.*` | `Store(0)` / `Store(false)` / `Store(nil)` | +| `sync/atomic` types | `Store(0)` / `Store(false)` / `Store(nil)`; `atomic.Value` is set to its zero value | | `sync.*` (Mutex, WaitGroup, Pool...) | left alone | +| `_` (padding) | left out: field by field it is not touched, bulk mode zeroes it | Struct tags change the treatment of a field: @@ -79,7 +80,9 @@ The mode is chosen per type by a cost model, in units of one field store: | array, struct without `Reset()` | 0 | 1 per 16 bytes | The cheaper mode is generated; a `sync` field forces field-wise mode whatever -the costs. The constants were fitted on two real structs (700 bytes / 95 +the costs, and so does a field bulk mode would keep by copy (`reset:"-"`, +`call=` on a value, a value with `Reset()`) whose value holds a lock: a +`sync` or `sync/atomic` value, or a type `go vet` treats as a lock. The constants were fitted on two real structs (700 bytes / 95 fields: both modes equal; 2400 bytes / 74 fields: field-wise 2.5x faster) — a model, not a measurement, so a struct near the break-even point is worth a benchmark of its own. diff --git a/doc.go b/doc.go index efaea78..7088385 100644 --- a/doc.go +++ b/doc.go @@ -12,7 +12,8 @@ // Conn *Conn `reset:"release=PutConn"` // PutConn(r.Conn); r.Conn = nil // // Fields of sync types are never touched, and a struct holding one is reset -// field by field. Any other struct is reset either in one assignment +// field by field, as is a struct whose kept fields (reset:"-", call=, values +// with Reset) hold a lock that one assignment would copy. Any other struct is reset either in one assignment // (`*r = T{}`) with the kept fields restored after it, or field by field, // whichever a cost model built on the field sizes rates cheaper; the // generated comment says which and why. diff --git a/goreset.go b/goreset.go index c19a5e6..1943905 100644 --- a/goreset.go +++ b/goreset.go @@ -5,8 +5,10 @@ import ( "fmt" "go/format" "go/types" + "path" "reflect" "slices" + "strconv" "strings" "text/template" ) @@ -35,9 +37,10 @@ func FileName(typeName string) string { } type fieldInfo struct { - Import string - Field string - Code string // field-wise reset + // Imports are the paths of the packages Code names. + Imports []string + Field string + Code string // field-wise reset // bulk mode: Keep runs before `*r = T{}`, Restore after. Empty Keep with // empty Restore means the bulk zeroing already did the right thing. Keep string @@ -103,20 +106,35 @@ func (p *Package) Analyze(typeName string) (Result, error) { // asks for through import=, e.g. `reset:"value=consts.Default,import=example.com/consts"`. tagImports []string fields []fieldInfo + names = importNames{byPath: map[string]string{}, byName: map[string]string{}, own: map[string]string{}} ) + // a value= expression names its import= package by the package's own + // name, so those names are taken first; field types get the rest + for i := range structType.NumFields() { + if imp := parseTag(reflect.StructTag(structType.Tag(i)).Get("reset")).importPath; imp != "" { + names.name(imp, path.Base(imp)) + } + } + for i := range structType.NumFields() { f := structType.Field(i) + if f.Name() == "_" { + continue // padding: it cannot be referred to, and nothing reads it + } + tag := reflect.StructTag(structType.Tag(i)).Get("reset") if tag == "-" { - fields = append(fields, fieldInfo{ + info := fieldInfo{ Field: f.Name(), Code: fmt.Sprintf("// r.%s skipped via tag", f.Name()), Keep: fmt.Sprintf("keep%s := r.%s", f.Name(), f.Name()), Restore: fmt.Sprintf("r.%s = keep%s", f.Name(), f.Name()), BulkExtra: costKeep, - }) + } + p.forbidCopy(&info, f.Type()) + fields = append(fields, info) continue } @@ -132,7 +150,9 @@ func (p *Package) Analyze(typeName string) (Result, error) { case opts.call != "": // call=Method keeps the field value and calls its method instead, // e.g. `reset:"call=Stop"` for a reusable *time.Timer. - fields = append(fields, callCode(f, opts.call)) + info := callCode(f, opts.call) + p.forbidCopy(&info, f.Type()) + fields = append(fields, info) case opts.value != "": // value=EXPR resets the field to EXPR instead of the zero value, @@ -146,14 +166,12 @@ func (p *Package) Analyze(typeName string) (Result, error) { }) default: - fields = append(fields, p.resetCode(f, opts.release)) + fields = append(fields, p.resetCode(f, opts.release, &names)) } } for i := range fields { - if f := &fields[i]; f.Import != "" { - imports = append(imports, f.Import) - } + imports = append(imports, fields[i].Imports...) } slices.SortFunc(fields, func(a, b fieldInfo) int { @@ -207,6 +225,9 @@ func (p *Package) Analyze(typeName string) (Result, error) { } imports = slices.Compact(slices.Sorted(slices.Values(imports))) + for i, path := range imports { + imports[i] = names.spec(path) + } data := struct { PackageName string @@ -271,10 +292,10 @@ func cut(part, prefix string, dst *string) bool { return ok } -func (p *Package) resetCode(f *types.Var, release string) fieldInfo { +func (p *Package) resetCode(f *types.Var, release string, names *importNames) fieldInfo { var ( - info fieldInfo - importPath string + info fieldInfo + imports []string ) qualifier := func(other *types.Package) string { @@ -282,9 +303,9 @@ func (p *Package) resetCode(f *types.Var, release string) fieldInfo { return "" } - importPath = other.Path() + imports = append(imports, other.Path()) - return other.Name() + return names.name(other.Path(), other.Name()) } info.Field = f.Name() @@ -292,11 +313,14 @@ func (p *Package) resetCode(f *types.Var, release string) fieldInfo { info.Weight = costStore // the common case: one statement, nothing to keep - if strings.HasPrefix(typeName, "atomic.") { - switch { - case strings.HasPrefix(typeName, "atomic.Pointer"): + // The sync/atomic types are stored to, but Value is zeroed by the + // assignment below: its Store panics on nil and on a type other than + // the one stored before, so it has no zero to store. + if atomicName := syncAtomicName(f.Type()); atomicName != "" && atomicName != "Value" { + switch atomicName { + case "Pointer": info.Code = fmt.Sprintf("r.%s.Store(nil)", info.Field) - case typeName == "atomic.Bool": + case "Bool": info.Code = fmt.Sprintf("r.%s.Store(false)", info.Field) default: info.Code = fmt.Sprintf("r.%s.Store(0)", info.Field) @@ -318,7 +342,9 @@ func (p *Package) resetCode(f *types.Var, release string) fieldInfo { return info } - if hasResetMethod(f.Type()) { + // An interface is set to nil even when its method set has Reset: the + // call would panic on a nil value and keep a non-nil one. + if _, ok := f.Type().Underlying().(*types.Interface); !ok && hasResetMethod(f.Type()) { if _, ok := f.Type().(*types.Pointer); ok { if release != "" { info.Code = fmt.Sprintf("if r.%s != nil { %s(r.%s); r.%s = nil }", info.Field, release, info.Field, info.Field) @@ -344,14 +370,22 @@ func (p *Package) resetCode(f *types.Var, release string) fieldInfo { info.Keep = fmt.Sprintf("keep%s := r.%s", info.Field, info.Field) info.Restore = fmt.Sprintf("r.%s = keep%s\n\tr.%s.Reset()", info.Field, info.Field, info.Field) info.BulkExtra = costKeep + 2*units(p.sizes.Sizeof(f.Type())) + p.forbidCopy(&info, f.Type()) return info } switch ut := f.Type().Underlying().(type) { case *types.Slice: - info.Code = fmt.Sprintf("clear(r.%s)\nr.%s = r.%s[:0]", info.Field, info.Field, info.Field) - info.Keep = fmt.Sprintf("clear(r.%s)\n\tkeep%s := r.%s[:0]", info.Field, info.Field, info.Field) + // Elements past len(s) that hold pointers keep their memory alive + // until the slice grows over them: clear those up to cap(s). + cleared := "r." + info.Field + if hasPointers(ut.Elem()) { + cleared = fmt.Sprintf("r.%s[:cap(r.%s)]", info.Field, info.Field) + } + + info.Code = fmt.Sprintf("clear(%s)\nr.%s = r.%s[:0]", cleared, info.Field, info.Field) + info.Keep = fmt.Sprintf("clear(%s)\n\tkeep%s := r.%s[:0]", cleared, info.Field, info.Field) info.Restore = fmt.Sprintf("r.%s = keep%s", info.Field, info.Field) info.Weight = costSlice info.BulkExtra = costSliceBK @@ -369,21 +403,90 @@ func (p *Package) resetCode(f *types.Var, release string) fieldInfo { info.Code = fmt.Sprintf("r.%s = 0", info.Field) case ut.Info()&types.IsBoolean != 0: info.Code = fmt.Sprintf("r.%s = false", info.Field) - default: // string + case ut.Info()&types.IsString != 0: info.Code = fmt.Sprintf("r.%s = \"\"", info.Field) + default: // unsafe.Pointer + info.Code = fmt.Sprintf("r.%s = nil", info.Field) } return info } // arrays and structs without Reset: assign the zero value, a memclr of the field - info.Import = importPath + info.Imports = imports info.Code = fmt.Sprintf("r.%s = %s{}", info.Field, typeName) info.Weight = units(p.sizes.Sizeof(f.Type())) return info } +// hasPointers reports whether a value of type t holds a pointer the garbage +// collector follows: a string, a pointer, a slice, a map, a channel, a func, +// an interface, or an array or struct with one of those. +func hasPointers(t types.Type) bool { + switch ut := t.Underlying().(type) { + case *types.Basic: + return ut.Info()&types.IsString != 0 || ut.Kind() == types.UnsafePointer + case *types.Array: + return hasPointers(ut.Elem()) + case *types.Struct: + for field := range ut.Fields() { + if hasPointers(field.Type()) { + return true + } + } + + return false + default: + return true + } +} + +// syncAtomicName is the name of t when t is a type of sync/atomic, "" if not. +func syncAtomicName(t types.Type) string { + named, ok := types.Unalias(t).(*types.Named) + if !ok || named.Obj().Pkg() == nil || named.Obj().Pkg().Path() != "sync/atomic" { + return "" + } + + return named.Obj().Name() +} + +// importNames gives every package the generated code names a name of its +// own: the package name, or, when another package has it already, that +// name with a number appended (atomic, atomic2). +type importNames struct { + byPath map[string]string // import path → name in the generated file + byName map[string]string // name → import path + own map[string]string // import path → package name +} + +// name returns the name of the package at importPath, whose own name is own. +func (n *importNames) name(importPath, own string) string { + if name, ok := n.byPath[importPath]; ok { + return name + } + + name := own + for i := 2; n.byName[name] != ""; i++ { + name = own + strconv.Itoa(i) + } + + n.byPath[importPath], n.byName[name], n.own[importPath] = name, importPath, own + + return name +} + +// spec is the import line for importPath: quoted, with the name in front when it +// is not the package's own. +func (n *importNames) spec(importPath string) string { + if name := n.byPath[importPath]; name != n.own[importPath] { + return name + " " + strconv.Quote(importPath) + } + + return strconv.Quote(importPath) +} + // units is the cost of zeroing or copying size bytes in bulk. func units(size int64) int { return max(1, int((size+bytesPerUnit-1)/bytesPerUnit)) @@ -393,9 +496,10 @@ func callCode(f *types.Var, method string) fieldInfo { info := fieldInfo{Field: f.Name(), Weight: costStore, BulkExtra: costKeep} info.Keep = fmt.Sprintf("keep%s := r.%s", info.Field, info.Field) - if _, ok := f.Type().Underlying().(*types.Pointer); ok { + switch f.Type().Underlying().(type) { + case *types.Pointer, *types.Interface: info.Code = fmt.Sprintf("if r.%s != nil { r.%s.%s() }", info.Field, info.Field, method) - } else { + default: info.Code = fmt.Sprintf("r.%s.%s()", info.Field, method) } @@ -411,8 +515,75 @@ func isForbidden(typeName string) bool { return strings.HasPrefix(typeName, "sync.") } +// forbidCopy rules bulk mode out for a field that bulk mode keeps by copy +// (reset:"-", call=, a value with Reset) when its value holds a lock. +func (p *Package) forbidCopy(info *fieldInfo, t types.Type) { + lock := heldLock(t) + if lock == "" { + return + } + + typeName := types.TypeString(t, types.RelativeTo(p.pkg)) + info.Forbidden = true + info.Reason = fmt.Sprintf("%s holds a %s, which bulk mode would copy", info.Field, lock) + info.Hint = fmt.Sprintf("%s: a %s holds a %s, so it cannot be kept across the assignment; "+ + "make the field a pointer, or keep the lock outside the pooled value", info.Field, typeName, lock) +} + +// heldLock names the lock a value of type t holds, "" if none: a type of +// sync or sync/atomic, or, as go vet's copylocks check sees it, a struct +// whose pointer is a sync.Locker and whose value is not. Pointers, +// interfaces and the like hold nothing; arrays and struct fields are +// searched (a struct cannot hold itself by value, so this ends). +func heldLock(t types.Type) string { + for { + arr, ok := t.Underlying().(*types.Array) + if !ok { + break + } + + t = arr.Elem() + } + + st, ok := t.Underlying().(*types.Struct) + if !ok { + return "" + } + + if named, ok := types.Unalias(t).(*types.Named); ok && named.Obj().Pkg() != nil { + switch named.Obj().Pkg().Path() { + case "sync", "sync/atomic": + return types.TypeString(named, func(p *types.Package) string { return p.Name() }) + } + } + + if isLocker(types.NewPointer(t)) && !isLocker(t) { + return types.TypeString(t, func(p *types.Package) string { return p.Name() }) + } + + for field := range st.Fields() { + if lock := heldLock(field.Type()); lock != "" { + return lock + } + } + + return "" +} + +// isLocker reports whether t has Lock() and Unlock() methods. +func isLocker(t types.Type) bool { + return hasNiladicMethod(t, false, "Lock") && hasNiladicMethod(t, false, "Unlock") +} + +// hasResetMethod reports whether r.F.Reset() compiles for a field of type t. func hasResetMethod(t types.Type) bool { - meth, _, _ := types.LookupFieldOrMethod(t, true, nil, "Reset") + return hasNiladicMethod(t, true, "Reset") +} + +// hasNiladicMethod reports whether t has a method name without parameters +// and results; addressable counts the methods of *t too. +func hasNiladicMethod(t types.Type, addressable bool, name string) bool { + meth, _, _ := types.LookupFieldOrMethod(t, addressable, nil, name) if meth == nil { return false } @@ -430,7 +601,7 @@ package {{.PackageName}} import ( {{- range .Imports}} - "{{.}}" + {{.}} {{- end}} ) {{- end}} diff --git a/internal/cases/bulk/request_reset.gen.go b/internal/cases/bulk/request_reset.gen.go index fc27a6f..ad56609 100644 --- a/internal/cases/bulk/request_reset.gen.go +++ b/internal/cases/bulk/request_reset.gen.go @@ -18,7 +18,7 @@ func (r *Request) Reset() { keepDim := r.Dim keepDimPtr := r.DimPtr keepKeep := r.Keep - clear(r.Names) + clear(r.Names[:cap(r.Names)]) keepNames := r.Names[:0] keepTimer := r.Timer diff --git a/regression_test.go b/regression_test.go new file mode 100644 index 0000000..d43c4fc --- /dev/null +++ b/regression_test.go @@ -0,0 +1,468 @@ +package goreset_test + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/darxnet/goreset" +) + +// checkGenerated writes a throwaway module, generates Reset for typeNames +// into it and runs go vet and go test there: the generated code must compile, +// pass vet (copylocks among others) and behave as the module's own tests say. +// It returns the generated sources by type name. +func checkGenerated(t *testing.T, name string, files map[string]string, typeNames ...string) map[string]string { + t.Helper() + + dir := writeModule(t, name, files) + + pkg, err := goreset.Load(dir) + if err != nil { + t.Fatal(err) + } + + srcs := make(map[string]string, len(typeNames)) + + for _, typeName := range typeNames { + src, err := pkg.Generate(typeName) + if err != nil { + t.Fatalf("Generate(%s): %v", typeName, err) + } + + if err := os.WriteFile(filepath.Join(dir, goreset.FileName(typeName)), src, 0o600); err != nil { + t.Fatal(err) + } + + srcs[typeName] = string(src) + } + + for _, args := range [][]string{{"vet", "./..."}, {"test", "-count=1", "-timeout=60s", "./..."}} { + cmd := exec.Command("go", args...) //nolint:gosec // fixed go subcommands + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GOWORK=off", "GOFLAGS=") + + if out, err := cmd.CombinedOutput(); err != nil { + var all strings.Builder + for typeName, src := range srcs { + all.WriteString("--- " + typeName + " ---\n" + src) + } + + t.Fatalf("go %s: %v\n%s\n%s", strings.Join(args, " "), err, out, all.String()) + } + } + + return srcs +} + +// TestInterfaceWithReset: an interface field is set to nil, even when its +// method set has Reset — calling it would panic on nil and keep the value. +func TestInterfaceWithReset(t *testing.T) { + t.Parallel() + + srcs := checkGenerated(t, "iface", map[string]string{ + "m.go": `package m + +import ( + "hash" + "sync" +) + +type Resetter interface{ Reset() } + +type Bulk struct { + H hash.Hash + R Resetter + A, B int +} + +type Fieldwise struct { + Mu sync.Mutex + H hash.Hash + R Resetter + C Resetter ` + "`" + `reset:"call=Reset"` + "`" + ` // kept: called when not nil +} +`, + "m_test.go": `package m + +import ( + "hash/fnv" + "testing" +) + +type res struct{} + +func (*res) Reset() {} + +func TestReset(t *testing.T) { + var b Bulk + b.Reset() + + b = Bulk{H: fnv.New32(), R: &res{}, A: 1} + b.Reset() + + if b.H != nil || b.R != nil || b.A != 0 { + t.Fatalf("Bulk = %+v, want zero", b) + } + + var f Fieldwise + f.Reset() + + f.H, f.R, f.C = fnv.New32(), &res{}, &res{} + f.Reset() + + if f.H != nil || f.R != nil || f.C == nil { + t.Fatalf("Fieldwise = %v %v %v, want H and R nil, C kept", f.H, f.R, f.C) + } +} +`, + }, "Bulk", "Fieldwise") + + if !strings.Contains(srcs["Bulk"], "*r = Bulk{}") { + t.Errorf("Bulk is not reset in one assignment:\n%s", srcs["Bulk"]) + } + + if !strings.Contains(srcs["Fieldwise"], "r.H = nil") || !strings.Contains(srcs["Fieldwise"], "r.R = nil") { + t.Errorf("Fieldwise does not set the interfaces to nil:\n%s", srcs["Fieldwise"]) + } +} + +// TestLocksNotCopied: bulk mode copies the fields it keeps, so a kept field +// holding a lock or a sync/atomic value (reset:"-", a value with Reset, +// call= on a value) forces field-wise mode, as a sync field does. +func TestLocksNotCopied(t *testing.T) { + t.Parallel() + + files := map[string]string{ + "m.go": `package m + +import ( + "sync" + "sync/atomic" +) + +type Stats struct { + mu sync.Mutex + n int +} + +func (s *Stats) Reset() { s.n = 0 } + +type Counter struct{ c atomic.Int64 } + +func (c *Counter) Clear() { c.c.Store(0) } + +// spin is a lock of its own: go vet's copylocks knows it by Lock and Unlock. +type spin struct{ v int32 } + +func (s *spin) Lock() { s.v = 1 } +func (s *spin) Unlock() { s.v = 0 } + +// Skipped keeps a lock through reset:"-". +type Skipped struct { + Mu [1]sync.Mutex ` + "`" + `reset:"-"` + "`" + ` + P0, P1, P2, P3, P4, P5, P6, P7 uint8 +} + +// Spun keeps a lock of its own through reset:"-". +type Spun struct { + L spin ` + "`" + `reset:"-"` + "`" + ` + P0, P1, P2, P3, P4, P5, P6, P7 uint8 +} + +// Nested has a value with Reset that holds a lock. +type Nested struct { + S Stats + P0, P1, P2, P3, P4, P5, P6, P7 uint8 +} + +// Called has call= on a value holding an atomic. +type Called struct { + C Counter ` + "`" + `reset:"call=Clear"` + "`" + ` + P0, P1, P2, P3, P4, P5, P6, P7 uint8 +} +`, + "m_test.go": `package m + +import "testing" + +func TestReset(t *testing.T) { + var s Skipped + s.Mu[0].Lock() + s.P0 = 1 + s.Reset() + if s.Mu[0].TryLock() || s.P0 != 0 { + t.Fatal("Skipped: Mu must stay locked, P0 zeroed") + } + + var sp Spun + sp.L.Lock() + sp.P0 = 1 + sp.Reset() + if sp.L.v != 1 || sp.P0 != 0 { + t.Fatal("Spun: L must stay locked, P0 zeroed") + } + + var n Nested + n.S.n = 1 + n.Reset() + if n.S.n != 0 { + t.Fatal("Nested: S not reset") + } + + var c Called + c.C.c.Store(5) + c.Reset() + if c.C.c.Load() != 0 { + t.Fatal("Called: Clear not called") + } +} +`, + } + + srcs := checkGenerated(t, "locks", files, "Skipped", "Spun", "Nested", "Called") + + for typeName, src := range srcs { + if strings.Contains(src, "*r = "+typeName+"{}") { + t.Errorf("%s holds a lock it keeps, yet is reset in one assignment:\n%s", typeName, src) + } + } + + pkg, err := goreset.Load(writeModule(t, "lockhints", files)) + if err != nil { + t.Fatal(err) + } + + res, err := pkg.Analyze("Nested") + if err != nil { + t.Fatal(err) + } + + wantReason := "S holds a sync.Mutex, which bulk mode would copy" + if res.Bulk || len(res.Hints) != 1 || !strings.HasPrefix(res.Hints[0], "S: a Stats holds a sync.Mutex") || + !strings.Contains(string(res.Source), wantReason) { + t.Fatalf("Analyze(Nested) = bulk %v, hints %q, want field-wise for %q:\n%s", + res.Bulk, res.Hints, wantReason, res.Source) + } +} + +// TestAtomics: sync/atomic types are reset through Store, except Value, +// which cannot store a zero of every type it may hold and is zeroed; a type +// of another package named atomic (go.uber.org/atomic) is no sync/atomic +// type, and two packages of the same name get distinct import names. +func TestAtomics(t *testing.T) { + t.Parallel() + + srcs := checkGenerated(t, "atomics", map[string]string{ + "atomic/atomic.go": `// Package atomic stands for go.uber.org/atomic. +package atomic + +type String struct{ v string } + +func (s *String) Store(v string) { s.v = v } +func (s *String) Load() string { return s.v } +`, + "m.go": `package m + +import ( + "sync" + "sync/atomic" + + uatomic "example.com/atomics/atomic" +) + +type Fieldwise struct { + Mu sync.Mutex + V atomic.Value + U atomic.Uint32 + S uatomic.String +} +`, + "m_test.go": `package m + +import "testing" + +func TestReset(t *testing.T) { + var f Fieldwise + f.Reset() + + f.V.Store("text") + f.U.Store(3) + f.S.Store("text") + f.Reset() + + if f.V.Load() != nil || f.U.Load() != 0 || f.S.Load() != "" { + t.Fatalf("Fieldwise = %v %v %q, want zero", f.V.Load(), f.U.Load(), f.S.Load()) + } +} +`, + }, "Fieldwise") + + for _, want := range []string{"r.V = atomic.Value{}", "r.U.Store(0)", "r.S = atomic2.String{}"} { + if !strings.Contains(srcs["Fieldwise"], want) { + t.Errorf("Fieldwise lacks %q:\n%s", want, srcs["Fieldwise"]) + } + } +} + +// TestSliceTailCleared: a slice of pointer-bearing elements is cleared up to +// its capacity, so the elements past its length do not keep memory alive; +// a slice of plain values is cleared up to its length only. +func TestSliceTailCleared(t *testing.T) { + t.Parallel() + + srcs := checkGenerated(t, "tail", map[string]string{ + "m.go": `package m + +import ( + "sync" + "unsafe" +) + +type Elem struct { + N int + Name string +} + +type Bulk struct { + P []*int + E []Elem + B []byte + + N0, N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, N11, N12, N13, N14, N15 uint8 +} + +type Fieldwise struct { + Mu sync.Mutex + P []*int + E []Elem + B []byte + D []struct{ W, H int } + Q [][2]uintptr + U [][1]unsafe.Pointer +} +`, + "m_test.go": `package m + +import "testing" + +func TestReset(t *testing.T) { + x := 1 + p := []*int{&x, &x} + e := []Elem{{1, "a"}, {2, "b"}} + + b := Bulk{P: p[:1], E: e[:1], B: []byte("ab")} + b.Reset() + + if p[0] != nil || p[1] != nil || e[1] != (Elem{}) || len(b.P) != 0 || cap(b.P) != 2 { + t.Fatalf("Bulk: %v %v, want the arrays cleared to their capacity", p, e) + } + + p, e = []*int{&x, &x}, []Elem{{1, "a"}, {2, "b"}} + + var f Fieldwise + f.P, f.E = p[:1], e[:1] + f.Reset() + + if p[0] != nil || p[1] != nil || e[1] != (Elem{}) || len(f.P) != 0 || cap(f.P) != 2 { + t.Fatalf("Fieldwise: %v %v, want the arrays cleared to their capacity", p, e) + } +} +`, + }, "Bulk", "Fieldwise") + + for typeName, src := range srcs { + if !strings.Contains(src, "clear(r.P[:cap(r.P)])") || !strings.Contains(src, "clear(r.B)\n") { + t.Errorf("%s: want P cleared to its capacity, B to its length:\n%s", typeName, src) + } + } + + for _, want := range []string{"clear(r.D)\n", "clear(r.Q)\n", "clear(r.U[:cap(r.U)])"} { + if !strings.Contains(srcs["Fieldwise"], want) { + t.Errorf("Fieldwise lacks %q:\n%s", want, srcs["Fieldwise"]) + } + } + + if !strings.Contains(srcs["Bulk"], "*r = Bulk{}") { + t.Errorf("Bulk is not reset in one assignment:\n%s", srcs["Bulk"]) + } +} + +// TestBlankAndUnsafe: blank fields (padding) cannot be referred to and are +// left out; an unsafe.Pointer is set to nil; a field type that names several +// packages imports all of them. +func TestBlankAndUnsafe(t *testing.T) { + t.Parallel() + + srcs := checkGenerated(t, "blank", map[string]string{ + "m.go": `package m + +import ( + "net/netip" + "sync" + "time" + "unsafe" +) + +type Pad struct{ n int } + +func (p *Pad) Reset() { p.n = 0 } + +type Bulk struct { + _ [8]byte ` + "`" + `reset:"-"` + "`" + ` + _ Pad + P unsafe.Pointer + N int +} + +type Fieldwise struct { + Mu sync.Mutex + _ [56]byte + _ Pad + P unsafe.Pointer + A [1]map[netip.Addr]time.Time +} +`, + "m_test.go": `package m + +import ( + "net/netip" + "testing" + "time" + "unsafe" +) + +func TestReset(t *testing.T) { + x := 1 + + b := Bulk{P: unsafe.Pointer(&x), N: 1} + b.Reset() + + if b.P != nil || b.N != 0 { + t.Fatalf("Bulk = %+v, want zero", b) + } + + var f Fieldwise + f.P = unsafe.Pointer(&x) + f.A[0] = map[netip.Addr]time.Time{} + f.Reset() + + if f.P != nil || f.A[0] != nil { + t.Fatal("Fieldwise: P and A are not zero") + } +} +`, + }, "Bulk", "Fieldwise") + + for typeName, src := range srcs { + if strings.Contains(src, "r._") { + t.Errorf("%s refers to a blank field:\n%s", typeName, src) + } + } + + if !strings.Contains(srcs["Bulk"], "*r = Bulk{}") { + t.Errorf("Bulk is not reset in one assignment:\n%s", srcs["Bulk"]) + } +}