Skip to content

Commit 8be4adf

Browse files
jbaeric
authored andcommitted
src/log/slog: disallow == on Values
Comparing two Values with == is sensitive to the internal representation of Values, and may not correspond to equality on the Go values they represent. For example, StringValue("X") != StringValue(strings.ToUpper("x")) because Go ends up doing a pointer comparison on the data stored in the Values. So make Values non-comparable by adding a non-comparable field. Updates golang#56345. Change-Id: Ieedbf454e631cda10bc6fcf470b57d3f1d2182cc Reviewed-on: https://go-review.googlesource.com/c/go/+/479516 Run-TryBot: Jonathan Amsterdam <[email protected]> Reviewed-by: Alan Donovan <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent 0eb9e23 commit 8be4adf

File tree

3 files changed

+7
-2
lines changed

3 files changed

+7
-2
lines changed

src/log/slog/attr.go

+4
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,7 @@ func (a Attr) Equal(b Attr) bool {
8282
func (a Attr) String() string {
8383
return fmt.Sprintf("%s=%s", a.Key, a.Value)
8484
}
85+
86+
func (a Attr) isEmpty() bool {
87+
return a.Key == "" && a.Value.num == 0 && a.Value.any == nil
88+
}

src/log/slog/record.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ func (r *Record) AddAttrs(attrs ...Attr) {
106106
// and seeing if the Attr there is non-zero.
107107
if cap(r.back) > len(r.back) {
108108
end := r.back[:len(r.back)+1][len(r.back)]
109-
if end != (Attr{}) {
109+
if !end.isEmpty() {
110110
panic("copies of a slog.Record were both modified")
111111
}
112112
}

src/log/slog/value.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
// it can represent most small values without an allocation.
1818
// The zero Value corresponds to nil.
1919
type Value struct {
20+
_ [0]func() // disallow ==
2021
// num holds the value for Kinds Int64, Uint64, Float64, Bool and Duration,
2122
// the string length for KindString, and nanoseconds since the epoch for KindTime.
2223
num uint64
@@ -371,7 +372,7 @@ func (v Value) group() []Attr {
371372

372373
//////////////// Other
373374

374-
// Equal reports whether v and w have equal keys and values.
375+
// Equal reports whether v and w represent the same Go value.
375376
func (v Value) Equal(w Value) bool {
376377
k1 := v.Kind()
377378
k2 := w.Kind()

0 commit comments

Comments
 (0)