From: Michael Pratt Date: Mon, 24 Jun 2024 21:17:13 +0000 (-0400) Subject: reflect: add flag tests for MapOf X-Git-Tag: go1.24rc1~1317 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=7dac9898c3d34378de8f523a77a01bcc86033562;p=gostls13.git reflect: add flag tests for MapOf 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 Auto-Submit: Michael Pratt LUCI-TryBot-Result: Go LUCI Reviewed-by: Cherry Mui --- diff --git a/src/reflect/all_test.go b/src/reflect/all_test.go index a57f17f8c3..277c703edd 100644 --- a/src/reflect/all_test.go +++ b/src/reflect/all_test.go @@ -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)) +}