From 65798b669e276c22c23f1aa1ac13bb9af5a176fb Mon Sep 17 00:00:00 2001 From: Klaus Post Date: Tue, 22 Oct 2024 04:19:28 -0700 Subject: [PATCH] Fix allownil propagated to byte slices as slice elements (#374) `[][]byte` would assume that the byte slices had allownil set. This would cause an extra `if x == nil {x = make([]byte,0)}` to be inserted on elements. Regression from #363 --- _generated/omitempty.go | 8 +++++--- gen/spec.go | 8 ++++++++ msgp/write_bytes_test.go | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/_generated/omitempty.go b/_generated/omitempty.go index c0a938e8..5dc8da11 100644 --- a/_generated/omitempty.go +++ b/_generated/omitempty.go @@ -29,9 +29,11 @@ type OmitEmpty0 struct { APtrNamedStr *NamedString `msg:"aptrnamedstr,omitempty"` - AString string `msg:"astring,omitempty"` - ANamedString string `msg:"anamedstring,omitempty"` - AByteSlice []byte `msg:"abyteslice,omitempty"` + AString string `msg:"astring,omitempty"` + ANamedString string `msg:"anamedstring,omitempty"` + AByteSlice []byte `msg:"abyteslice,omitempty"` + ASliceByteSlice [][]byte `msg:"aslicebyteslice,omitempty"` + AMapByteSlice map[string][]byte `msg:"amapbyteslice,omitempty"` ASliceString []string `msg:"aslicestring,omitempty"` ASliceNamedString []NamedString `msg:"aslicenamedstring,omitempty"` diff --git a/gen/spec.go b/gen/spec.go index 18cbec39..93f632d3 100644 --- a/gen/spec.go +++ b/gen/spec.go @@ -385,6 +385,14 @@ func (p *printer) closeblock() { p.print("\n}") } // } func (p *printer) rangeBlock(ctx *Context, idx string, iter string, t traversal, inner Elem) { ctx.PushVar(idx) + // Tags on slices do not extend to the elements, so we always disable allownil on elements. + // If we want this to happen in the future, it should be a unique tag. + type an interface { + SetIsAllowNil(b bool) + } + if set, ok := inner.(an); ok { + set.SetIsAllowNil(false) + } p.printf("\n for %s := range %s {", idx, iter) next(t, inner) p.closeblock() diff --git a/msgp/write_bytes_test.go b/msgp/write_bytes_test.go index e2763279..68f2eb3e 100644 --- a/msgp/write_bytes_test.go +++ b/msgp/write_bytes_test.go @@ -199,7 +199,7 @@ func BenchmarkAppendFloat(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - AppendFloat64(buf, src[i&(n-1)]) + AppendFloat(buf, src[i&(n-1)]) } }