]> Cypherpunks.ru repositories - gostls13.git/commitdiff
log/slog: fix Record.back slice always too small during Add()
authorChris Duncan <veqryn@hotmail.com>
Wed, 13 Sep 2023 22:26:19 +0000 (22:26 +0000)
committerJonathan Amsterdam <jba@google.com>
Thu, 14 Sep 2023 17:38:25 +0000 (17:38 +0000)
When slog.Record.Add(args) is called, with enough args to cause the
Record.back []Attr to be created, it is being created 1 too small, which
results in it immediately being grown again by append before the function
exits (needless allocation and copying).
This is because it is created with a capacity equal to countAttrs(args),
but forgets that there is an additional attribute to be appended: a
(args is just the remaining unconsumed attributes).
This PR fixes that by adding 1 to the capacity to account for the `a` attribute.

Additionally, when Record.back already exists, it will most likely be at
max capacity already. Rather than append to it and risk having it grown
multiple times, or grow too large, this adds a slices.Grow call to set it
to the right capacity, similar to what is already done in the
Record.AddAttrs(attrs) function.

Change-Id: Ic4bcf45909fe4436c586ccd2b8d61f24606b6be8
GitHub-Last-Rev: 4c924b610a7987a940360bb1b4cc7c53981afdc5
GitHub-Pull-Request: golang/go#62388
Reviewed-on: https://go-review.googlesource.com/c/go/+/524618
Reviewed-by: Jonathan Amsterdam <jba@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
src/log/slog/logger_test.go
src/log/slog/record.go

index 17bdff2ba5d15bfc6cc03decfce252dd083ad1bc..26e6f68f49c05e8a5694ee2b50ffb874ef0f9604 100644 (file)
@@ -276,7 +276,7 @@ func TestAlloc(t *testing.T) {
                s := "abc"
                i := 2000
                d := time.Second
-               wantAllocs(t, 11, func() {
+               wantAllocs(t, 10, func() {
                        dl.Info("hello",
                                "n", i, "s", s, "d", d,
                                "n", i, "s", s, "d", d,
index 82acc7ac7b1c026d3093cf2330f72ff7444495be..ea57c81c50ee342cc963d5d8959353d8b216d862 100644 (file)
@@ -138,12 +138,11 @@ func (r *Record) Add(args ...any) {
                        r.nFront++
                } else {
                        if r.back == nil {
-                               r.back = make([]Attr, 0, countAttrs(args))
+                               r.back = make([]Attr, 0, countAttrs(args)+1)
                        }
                        r.back = append(r.back, a)
                }
        }
-
 }
 
 // countAttrs returns the number of Attrs that would be created from args.