]> Cypherpunks repositories - gostls13.git/commitdiff
reflect: add flag tests for MapOf
authorMichael Pratt <mpratt@google.com>
Mon, 24 Jun 2024 21:17:13 +0000 (17:17 -0400)
committerGopher Robot <gobot@golang.org>
Wed, 31 Jul 2024 20:45:55 +0000 (20:45 +0000)
Add two tests that verify that MapOf sets the map NeedsKeyUpdate and
HashMightPanic flags in the created map. Missing these flags would cause
correctness issues not otherwise caught in the reflect tests.

For #54766.

Change-Id: Icd5f117e0794e7b4d1b70fa94e5afbe97c4543e3
Reviewed-on: https://go-review.googlesource.com/c/go/+/594656
Reviewed-by: Keith Randall <khr@golang.org>
Auto-Submit: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
src/reflect/all_test.go

index a57f17f8c30f122006070f230199514ee5b82493..277c703eddeaf7d6095c27f1d309c6cac8944606 100644 (file)
@@ -8603,3 +8603,48 @@ func TestSliceAt(t *testing.T) {
        // _ = SliceAt(typ, unsafe.Pointer(last), 1)
        shouldPanic("", func() { _ = SliceAt(typ, unsafe.Pointer(last), 2) })
 }
+
+// Test that maps created with MapOf properly updates keys on overwrite as
+// expected (i.e., it sets the key update flag in the map).
+//
+// This test is based on runtime.TestNegativeZero.
+func TestMapOfKeyUpdate(t *testing.T) {
+       m := MakeMap(MapOf(TypeFor[float64](), TypeFor[bool]()))
+
+       zero := float64(0.0)
+       negZero := math.Copysign(zero, -1.0)
+
+       m.SetMapIndex(ValueOf(zero), ValueOf(true))
+       m.SetMapIndex(ValueOf(negZero), ValueOf(true))
+
+       if m.Len() != 1 {
+               t.Errorf("map length got %d want 1", m.Len())
+       }
+
+       iter := m.MapRange()
+       for iter.Next() {
+               k := iter.Key().Float()
+               if math.Copysign(1.0, k) > 0 {
+                       t.Errorf("map key %f has positive sign", k)
+               }
+       }
+}
+
+// Test that maps created with MapOf properly panic on unhashable keys, even if
+// the map is empty. (i.e., it sets the hash might panic flag in the map).
+//
+// This test is a simplified version of runtime.TestEmptyMapWithInterfaceKey
+// for reflect.
+func TestMapOfKeyPanic(t *testing.T) {
+       defer func() {
+               r := recover()
+               if r == nil {
+                       t.Errorf("didn't panic")
+               }
+       }()
+
+       m := MakeMap(MapOf(TypeFor[any](), TypeFor[bool]()))
+
+       var slice []int
+       m.MapIndex(ValueOf(slice))
+}