Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ func (r *Request) Reset() {
}
```

Everything is reset unless a tag says otherwise. Pooled state goes wrong in
the field nobody thought of: a flag like "skip the body" set for one request
and still set for the next one that takes the object from the pool. A
hand-written `Reset` lists what to clear and misses what it forgot; a
generated one lists only what to keep, so a new field is cleared from the
first `go generate` on.

## What it does per field

| Field | Reset |
Expand All @@ -60,6 +67,7 @@ Struct tags change the treatment of a field:
| `reset:"value=pkg.Const,import=example.com/pkg"` | the same with an import the expression needs |
| `reset:"call=Method"` | kept; `r.F.Method()` is called (`call=Stop` for a `*time.Timer`), when not nil if the field can be nil; a type parameter that is not only pointers cannot be checked for nil, so the method is called whatever the value |
| `reset:"release=Func"` | pointer with `Reset()`: `Func(r.F)` is called and the field set to nil |
| `reset:"maxcap=N"` | slice: kept and cleared as usual while `cap` is at most `N`, set to nil (the array let go, not cleared) above it; `N` is a constant integer expression of the package, e.g. `maxcap=64<<10` |

## Two modes

Expand All @@ -76,6 +84,7 @@ The mode is chosen per type by a cost model, in units of one field store:
| the struct | `memclr`: 1 per 16 bytes | — |
| plain field (number, pointer, string, atomic...) | 0 | 1 |
| slice | 3 (clear, keep, restore) | 2 (clear, reslice) |
| slice with `maxcap=` | 4 | 3 |
| value with `Reset()` | 2 + 2 per 16 bytes (copied out and back) | 1 (the call) |
| pointer with `Reset()`, `call=`, `reset:"-"` | 2 (keep, restore) | 1 |
| `value=` | 1 | 1 |
Expand Down Expand Up @@ -142,9 +151,11 @@ for tools that want the source without the file.

- It must run without concurrent users of the value: atomics are stored,
not swapped, and bulk mode copies the struct.
- Slices keep their capacity. A field that must not keep memory between uses
(a buffer that may grow very large once) should be tagged `reset:"-"` and
handled by hand, or released through `release=`.
- Slices keep their capacity. A buffer that may grow very large once should
be tagged `reset:"maxcap=N"`, so an array past `N` is let go instead of
kept for every later use; anything else that must not keep memory between
uses is tagged `reset:"-"` and handled by hand, or released through
`release=`.
- A nested value's `Reset()` is called after the bulk assignment, so it sees
its own state, not zeroes.
- A generic struct gets one `Reset` for all its instantiations
Expand Down
1 change: 1 addition & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// Timer *time.Timer `reset:"call=Stop"` // kept, method called
// Flags uint32 `reset:"value=^uint32(0)"` // set to EXPR, not zero
// Conn *Conn `reset:"release=PutConn"` // PutConn(r.Conn); r.Conn = nil
// Body []byte `reset:"maxcap=64<<10"` // array let go once cap > 64 KiB
//
// Fields of sync types are never touched, and a struct holding one is reset
// field by field, as is a struct whose kept fields (reset:"-", call=, values
Expand Down
63 changes: 59 additions & 4 deletions goreset.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package goreset
import (
"bytes"
"fmt"
"go/constant"
"go/format"
"go/token"
"go/types"
"path"
"reflect"
Expand All @@ -29,6 +31,7 @@ const (
costSlice = 2 // clear(r.F); r.F = r.F[:0]
costKeep = 2 // keepF := r.F ... r.F = keepF, around the bulk assignment
costSliceBK = 3 // clear(r.F); keepF := r.F[:0] ... r.F = keepF
costMaxCap = 1 // the cap(r.F) > N check of a maxcap= slice
)

// FileName is the file Generate's output is meant for: <type>_reset.gen.go, lower case.
Expand Down Expand Up @@ -146,6 +149,10 @@ func (p *Package) Analyze(typeName string) (Result, error) {

opts := parseTag(tag)

if tagErr := p.checkMaxCap(f, &opts); tagErr != nil {
return res, tagErr
}

if opts.importPath != "" {
imports = append(imports, opts.importPath)
tagImports = append(tagImports, opts.importPath)
Expand All @@ -171,7 +178,7 @@ func (p *Package) Analyze(typeName string) (Result, error) {
})

default:
fields = append(fields, p.resetCode(f, sized.Field(i).Type(), opts.release, &names))
fields = append(fields, p.resetCode(f, sized.Field(i).Type(), &opts, &names))
}
}

Expand Down Expand Up @@ -272,6 +279,7 @@ type tagOptions struct {
release string
call string
value string
maxcap string
}

func parseTag(tag string) tagOptions {
Expand All @@ -282,7 +290,8 @@ func parseTag(tag string) tagOptions {
case cut(part, "import=", &opts.importPath),
cut(part, "release=", &opts.release),
cut(part, "call=", &opts.call),
cut(part, "value=", &opts.value):
cut(part, "value=", &opts.value),
cut(part, "maxcap=", &opts.maxcap):
}
}

Expand All @@ -299,9 +308,40 @@ func cut(part, prefix string, dst *string) bool {
return ok
}

// checkMaxCap reports, when the tag has maxcap=, why `reset:"maxcap=N"` cannot apply to field f: it needs
// a slice reset the default way (no call=, value=, release=, no Reset method
// of its own), and N must be a constant non-negative integer the package can
// evaluate, like 4096, 64<<10 or a constant of the package.
func (p *Package) checkMaxCap(f *types.Var, opts *tagOptions) error {
if opts.maxcap == "" {
return nil
}

_, slice := f.Type().Underlying().(*types.Slice)
if !slice || hasResetMethod(f.Type()) || opts.call != "" || opts.value != "" || opts.release != "" {
return fmt.Errorf("goreset: field %s: maxcap= applies only to a slice without call=, value=, "+
"release= or a Reset method of its own", f.Name())
}

tv, err := types.Eval(token.NewFileSet(), p.pkg, token.NoPos, opts.maxcap)
if err != nil {
return fmt.Errorf("goreset: field %s: maxcap=%s: %w", f.Name(), opts.maxcap, err)
}

if tv.Value == nil || tv.Value.Kind() != constant.Int || constant.Sign(tv.Value) < 0 {
return fmt.Errorf("goreset: field %s: maxcap=%s is not a constant non-negative integer", f.Name(), opts.maxcap)
}

if _, exact := constant.Int64Val(tv.Value); !exact {
return fmt.Errorf("goreset: field %s: maxcap=%s overflows int64", f.Name(), opts.maxcap)
}

return nil
}

// resetCode is the code that resets field f; sized is f's type with any type
// parameters replaced, whose size the model can take.
func (p *Package) resetCode(f *types.Var, sized types.Type, release string, names *importNames) fieldInfo {
func (p *Package) resetCode(f *types.Var, sized types.Type, opts *tagOptions, names *importNames) fieldInfo {
var (
info fieldInfo
imports []string
Expand Down Expand Up @@ -369,7 +409,7 @@ func (p *Package) resetCode(f *types.Var, sized types.Type, release string, name
// call would panic on a nil value and keep a non-nil one.
if _, iface := f.Type().Underlying().(*types.Interface); (ptr || !iface) && hasResetMethod(f.Type()) {
if ptr {
if release != "" {
if release := opts.release; release != "" {
info.Code = fmt.Sprintf("if r.%s != nil { %s(r.%s); r.%s = nil }", info.Field, release, info.Field, info.Field)
info.Keep = fmt.Sprintf("if r.%s != nil { %s(r.%s) }", info.Field, release, info.Field)
info.Weight = costSlice // the call and the nil store
Expand Down Expand Up @@ -407,6 +447,21 @@ func (p *Package) resetCode(f *types.Var, sized types.Type, release string, name
cleared = fmt.Sprintf("r.%s[:cap(r.%s)]", info.Field, info.Field)
}

// maxcap=N: an array that grew past N is let go instead of kept, so
// one huge use does not pin its memory for every later one. It is
// not cleared: nothing here reads it again.
if opts.maxcap != "" {
info.Code = fmt.Sprintf("if cap(r.%s) > %s {\nr.%s = nil\n} else {\nclear(%s)\nr.%s = r.%s[:0]\n}",
info.Field, opts.maxcap, info.Field, cleared, info.Field, info.Field)
info.Keep = fmt.Sprintf("keep%s := r.%s[:0]\n\tif cap(keep%s) > %s {\nkeep%s = nil\n} else {\nclear(%s)\n}",
info.Field, info.Field, info.Field, opts.maxcap, info.Field, cleared)
info.Restore = fmt.Sprintf("r.%s = keep%s", info.Field, info.Field)
info.Weight = costSlice + costMaxCap
info.BulkExtra = costSliceBK + costMaxCap

return info
}

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)
Expand Down
135 changes: 135 additions & 0 deletions regression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -595,3 +595,138 @@ func TestGenericReceiverName(t *testing.T) {
t.Fatal("Generate(Box) succeeded with a type parameter named r, the receiver's name")
}
}

// TestMaxCap: a slice tagged maxcap=N keeps its array, cleared, while the
// capacity is at most N, and lets it go (nil, the array untouched) past N,
// in both modes. N may be a constant expression of the package.
func TestMaxCap(t *testing.T) {
t.Parallel()

srcs := checkGenerated(t, "maxcap", map[string]string{
"m.go": `package m

import "sync"

const limit = 4

type Bulk struct {
B []byte ` + "`" + `reset:"maxcap=limit"` + "`" + `
P []*int ` + "`" + `reset:"maxcap=1<<2"` + "`" + `
N int

N0, N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, N11, N12, N13, N14, N15 uint8
}

type Fieldwise struct {
Mu sync.Mutex
B []byte ` + "`" + `reset:"maxcap=limit"` + "`" + `
P []*int ` + "`" + `reset:"maxcap=4"` + "`" + `
}
`,
"m_test.go": `package m

import "testing"

func TestReset(t *testing.T) {
x := 1
small := []*int{&x, &x, &x, &x}
big := []*int{&x, &x, &x, &x, &x}
sb, bb := []byte("abcd"), []byte("abcde")

b := Bulk{B: sb[:2], P: small[:1], N: 1}
b.Reset()

if len(b.B) != 0 || cap(b.B) != 4 || sb[0] != 0 || len(b.P) != 0 || cap(b.P) != 4 || small[3] != nil || b.N != 0 {
t.Fatalf("Bulk under the limit: %+v %v %v, want the arrays kept and cleared", b, sb, small)
}

b = Bulk{B: bb[:1], P: big[:1]}
b.Reset()

if b.B != nil || b.P != nil || bb[0] != 'a' || big[0] == nil {
t.Fatalf("Bulk over the limit: %+v %v %v, want nil slices and the arrays untouched", b, bb, big)
}

small = []*int{&x, &x, &x, &x}
sb = []byte("abcd")

var f Fieldwise
f.B, f.P = sb[:2], small[:1]
f.Reset()

if len(f.B) != 0 || cap(f.B) != 4 || sb[0] != 0 || len(f.P) != 0 || cap(f.P) != 4 || small[3] != nil {
t.Fatalf("Fieldwise under the limit: %v %v, want the arrays kept and cleared", sb, small)
}

f.B, f.P = bb, big
f.Reset()

if f.B != nil || f.P != nil || bb[0] != 'a' || big[0] == nil {
t.Fatalf("Fieldwise over the limit: %v %v, want nil slices and the arrays untouched", bb, big)
}

var z Fieldwise
z.Reset()
z.B = append(z.B, 1)
}
`,
}, "Bulk", "Fieldwise")

if !strings.Contains(srcs["Bulk"], "*r = Bulk{}") {
t.Errorf("Bulk is not reset in one assignment:\n%s", srcs["Bulk"])
}

for typeName, src := range srcs {
if !strings.Contains(src, "> limit {") || !strings.Contains(src, "clear(r.P[:cap(r.P)])") {
t.Errorf("%s: want the limit as written and P cleared to its capacity:\n%s", typeName, src)
}
}
}

// TestMaxCapErrors: maxcap= is refused on anything but a plain slice and
// for a limit that is not a constant non-negative integer.
func TestMaxCapErrors(t *testing.T) {
t.Parallel()

dir := writeModule(t, "maxcaperr", map[string]string{
"m.go": `package m

type S []int

func (*S) Reset() {}

type T struct{ X int }

` + strings.Join([]string{
"type NotSlice struct{ M map[int]int `reset:\"maxcap=4\"` }",
"type OwnReset struct{ Buf S `reset:\"maxcap=4\"` }",
"type WithValue struct{ B []byte `reset:\"maxcap=4,value=nil\"` }",
"type Negative struct{ B []byte `reset:\"maxcap=-1\"` }",
"type NotInt struct{ B []byte `reset:\"maxcap=1.5\"` }",
"type Unknown struct{ B []byte `reset:\"maxcap=nope\"` }",
"type Variable struct{ B []byte `reset:\"maxcap=v\"` }",
"type Huge struct{ B []byte `reset:\"maxcap=1<<70\"` }",
"var v = 4",
}, "\n") + "\n",
})

pkg, err := goreset.Load(dir)
if err != nil {
t.Fatal(err)
}

for typeName, want := range map[string]string{
"NotSlice": "applies only to a slice",
"OwnReset": "applies only to a slice",
"WithValue": "applies only to a slice",
"Negative": "not a constant non-negative integer",
"NotInt": "not a constant non-negative integer",
"Unknown": "undefined",
"Variable": "not a constant non-negative integer",
"Huge": "overflows int64",
} {
if _, err := pkg.Generate(typeName); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Generate(%s) error = %v, want %q", typeName, err, want)
}
}
}
Loading