Source file src/reflect/all_test.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package reflect_test
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/base64"
    10  	"flag"
    11  	"fmt"
    12  	"go/token"
    13  	"internal/goarch"
    14  	"internal/testenv"
    15  	"io"
    16  	"math"
    17  	"math/rand"
    18  	"os"
    19  	. "reflect"
    20  	"reflect/internal/example1"
    21  	"reflect/internal/example2"
    22  	"runtime"
    23  	"sort"
    24  	"strconv"
    25  	"strings"
    26  	"sync"
    27  	"sync/atomic"
    28  	"testing"
    29  	"time"
    30  	"unsafe"
    31  )
    32  
    33  var sink any
    34  
    35  func TestBool(t *testing.T) {
    36  	v := ValueOf(true)
    37  	if v.Bool() != true {
    38  		t.Fatal("ValueOf(true).Bool() = false")
    39  	}
    40  }
    41  
    42  type integer int
    43  type T struct {
    44  	a int
    45  	b float64
    46  	c string
    47  	d *int
    48  }
    49  
    50  type pair struct {
    51  	i any
    52  	s string
    53  }
    54  
    55  func assert(t *testing.T, s, want string) {
    56  	if s != want {
    57  		t.Errorf("have %#q want %#q", s, want)
    58  	}
    59  }
    60  
    61  var typeTests = []pair{
    62  	{struct{ x int }{}, "int"},
    63  	{struct{ x int8 }{}, "int8"},
    64  	{struct{ x int16 }{}, "int16"},
    65  	{struct{ x int32 }{}, "int32"},
    66  	{struct{ x int64 }{}, "int64"},
    67  	{struct{ x uint }{}, "uint"},
    68  	{struct{ x uint8 }{}, "uint8"},
    69  	{struct{ x uint16 }{}, "uint16"},
    70  	{struct{ x uint32 }{}, "uint32"},
    71  	{struct{ x uint64 }{}, "uint64"},
    72  	{struct{ x float32 }{}, "float32"},
    73  	{struct{ x float64 }{}, "float64"},
    74  	{struct{ x int8 }{}, "int8"},
    75  	{struct{ x (**int8) }{}, "**int8"},
    76  	{struct{ x (**integer) }{}, "**reflect_test.integer"},
    77  	{struct{ x ([32]int32) }{}, "[32]int32"},
    78  	{struct{ x ([]int8) }{}, "[]int8"},
    79  	{struct{ x (map[string]int32) }{}, "map[string]int32"},
    80  	{struct{ x (chan<- string) }{}, "chan<- string"},
    81  	{struct{ x (chan<- chan string) }{}, "chan<- chan string"},
    82  	{struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
    83  	{struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
    84  	{struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
    85  	{struct {
    86  		x struct {
    87  			c chan *int32
    88  			d float32
    89  		}
    90  	}{},
    91  		"struct { c chan *int32; d float32 }",
    92  	},
    93  	{struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
    94  	{struct {
    95  		x struct {
    96  			c func(chan *integer, *int8)
    97  		}
    98  	}{},
    99  		"struct { c func(chan *reflect_test.integer, *int8) }",
   100  	},
   101  	{struct {
   102  		x struct {
   103  			a int8
   104  			b int32
   105  		}
   106  	}{},
   107  		"struct { a int8; b int32 }",
   108  	},
   109  	{struct {
   110  		x struct {
   111  			a int8
   112  			b int8
   113  			c int32
   114  		}
   115  	}{},
   116  		"struct { a int8; b int8; c int32 }",
   117  	},
   118  	{struct {
   119  		x struct {
   120  			a int8
   121  			b int8
   122  			c int8
   123  			d int32
   124  		}
   125  	}{},
   126  		"struct { a int8; b int8; c int8; d int32 }",
   127  	},
   128  	{struct {
   129  		x struct {
   130  			a int8
   131  			b int8
   132  			c int8
   133  			d int8
   134  			e int32
   135  		}
   136  	}{},
   137  		"struct { a int8; b int8; c int8; d int8; e int32 }",
   138  	},
   139  	{struct {
   140  		x struct {
   141  			a int8
   142  			b int8
   143  			c int8
   144  			d int8
   145  			e int8
   146  			f int32
   147  		}
   148  	}{},
   149  		"struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
   150  	},
   151  	{struct {
   152  		x struct {
   153  			a int8 `reflect:"hi there"`
   154  		}
   155  	}{},
   156  		`struct { a int8 "reflect:\"hi there\"" }`,
   157  	},
   158  	{struct {
   159  		x struct {
   160  			a int8 `reflect:"hi \x00there\t\n\"\\"`
   161  		}
   162  	}{},
   163  		`struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
   164  	},
   165  	{struct {
   166  		x struct {
   167  			f func(args ...int)
   168  		}
   169  	}{},
   170  		"struct { f func(...int) }",
   171  	},
   172  	{struct {
   173  		x (interface {
   174  			a(func(func(int) int) func(func(int)) int)
   175  			b()
   176  		})
   177  	}{},
   178  		"interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
   179  	},
   180  	{struct {
   181  		x struct {
   182  			int32
   183  			int64
   184  		}
   185  	}{},
   186  		"struct { int32; int64 }",
   187  	},
   188  }
   189  
   190  var valueTests = []pair{
   191  	{new(int), "132"},
   192  	{new(int8), "8"},
   193  	{new(int16), "16"},
   194  	{new(int32), "32"},
   195  	{new(int64), "64"},
   196  	{new(uint), "132"},
   197  	{new(uint8), "8"},
   198  	{new(uint16), "16"},
   199  	{new(uint32), "32"},
   200  	{new(uint64), "64"},
   201  	{new(float32), "256.25"},
   202  	{new(float64), "512.125"},
   203  	{new(complex64), "532.125+10i"},
   204  	{new(complex128), "564.25+1i"},
   205  	{new(string), "stringy cheese"},
   206  	{new(bool), "true"},
   207  	{new(*int8), "*int8(0)"},
   208  	{new(**int8), "**int8(0)"},
   209  	{new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
   210  	{new(**integer), "**reflect_test.integer(0)"},
   211  	{new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
   212  	{new(chan<- string), "chan<- string"},
   213  	{new(func(a int8, b int32)), "func(int8, int32)(0)"},
   214  	{new(struct {
   215  		c chan *int32
   216  		d float32
   217  	}),
   218  		"struct { c chan *int32; d float32 }{chan *int32, 0}",
   219  	},
   220  	{new(struct{ c func(chan *integer, *int8) }),
   221  		"struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
   222  	},
   223  	{new(struct {
   224  		a int8
   225  		b int32
   226  	}),
   227  		"struct { a int8; b int32 }{0, 0}",
   228  	},
   229  	{new(struct {
   230  		a int8
   231  		b int8
   232  		c int32
   233  	}),
   234  		"struct { a int8; b int8; c int32 }{0, 0, 0}",
   235  	},
   236  }
   237  
   238  func testType(t *testing.T, i int, typ Type, want string) {
   239  	s := typ.String()
   240  	if s != want {
   241  		t.Errorf("#%d: have %#q, want %#q", i, s, want)
   242  	}
   243  }
   244  
   245  func TestTypes(t *testing.T) {
   246  	for i, tt := range typeTests {
   247  		testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
   248  	}
   249  }
   250  
   251  func TestSet(t *testing.T) {
   252  	for i, tt := range valueTests {
   253  		v := ValueOf(tt.i)
   254  		v = v.Elem()
   255  		switch v.Kind() {
   256  		case Int:
   257  			v.SetInt(132)
   258  		case Int8:
   259  			v.SetInt(8)
   260  		case Int16:
   261  			v.SetInt(16)
   262  		case Int32:
   263  			v.SetInt(32)
   264  		case Int64:
   265  			v.SetInt(64)
   266  		case Uint:
   267  			v.SetUint(132)
   268  		case Uint8:
   269  			v.SetUint(8)
   270  		case Uint16:
   271  			v.SetUint(16)
   272  		case Uint32:
   273  			v.SetUint(32)
   274  		case Uint64:
   275  			v.SetUint(64)
   276  		case Float32:
   277  			v.SetFloat(256.25)
   278  		case Float64:
   279  			v.SetFloat(512.125)
   280  		case Complex64:
   281  			v.SetComplex(532.125 + 10i)
   282  		case Complex128:
   283  			v.SetComplex(564.25 + 1i)
   284  		case String:
   285  			v.SetString("stringy cheese")
   286  		case Bool:
   287  			v.SetBool(true)
   288  		}
   289  		s := valueToString(v)
   290  		if s != tt.s {
   291  			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
   292  		}
   293  	}
   294  }
   295  
   296  func TestSetValue(t *testing.T) {
   297  	for i, tt := range valueTests {
   298  		v := ValueOf(tt.i).Elem()
   299  		switch v.Kind() {
   300  		case Int:
   301  			v.Set(ValueOf(int(132)))
   302  		case Int8:
   303  			v.Set(ValueOf(int8(8)))
   304  		case Int16:
   305  			v.Set(ValueOf(int16(16)))
   306  		case Int32:
   307  			v.Set(ValueOf(int32(32)))
   308  		case Int64:
   309  			v.Set(ValueOf(int64(64)))
   310  		case Uint:
   311  			v.Set(ValueOf(uint(132)))
   312  		case Uint8:
   313  			v.Set(ValueOf(uint8(8)))
   314  		case Uint16:
   315  			v.Set(ValueOf(uint16(16)))
   316  		case Uint32:
   317  			v.Set(ValueOf(uint32(32)))
   318  		case Uint64:
   319  			v.Set(ValueOf(uint64(64)))
   320  		case Float32:
   321  			v.Set(ValueOf(float32(256.25)))
   322  		case Float64:
   323  			v.Set(ValueOf(512.125))
   324  		case Complex64:
   325  			v.Set(ValueOf(complex64(532.125 + 10i)))
   326  		case Complex128:
   327  			v.Set(ValueOf(complex128(564.25 + 1i)))
   328  		case String:
   329  			v.Set(ValueOf("stringy cheese"))
   330  		case Bool:
   331  			v.Set(ValueOf(true))
   332  		}
   333  		s := valueToString(v)
   334  		if s != tt.s {
   335  			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
   336  		}
   337  	}
   338  }
   339  
   340  func TestMapIterSet(t *testing.T) {
   341  	m := make(map[string]any, len(valueTests))
   342  	for _, tt := range valueTests {
   343  		m[tt.s] = tt.i
   344  	}
   345  	v := ValueOf(m)
   346  
   347  	k := New(v.Type().Key()).Elem()
   348  	e := New(v.Type().Elem()).Elem()
   349  
   350  	iter := v.MapRange()
   351  	for iter.Next() {
   352  		k.SetIterKey(iter)
   353  		e.SetIterValue(iter)
   354  		want := m[k.String()]
   355  		got := e.Interface()
   356  		if got != want {
   357  			t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
   358  		}
   359  		if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
   360  			t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
   361  		}
   362  		if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
   363  			t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
   364  		}
   365  	}
   366  
   367  	if strings.HasSuffix(testenv.Builder(), "-noopt") {
   368  		return // no inlining with the noopt builder
   369  	}
   370  
   371  	got := int(testing.AllocsPerRun(10, func() {
   372  		iter := v.MapRange()
   373  		for iter.Next() {
   374  			k.SetIterKey(iter)
   375  			e.SetIterValue(iter)
   376  		}
   377  	}))
   378  	// Calling MapRange should not allocate even though it returns a *MapIter.
   379  	// The function is inlineable, so if the local usage does not escape
   380  	// the *MapIter, it can remain stack allocated.
   381  	want := 0
   382  	if got != want {
   383  		t.Errorf("wanted %d alloc, got %d", want, got)
   384  	}
   385  }
   386  
   387  func TestCanIntUintFloatComplex(t *testing.T) {
   388  	type integer int
   389  	type uinteger uint
   390  	type float float64
   391  	type complex complex128
   392  
   393  	var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
   394  
   395  	var testCases = []struct {
   396  		i    any
   397  		want [4]bool
   398  	}{
   399  		// signed integer
   400  		{132, [...]bool{true, false, false, false}},
   401  		{int8(8), [...]bool{true, false, false, false}},
   402  		{int16(16), [...]bool{true, false, false, false}},
   403  		{int32(32), [...]bool{true, false, false, false}},
   404  		{int64(64), [...]bool{true, false, false, false}},
   405  		// unsigned integer
   406  		{uint(132), [...]bool{false, true, false, false}},
   407  		{uint8(8), [...]bool{false, true, false, false}},
   408  		{uint16(16), [...]bool{false, true, false, false}},
   409  		{uint32(32), [...]bool{false, true, false, false}},
   410  		{uint64(64), [...]bool{false, true, false, false}},
   411  		{uintptr(0xABCD), [...]bool{false, true, false, false}},
   412  		// floating-point
   413  		{float32(256.25), [...]bool{false, false, true, false}},
   414  		{float64(512.125), [...]bool{false, false, true, false}},
   415  		// complex
   416  		{complex64(532.125 + 10i), [...]bool{false, false, false, true}},
   417  		{complex128(564.25 + 1i), [...]bool{false, false, false, true}},
   418  		// underlying
   419  		{integer(-132), [...]bool{true, false, false, false}},
   420  		{uinteger(132), [...]bool{false, true, false, false}},
   421  		{float(256.25), [...]bool{false, false, true, false}},
   422  		{complex(532.125 + 10i), [...]bool{false, false, false, true}},
   423  		// not-acceptable
   424  		{"hello world", [...]bool{false, false, false, false}},
   425  		{new(int), [...]bool{false, false, false, false}},
   426  		{new(uint), [...]bool{false, false, false, false}},
   427  		{new(float64), [...]bool{false, false, false, false}},
   428  		{new(complex64), [...]bool{false, false, false, false}},
   429  		{new([5]int), [...]bool{false, false, false, false}},
   430  		{new(integer), [...]bool{false, false, false, false}},
   431  		{new(map[int]int), [...]bool{false, false, false, false}},
   432  		{new(chan<- int), [...]bool{false, false, false, false}},
   433  		{new(func(a int8)), [...]bool{false, false, false, false}},
   434  		{new(struct{ i int }), [...]bool{false, false, false, false}},
   435  	}
   436  
   437  	for i, tc := range testCases {
   438  		v := ValueOf(tc.i)
   439  		got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
   440  
   441  		for j := range tc.want {
   442  			if got[j] != tc.want[j] {
   443  				t.Errorf(
   444  					"#%d: v.%s() returned %t for type %T, want %t",
   445  					i,
   446  					ops[j],
   447  					got[j],
   448  					tc.i,
   449  					tc.want[j],
   450  				)
   451  			}
   452  		}
   453  	}
   454  }
   455  
   456  func TestCanSetField(t *testing.T) {
   457  	type embed struct{ x, X int }
   458  	type Embed struct{ x, X int }
   459  	type S1 struct {
   460  		embed
   461  		x, X int
   462  	}
   463  	type S2 struct {
   464  		*embed
   465  		x, X int
   466  	}
   467  	type S3 struct {
   468  		Embed
   469  		x, X int
   470  	}
   471  	type S4 struct {
   472  		*Embed
   473  		x, X int
   474  	}
   475  
   476  	type testCase struct {
   477  		// -1 means Addr().Elem() of current value
   478  		index  []int
   479  		canSet bool
   480  	}
   481  	tests := []struct {
   482  		val   Value
   483  		cases []testCase
   484  	}{{
   485  		val: ValueOf(&S1{}),
   486  		cases: []testCase{
   487  			{[]int{0}, false},
   488  			{[]int{0, -1}, false},
   489  			{[]int{0, 0}, false},
   490  			{[]int{0, 0, -1}, false},
   491  			{[]int{0, -1, 0}, false},
   492  			{[]int{0, -1, 0, -1}, false},
   493  			{[]int{0, 1}, true},
   494  			{[]int{0, 1, -1}, true},
   495  			{[]int{0, -1, 1}, true},
   496  			{[]int{0, -1, 1, -1}, true},
   497  			{[]int{1}, false},
   498  			{[]int{1, -1}, false},
   499  			{[]int{2}, true},
   500  			{[]int{2, -1}, true},
   501  		},
   502  	}, {
   503  		val: ValueOf(&S2{embed: &embed{}}),
   504  		cases: []testCase{
   505  			{[]int{0}, false},
   506  			{[]int{0, -1}, false},
   507  			{[]int{0, 0}, false},
   508  			{[]int{0, 0, -1}, false},
   509  			{[]int{0, -1, 0}, false},
   510  			{[]int{0, -1, 0, -1}, false},
   511  			{[]int{0, 1}, true},
   512  			{[]int{0, 1, -1}, true},
   513  			{[]int{0, -1, 1}, true},
   514  			{[]int{0, -1, 1, -1}, true},
   515  			{[]int{1}, false},
   516  			{[]int{2}, true},
   517  		},
   518  	}, {
   519  		val: ValueOf(&S3{}),
   520  		cases: []testCase{
   521  			{[]int{0}, true},
   522  			{[]int{0, -1}, true},
   523  			{[]int{0, 0}, false},
   524  			{[]int{0, 0, -1}, false},
   525  			{[]int{0, -1, 0}, false},
   526  			{[]int{0, -1, 0, -1}, false},
   527  			{[]int{0, 1}, true},
   528  			{[]int{0, 1, -1}, true},
   529  			{[]int{0, -1, 1}, true},
   530  			{[]int{0, -1, 1, -1}, true},
   531  			{[]int{1}, false},
   532  			{[]int{2}, true},
   533  		},
   534  	}, {
   535  		val: ValueOf(&S4{Embed: &Embed{}}),
   536  		cases: []testCase{
   537  			{[]int{0}, true},
   538  			{[]int{0, -1}, true},
   539  			{[]int{0, 0}, false},
   540  			{[]int{0, 0, -1}, false},
   541  			{[]int{0, -1, 0}, false},
   542  			{[]int{0, -1, 0, -1}, false},
   543  			{[]int{0, 1}, true},
   544  			{[]int{0, 1, -1}, true},
   545  			{[]int{0, -1, 1}, true},
   546  			{[]int{0, -1, 1, -1}, true},
   547  			{[]int{1}, false},
   548  			{[]int{2}, true},
   549  		},
   550  	}}
   551  
   552  	for _, tt := range tests {
   553  		t.Run(tt.val.Type().Name(), func(t *testing.T) {
   554  			for _, tc := range tt.cases {
   555  				f := tt.val
   556  				for _, i := range tc.index {
   557  					if f.Kind() == Pointer {
   558  						f = f.Elem()
   559  					}
   560  					if i == -1 {
   561  						f = f.Addr().Elem()
   562  					} else {
   563  						f = f.Field(i)
   564  					}
   565  				}
   566  				if got := f.CanSet(); got != tc.canSet {
   567  					t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
   568  				}
   569  			}
   570  		})
   571  	}
   572  }
   573  
   574  var _i = 7
   575  
   576  var valueToStringTests = []pair{
   577  	{123, "123"},
   578  	{123.5, "123.5"},
   579  	{byte(123), "123"},
   580  	{"abc", "abc"},
   581  	{T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
   582  	{new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
   583  	{[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
   584  	{&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
   585  	{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
   586  	{&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
   587  }
   588  
   589  func TestValueToString(t *testing.T) {
   590  	for i, test := range valueToStringTests {
   591  		s := valueToString(ValueOf(test.i))
   592  		if s != test.s {
   593  			t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
   594  		}
   595  	}
   596  }
   597  
   598  func TestArrayElemSet(t *testing.T) {
   599  	v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
   600  	v.Index(4).SetInt(123)
   601  	s := valueToString(v)
   602  	const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
   603  	if s != want {
   604  		t.Errorf("[10]int: have %#q want %#q", s, want)
   605  	}
   606  
   607  	v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
   608  	v.Index(4).SetInt(123)
   609  	s = valueToString(v)
   610  	const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
   611  	if s != want1 {
   612  		t.Errorf("[]int: have %#q want %#q", s, want1)
   613  	}
   614  }
   615  
   616  func TestPtrPointTo(t *testing.T) {
   617  	var ip *int32
   618  	var i int32 = 1234
   619  	vip := ValueOf(&ip)
   620  	vi := ValueOf(&i).Elem()
   621  	vip.Elem().Set(vi.Addr())
   622  	if *ip != 1234 {
   623  		t.Errorf("got %d, want 1234", *ip)
   624  	}
   625  
   626  	ip = nil
   627  	vp := ValueOf(&ip).Elem()
   628  	vp.Set(Zero(vp.Type()))
   629  	if ip != nil {
   630  		t.Errorf("got non-nil (%p), want nil", ip)
   631  	}
   632  }
   633  
   634  func TestPtrSetNil(t *testing.T) {
   635  	var i int32 = 1234
   636  	ip := &i
   637  	vip := ValueOf(&ip)
   638  	vip.Elem().Set(Zero(vip.Elem().Type()))
   639  	if ip != nil {
   640  		t.Errorf("got non-nil (%d), want nil", *ip)
   641  	}
   642  }
   643  
   644  func TestMapSetNil(t *testing.T) {
   645  	m := make(map[string]int)
   646  	vm := ValueOf(&m)
   647  	vm.Elem().Set(Zero(vm.Elem().Type()))
   648  	if m != nil {
   649  		t.Errorf("got non-nil (%p), want nil", m)
   650  	}
   651  }
   652  
   653  func TestAll(t *testing.T) {
   654  	testType(t, 1, TypeOf((int8)(0)), "int8")
   655  	testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
   656  
   657  	typ := TypeOf((*struct {
   658  		c chan *int32
   659  		d float32
   660  	})(nil))
   661  	testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
   662  	etyp := typ.Elem()
   663  	testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
   664  	styp := etyp
   665  	f := styp.Field(0)
   666  	testType(t, 5, f.Type, "chan *int32")
   667  
   668  	f, present := styp.FieldByName("d")
   669  	if !present {
   670  		t.Errorf("FieldByName says present field is absent")
   671  	}
   672  	testType(t, 6, f.Type, "float32")
   673  
   674  	f, present = styp.FieldByName("absent")
   675  	if present {
   676  		t.Errorf("FieldByName says absent field is present")
   677  	}
   678  
   679  	typ = TypeOf([32]int32{})
   680  	testType(t, 7, typ, "[32]int32")
   681  	testType(t, 8, typ.Elem(), "int32")
   682  
   683  	typ = TypeOf((map[string]*int32)(nil))
   684  	testType(t, 9, typ, "map[string]*int32")
   685  	mtyp := typ
   686  	testType(t, 10, mtyp.Key(), "string")
   687  	testType(t, 11, mtyp.Elem(), "*int32")
   688  
   689  	typ = TypeOf((chan<- string)(nil))
   690  	testType(t, 12, typ, "chan<- string")
   691  	testType(t, 13, typ.Elem(), "string")
   692  
   693  	// make sure tag strings are not part of element type
   694  	typ = TypeOf(struct {
   695  		d []uint32 `reflect:"TAG"`
   696  	}{}).Field(0).Type
   697  	testType(t, 14, typ, "[]uint32")
   698  }
   699  
   700  func TestInterfaceGet(t *testing.T) {
   701  	var inter struct {
   702  		E any
   703  	}
   704  	inter.E = 123.456
   705  	v1 := ValueOf(&inter)
   706  	v2 := v1.Elem().Field(0)
   707  	assert(t, v2.Type().String(), "interface {}")
   708  	i2 := v2.Interface()
   709  	v3 := ValueOf(i2)
   710  	assert(t, v3.Type().String(), "float64")
   711  }
   712  
   713  func TestInterfaceValue(t *testing.T) {
   714  	var inter struct {
   715  		E any
   716  	}
   717  	inter.E = 123.456
   718  	v1 := ValueOf(&inter)
   719  	v2 := v1.Elem().Field(0)
   720  	assert(t, v2.Type().String(), "interface {}")
   721  	v3 := v2.Elem()
   722  	assert(t, v3.Type().String(), "float64")
   723  
   724  	i3 := v2.Interface()
   725  	if _, ok := i3.(float64); !ok {
   726  		t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
   727  	}
   728  }
   729  
   730  func TestFunctionValue(t *testing.T) {
   731  	var x any = func() {}
   732  	v := ValueOf(x)
   733  	if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
   734  		t.Fatalf("TestFunction returned wrong pointer")
   735  	}
   736  	assert(t, v.Type().String(), "func()")
   737  }
   738  
   739  var appendTests = []struct {
   740  	orig, extra []int
   741  }{
   742  	{make([]int, 2, 4), []int{22}},
   743  	{make([]int, 2, 4), []int{22, 33, 44}},
   744  }
   745  
   746  func sameInts(x, y []int) bool {
   747  	if len(x) != len(y) {
   748  		return false
   749  	}
   750  	for i, xx := range x {
   751  		if xx != y[i] {
   752  			return false
   753  		}
   754  	}
   755  	return true
   756  }
   757  
   758  func TestAppend(t *testing.T) {
   759  	for i, test := range appendTests {
   760  		origLen, extraLen := len(test.orig), len(test.extra)
   761  		want := append(test.orig, test.extra...)
   762  		// Convert extra from []int to []Value.
   763  		e0 := make([]Value, len(test.extra))
   764  		for j, e := range test.extra {
   765  			e0[j] = ValueOf(e)
   766  		}
   767  		// Convert extra from []int to *SliceValue.
   768  		e1 := ValueOf(test.extra)
   769  		// Test Append.
   770  		a0 := ValueOf(test.orig)
   771  		have0 := Append(a0, e0...).Interface().([]int)
   772  		if !sameInts(have0, want) {
   773  			t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
   774  		}
   775  		// Check that the orig and extra slices were not modified.
   776  		if len(test.orig) != origLen {
   777  			t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
   778  		}
   779  		if len(test.extra) != extraLen {
   780  			t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
   781  		}
   782  		// Test AppendSlice.
   783  		a1 := ValueOf(test.orig)
   784  		have1 := AppendSlice(a1, e1).Interface().([]int)
   785  		if !sameInts(have1, want) {
   786  			t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
   787  		}
   788  		// Check that the orig and extra slices were not modified.
   789  		if len(test.orig) != origLen {
   790  			t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
   791  		}
   792  		if len(test.extra) != extraLen {
   793  			t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
   794  		}
   795  	}
   796  }
   797  
   798  func TestCopy(t *testing.T) {
   799  	a := []int{1, 2, 3, 4, 10, 9, 8, 7}
   800  	b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   801  	c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   802  	for i := 0; i < len(b); i++ {
   803  		if b[i] != c[i] {
   804  			t.Fatalf("b != c before test")
   805  		}
   806  	}
   807  	a1 := a
   808  	b1 := b
   809  	aa := ValueOf(&a1).Elem()
   810  	ab := ValueOf(&b1).Elem()
   811  	for tocopy := 1; tocopy <= 7; tocopy++ {
   812  		aa.SetLen(tocopy)
   813  		Copy(ab, aa)
   814  		aa.SetLen(8)
   815  		for i := 0; i < tocopy; i++ {
   816  			if a[i] != b[i] {
   817  				t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
   818  					tocopy, i, a[i], i, b[i])
   819  			}
   820  		}
   821  		for i := tocopy; i < len(b); i++ {
   822  			if b[i] != c[i] {
   823  				if i < len(a) {
   824  					t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
   825  						tocopy, i, a[i], i, b[i], i, c[i])
   826  				} else {
   827  					t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
   828  						tocopy, i, b[i], i, c[i])
   829  				}
   830  			} else {
   831  				t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
   832  			}
   833  		}
   834  	}
   835  }
   836  
   837  func TestCopyString(t *testing.T) {
   838  	t.Run("Slice", func(t *testing.T) {
   839  		s := bytes.Repeat([]byte{'_'}, 8)
   840  		val := ValueOf(s)
   841  
   842  		n := Copy(val, ValueOf(""))
   843  		if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
   844  			t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
   845  		}
   846  
   847  		n = Copy(val, ValueOf("hello"))
   848  		if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
   849  			t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
   850  		}
   851  
   852  		n = Copy(val, ValueOf("helloworld"))
   853  		if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
   854  			t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
   855  		}
   856  	})
   857  	t.Run("Array", func(t *testing.T) {
   858  		s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
   859  		val := ValueOf(&s).Elem()
   860  
   861  		n := Copy(val, ValueOf(""))
   862  		if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
   863  			t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
   864  		}
   865  
   866  		n = Copy(val, ValueOf("hello"))
   867  		if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
   868  			t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
   869  		}
   870  
   871  		n = Copy(val, ValueOf("helloworld"))
   872  		if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
   873  			t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
   874  		}
   875  	})
   876  }
   877  
   878  func TestCopyArray(t *testing.T) {
   879  	a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
   880  	b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   881  	c := b
   882  	aa := ValueOf(&a).Elem()
   883  	ab := ValueOf(&b).Elem()
   884  	Copy(ab, aa)
   885  	for i := 0; i < len(a); i++ {
   886  		if a[i] != b[i] {
   887  			t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
   888  		}
   889  	}
   890  	for i := len(a); i < len(b); i++ {
   891  		if b[i] != c[i] {
   892  			t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
   893  		} else {
   894  			t.Logf("elem %d is okay\n", i)
   895  		}
   896  	}
   897  }
   898  
   899  func TestBigUnnamedStruct(t *testing.T) {
   900  	b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
   901  	v := ValueOf(b)
   902  	b1 := v.Interface().(struct {
   903  		a, b, c, d int64
   904  	})
   905  	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
   906  		t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
   907  	}
   908  }
   909  
   910  type big struct {
   911  	a, b, c, d, e int64
   912  }
   913  
   914  func TestBigStruct(t *testing.T) {
   915  	b := big{1, 2, 3, 4, 5}
   916  	v := ValueOf(b)
   917  	b1 := v.Interface().(big)
   918  	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
   919  		t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
   920  	}
   921  }
   922  
   923  type Basic struct {
   924  	x int
   925  	y float32
   926  }
   927  
   928  type NotBasic Basic
   929  
   930  type DeepEqualTest struct {
   931  	a, b any
   932  	eq   bool
   933  }
   934  
   935  // Simple functions for DeepEqual tests.
   936  var (
   937  	fn1 func()             // nil.
   938  	fn2 func()             // nil.
   939  	fn3 = func() { fn1() } // Not nil.
   940  )
   941  
   942  type self struct{}
   943  
   944  type Loop *Loop
   945  type Loopy any
   946  
   947  var loop1, loop2 Loop
   948  var loopy1, loopy2 Loopy
   949  var cycleMap1, cycleMap2, cycleMap3 map[string]any
   950  
   951  type structWithSelfPtr struct {
   952  	p *structWithSelfPtr
   953  	s string
   954  }
   955  
   956  func init() {
   957  	loop1 = &loop2
   958  	loop2 = &loop1
   959  
   960  	loopy1 = &loopy2
   961  	loopy2 = &loopy1
   962  
   963  	cycleMap1 = map[string]any{}
   964  	cycleMap1["cycle"] = cycleMap1
   965  	cycleMap2 = map[string]any{}
   966  	cycleMap2["cycle"] = cycleMap2
   967  	cycleMap3 = map[string]any{}
   968  	cycleMap3["different"] = cycleMap3
   969  }
   970  
   971  var deepEqualTests = []DeepEqualTest{
   972  	// Equalities
   973  	{nil, nil, true},
   974  	{1, 1, true},
   975  	{int32(1), int32(1), true},
   976  	{0.5, 0.5, true},
   977  	{float32(0.5), float32(0.5), true},
   978  	{"hello", "hello", true},
   979  	{make([]int, 10), make([]int, 10), true},
   980  	{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
   981  	{Basic{1, 0.5}, Basic{1, 0.5}, true},
   982  	{error(nil), error(nil), true},
   983  	{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
   984  	{fn1, fn2, true},
   985  	{[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
   986  	{[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
   987  	{MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
   988  
   989  	// Inequalities
   990  	{1, 2, false},
   991  	{int32(1), int32(2), false},
   992  	{0.5, 0.6, false},
   993  	{float32(0.5), float32(0.6), false},
   994  	{"hello", "hey", false},
   995  	{make([]int, 10), make([]int, 11), false},
   996  	{&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
   997  	{Basic{1, 0.5}, Basic{1, 0.6}, false},
   998  	{Basic{1, 0}, Basic{2, 0}, false},
   999  	{map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
  1000  	{map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
  1001  	{map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
  1002  	{map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
  1003  	{nil, 1, false},
  1004  	{1, nil, false},
  1005  	{fn1, fn3, false},
  1006  	{fn3, fn3, false},
  1007  	{[][]int{{1}}, [][]int{{2}}, false},
  1008  	{&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
  1009  
  1010  	// Fun with floating point.
  1011  	{math.NaN(), math.NaN(), false},
  1012  	{&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
  1013  	{&[1]float64{math.NaN()}, self{}, true},
  1014  	{[]float64{math.NaN()}, []float64{math.NaN()}, false},
  1015  	{[]float64{math.NaN()}, self{}, true},
  1016  	{map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
  1017  	{map[float64]float64{math.NaN(): 1}, self{}, true},
  1018  
  1019  	// Nil vs empty: not the same.
  1020  	{[]int{}, []int(nil), false},
  1021  	{[]int{}, []int{}, true},
  1022  	{[]int(nil), []int(nil), true},
  1023  	{map[int]int{}, map[int]int(nil), false},
  1024  	{map[int]int{}, map[int]int{}, true},
  1025  	{map[int]int(nil), map[int]int(nil), true},
  1026  
  1027  	// Mismatched types
  1028  	{1, 1.0, false},
  1029  	{int32(1), int64(1), false},
  1030  	{0.5, "hello", false},
  1031  	{[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
  1032  	{&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
  1033  	{Basic{1, 0.5}, NotBasic{1, 0.5}, false},
  1034  	{map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
  1035  	{[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
  1036  	{[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
  1037  	{[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
  1038  
  1039  	// Possible loops.
  1040  	{&loop1, &loop1, true},
  1041  	{&loop1, &loop2, true},
  1042  	{&loopy1, &loopy1, true},
  1043  	{&loopy1, &loopy2, true},
  1044  	{&cycleMap1, &cycleMap2, true},
  1045  	{&cycleMap1, &cycleMap3, false},
  1046  }
  1047  
  1048  func TestDeepEqual(t *testing.T) {
  1049  	for _, test := range deepEqualTests {
  1050  		if test.b == (self{}) {
  1051  			test.b = test.a
  1052  		}
  1053  		if r := DeepEqual(test.a, test.b); r != test.eq {
  1054  			t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
  1055  		}
  1056  	}
  1057  }
  1058  
  1059  func TestTypeOf(t *testing.T) {
  1060  	// Special case for nil
  1061  	if typ := TypeOf(nil); typ != nil {
  1062  		t.Errorf("expected nil type for nil value; got %v", typ)
  1063  	}
  1064  	for _, test := range deepEqualTests {
  1065  		v := ValueOf(test.a)
  1066  		if !v.IsValid() {
  1067  			continue
  1068  		}
  1069  		typ := TypeOf(test.a)
  1070  		if typ != v.Type() {
  1071  			t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
  1072  		}
  1073  	}
  1074  }
  1075  
  1076  type Recursive struct {
  1077  	x int
  1078  	r *Recursive
  1079  }
  1080  
  1081  func TestDeepEqualRecursiveStruct(t *testing.T) {
  1082  	a, b := new(Recursive), new(Recursive)
  1083  	*a = Recursive{12, a}
  1084  	*b = Recursive{12, b}
  1085  	if !DeepEqual(a, b) {
  1086  		t.Error("DeepEqual(recursive same) = false, want true")
  1087  	}
  1088  }
  1089  
  1090  type _Complex struct {
  1091  	a int
  1092  	b [3]*_Complex
  1093  	c *string
  1094  	d map[float64]float64
  1095  }
  1096  
  1097  func TestDeepEqualComplexStruct(t *testing.T) {
  1098  	m := make(map[float64]float64)
  1099  	stra, strb := "hello", "hello"
  1100  	a, b := new(_Complex), new(_Complex)
  1101  	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
  1102  	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
  1103  	if !DeepEqual(a, b) {
  1104  		t.Error("DeepEqual(complex same) = false, want true")
  1105  	}
  1106  }
  1107  
  1108  func TestDeepEqualComplexStructInequality(t *testing.T) {
  1109  	m := make(map[float64]float64)
  1110  	stra, strb := "hello", "helloo" // Difference is here
  1111  	a, b := new(_Complex), new(_Complex)
  1112  	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
  1113  	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
  1114  	if DeepEqual(a, b) {
  1115  		t.Error("DeepEqual(complex different) = true, want false")
  1116  	}
  1117  }
  1118  
  1119  type UnexpT struct {
  1120  	m map[int]int
  1121  }
  1122  
  1123  func TestDeepEqualUnexportedMap(t *testing.T) {
  1124  	// Check that DeepEqual can look at unexported fields.
  1125  	x1 := UnexpT{map[int]int{1: 2}}
  1126  	x2 := UnexpT{map[int]int{1: 2}}
  1127  	if !DeepEqual(&x1, &x2) {
  1128  		t.Error("DeepEqual(x1, x2) = false, want true")
  1129  	}
  1130  
  1131  	y1 := UnexpT{map[int]int{2: 3}}
  1132  	if DeepEqual(&x1, &y1) {
  1133  		t.Error("DeepEqual(x1, y1) = true, want false")
  1134  	}
  1135  }
  1136  
  1137  var deepEqualPerfTests = []struct {
  1138  	x, y any
  1139  }{
  1140  	{x: int8(99), y: int8(99)},
  1141  	{x: []int8{99}, y: []int8{99}},
  1142  	{x: int16(99), y: int16(99)},
  1143  	{x: []int16{99}, y: []int16{99}},
  1144  	{x: int32(99), y: int32(99)},
  1145  	{x: []int32{99}, y: []int32{99}},
  1146  	{x: int64(99), y: int64(99)},
  1147  	{x: []int64{99}, y: []int64{99}},
  1148  	{x: int(999999), y: int(999999)},
  1149  	{x: []int{999999}, y: []int{999999}},
  1150  
  1151  	{x: uint8(99), y: uint8(99)},
  1152  	{x: []uint8{99}, y: []uint8{99}},
  1153  	{x: uint16(99), y: uint16(99)},
  1154  	{x: []uint16{99}, y: []uint16{99}},
  1155  	{x: uint32(99), y: uint32(99)},
  1156  	{x: []uint32{99}, y: []uint32{99}},
  1157  	{x: uint64(99), y: uint64(99)},
  1158  	{x: []uint64{99}, y: []uint64{99}},
  1159  	{x: uint(999999), y: uint(999999)},
  1160  	{x: []uint{999999}, y: []uint{999999}},
  1161  	{x: uintptr(999999), y: uintptr(999999)},
  1162  	{x: []uintptr{999999}, y: []uintptr{999999}},
  1163  
  1164  	{x: float32(1.414), y: float32(1.414)},
  1165  	{x: []float32{1.414}, y: []float32{1.414}},
  1166  	{x: float64(1.414), y: float64(1.414)},
  1167  	{x: []float64{1.414}, y: []float64{1.414}},
  1168  
  1169  	{x: complex64(1.414), y: complex64(1.414)},
  1170  	{x: []complex64{1.414}, y: []complex64{1.414}},
  1171  	{x: complex128(1.414), y: complex128(1.414)},
  1172  	{x: []complex128{1.414}, y: []complex128{1.414}},
  1173  
  1174  	{x: true, y: true},
  1175  	{x: []bool{true}, y: []bool{true}},
  1176  
  1177  	{x: "abcdef", y: "abcdef"},
  1178  	{x: []string{"abcdef"}, y: []string{"abcdef"}},
  1179  
  1180  	{x: []byte("abcdef"), y: []byte("abcdef")},
  1181  	{x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
  1182  
  1183  	{x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
  1184  	{x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
  1185  }
  1186  
  1187  func TestDeepEqualAllocs(t *testing.T) {
  1188  	for _, tt := range deepEqualPerfTests {
  1189  		t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
  1190  			got := testing.AllocsPerRun(100, func() {
  1191  				if !DeepEqual(tt.x, tt.y) {
  1192  					t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
  1193  				}
  1194  			})
  1195  			if int(got) != 0 {
  1196  				t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
  1197  			}
  1198  		})
  1199  	}
  1200  }
  1201  
  1202  func BenchmarkDeepEqual(b *testing.B) {
  1203  	for _, bb := range deepEqualPerfTests {
  1204  		b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
  1205  			b.ReportAllocs()
  1206  			for i := 0; i < b.N; i++ {
  1207  				sink = DeepEqual(bb.x, bb.y)
  1208  			}
  1209  		})
  1210  	}
  1211  }
  1212  
  1213  func check2ndField(x any, offs uintptr, t *testing.T) {
  1214  	s := ValueOf(x)
  1215  	f := s.Type().Field(1)
  1216  	if f.Offset != offs {
  1217  		t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
  1218  	}
  1219  }
  1220  
  1221  // Check that structure alignment & offsets viewed through reflect agree with those
  1222  // from the compiler itself.
  1223  func TestAlignment(t *testing.T) {
  1224  	type T1inner struct {
  1225  		a int
  1226  	}
  1227  	type T1 struct {
  1228  		T1inner
  1229  		f int
  1230  	}
  1231  	type T2inner struct {
  1232  		a, b int
  1233  	}
  1234  	type T2 struct {
  1235  		T2inner
  1236  		f int
  1237  	}
  1238  
  1239  	x := T1{T1inner{2}, 17}
  1240  	check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
  1241  
  1242  	x1 := T2{T2inner{2, 3}, 17}
  1243  	check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
  1244  }
  1245  
  1246  func Nil(a any, t *testing.T) {
  1247  	n := ValueOf(a).Field(0)
  1248  	if !n.IsNil() {
  1249  		t.Errorf("%v should be nil", a)
  1250  	}
  1251  }
  1252  
  1253  func NotNil(a any, t *testing.T) {
  1254  	n := ValueOf(a).Field(0)
  1255  	if n.IsNil() {
  1256  		t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
  1257  	}
  1258  }
  1259  
  1260  func TestIsNil(t *testing.T) {
  1261  	// These implement IsNil.
  1262  	// Wrap in extra struct to hide interface type.
  1263  	doNil := []any{
  1264  		struct{ x *int }{},
  1265  		struct{ x any }{},
  1266  		struct{ x map[string]int }{},
  1267  		struct{ x func() bool }{},
  1268  		struct{ x chan int }{},
  1269  		struct{ x []string }{},
  1270  		struct{ x unsafe.Pointer }{},
  1271  	}
  1272  	for _, ts := range doNil {
  1273  		ty := TypeOf(ts).Field(0).Type
  1274  		v := Zero(ty)
  1275  		v.IsNil() // panics if not okay to call
  1276  	}
  1277  
  1278  	// Check the implementations
  1279  	var pi struct {
  1280  		x *int
  1281  	}
  1282  	Nil(pi, t)
  1283  	pi.x = new(int)
  1284  	NotNil(pi, t)
  1285  
  1286  	var si struct {
  1287  		x []int
  1288  	}
  1289  	Nil(si, t)
  1290  	si.x = make([]int, 10)
  1291  	NotNil(si, t)
  1292  
  1293  	var ci struct {
  1294  		x chan int
  1295  	}
  1296  	Nil(ci, t)
  1297  	ci.x = make(chan int)
  1298  	NotNil(ci, t)
  1299  
  1300  	var mi struct {
  1301  		x map[int]int
  1302  	}
  1303  	Nil(mi, t)
  1304  	mi.x = make(map[int]int)
  1305  	NotNil(mi, t)
  1306  
  1307  	var ii struct {
  1308  		x any
  1309  	}
  1310  	Nil(ii, t)
  1311  	ii.x = 2
  1312  	NotNil(ii, t)
  1313  
  1314  	var fi struct {
  1315  		x func(t *testing.T)
  1316  	}
  1317  	Nil(fi, t)
  1318  	fi.x = TestIsNil
  1319  	NotNil(fi, t)
  1320  }
  1321  
  1322  func TestIsZero(t *testing.T) {
  1323  	for i, tt := range []struct {
  1324  		x    any
  1325  		want bool
  1326  	}{
  1327  		// Booleans
  1328  		{true, false},
  1329  		{false, true},
  1330  		// Numeric types
  1331  		{int(0), true},
  1332  		{int(1), false},
  1333  		{int8(0), true},
  1334  		{int8(1), false},
  1335  		{int16(0), true},
  1336  		{int16(1), false},
  1337  		{int32(0), true},
  1338  		{int32(1), false},
  1339  		{int64(0), true},
  1340  		{int64(1), false},
  1341  		{uint(0), true},
  1342  		{uint(1), false},
  1343  		{uint8(0), true},
  1344  		{uint8(1), false},
  1345  		{uint16(0), true},
  1346  		{uint16(1), false},
  1347  		{uint32(0), true},
  1348  		{uint32(1), false},
  1349  		{uint64(0), true},
  1350  		{uint64(1), false},
  1351  		{float32(0), true},
  1352  		{float32(1.2), false},
  1353  		{float64(0), true},
  1354  		{float64(1.2), false},
  1355  		{math.Copysign(0, -1), false},
  1356  		{complex64(0), true},
  1357  		{complex64(1.2), false},
  1358  		{complex128(0), true},
  1359  		{complex128(1.2), false},
  1360  		{complex(math.Copysign(0, -1), 0), false},
  1361  		{complex(0, math.Copysign(0, -1)), false},
  1362  		{complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
  1363  		{uintptr(0), true},
  1364  		{uintptr(128), false},
  1365  		// Array
  1366  		{Zero(TypeOf([5]string{})).Interface(), true},
  1367  		{[5]string{"", "", "", "", ""}, true},
  1368  		{[5]string{}, true},
  1369  		{[5]string{"", "", "", "a", ""}, false},
  1370  		// Chan
  1371  		{(chan string)(nil), true},
  1372  		{make(chan string), false},
  1373  		{time.After(1), false},
  1374  		// Func
  1375  		{(func())(nil), true},
  1376  		{New, false},
  1377  		// Interface
  1378  		{New(TypeOf(new(error)).Elem()).Elem(), true},
  1379  		{(io.Reader)(strings.NewReader("")), false},
  1380  		// Map
  1381  		{(map[string]string)(nil), true},
  1382  		{map[string]string{}, false},
  1383  		{make(map[string]string), false},
  1384  		// Pointer
  1385  		{(*func())(nil), true},
  1386  		{(*int)(nil), true},
  1387  		{new(int), false},
  1388  		// Slice
  1389  		{[]string{}, false},
  1390  		{([]string)(nil), true},
  1391  		{make([]string, 0), false},
  1392  		// Strings
  1393  		{"", true},
  1394  		{"not-zero", false},
  1395  		// Structs
  1396  		{T{}, true},
  1397  		{T{123, 456.75, "hello", &_i}, false},
  1398  		// UnsafePointer
  1399  		{(unsafe.Pointer)(nil), true},
  1400  		{(unsafe.Pointer)(new(int)), false},
  1401  	} {
  1402  		var x Value
  1403  		if v, ok := tt.x.(Value); ok {
  1404  			x = v
  1405  		} else {
  1406  			x = ValueOf(tt.x)
  1407  		}
  1408  
  1409  		b := x.IsZero()
  1410  		if b != tt.want {
  1411  			t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
  1412  		}
  1413  
  1414  		if !Zero(TypeOf(tt.x)).IsZero() {
  1415  			t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
  1416  		}
  1417  	}
  1418  
  1419  	func() {
  1420  		defer func() {
  1421  			if r := recover(); r == nil {
  1422  				t.Error("should panic for invalid value")
  1423  			}
  1424  		}()
  1425  		(Value{}).IsZero()
  1426  	}()
  1427  }
  1428  
  1429  func TestInterfaceExtraction(t *testing.T) {
  1430  	var s struct {
  1431  		W io.Writer
  1432  	}
  1433  
  1434  	s.W = os.Stdout
  1435  	v := Indirect(ValueOf(&s)).Field(0).Interface()
  1436  	if v != s.W.(any) {
  1437  		t.Error("Interface() on interface: ", v, s.W)
  1438  	}
  1439  }
  1440  
  1441  func TestNilPtrValueSub(t *testing.T) {
  1442  	var pi *int
  1443  	if pv := ValueOf(pi); pv.Elem().IsValid() {
  1444  		t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
  1445  	}
  1446  }
  1447  
  1448  func TestMap(t *testing.T) {
  1449  	m := map[string]int{"a": 1, "b": 2}
  1450  	mv := ValueOf(m)
  1451  	if n := mv.Len(); n != len(m) {
  1452  		t.Errorf("Len = %d, want %d", n, len(m))
  1453  	}
  1454  	keys := mv.MapKeys()
  1455  	newmap := MakeMap(mv.Type())
  1456  	for k, v := range m {
  1457  		// Check that returned Keys match keys in range.
  1458  		// These aren't required to be in the same order.
  1459  		seen := false
  1460  		for _, kv := range keys {
  1461  			if kv.String() == k {
  1462  				seen = true
  1463  				break
  1464  			}
  1465  		}
  1466  		if !seen {
  1467  			t.Errorf("Missing key %q", k)
  1468  		}
  1469  
  1470  		// Check that value lookup is correct.
  1471  		vv := mv.MapIndex(ValueOf(k))
  1472  		if vi := vv.Int(); vi != int64(v) {
  1473  			t.Errorf("Key %q: have value %d, want %d", k, vi, v)
  1474  		}
  1475  
  1476  		// Copy into new map.
  1477  		newmap.SetMapIndex(ValueOf(k), ValueOf(v))
  1478  	}
  1479  	vv := mv.MapIndex(ValueOf("not-present"))
  1480  	if vv.IsValid() {
  1481  		t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
  1482  	}
  1483  
  1484  	newm := newmap.Interface().(map[string]int)
  1485  	if len(newm) != len(m) {
  1486  		t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
  1487  	}
  1488  
  1489  	for k, v := range newm {
  1490  		mv, ok := m[k]
  1491  		if mv != v {
  1492  			t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
  1493  		}
  1494  	}
  1495  
  1496  	newmap.SetMapIndex(ValueOf("a"), Value{})
  1497  	v, ok := newm["a"]
  1498  	if ok {
  1499  		t.Errorf("newm[\"a\"] = %d after delete", v)
  1500  	}
  1501  
  1502  	mv = ValueOf(&m).Elem()
  1503  	mv.Set(Zero(mv.Type()))
  1504  	if m != nil {
  1505  		t.Errorf("mv.Set(nil) failed")
  1506  	}
  1507  
  1508  	type S string
  1509  	shouldPanic("not assignable", func() { mv.MapIndex(ValueOf(S("key"))) })
  1510  	shouldPanic("not assignable", func() { mv.SetMapIndex(ValueOf(S("key")), ValueOf(0)) })
  1511  }
  1512  
  1513  func TestNilMap(t *testing.T) {
  1514  	var m map[string]int
  1515  	mv := ValueOf(m)
  1516  	keys := mv.MapKeys()
  1517  	if len(keys) != 0 {
  1518  		t.Errorf(">0 keys for nil map: %v", keys)
  1519  	}
  1520  
  1521  	// Check that value for missing key is zero.
  1522  	x := mv.MapIndex(ValueOf("hello"))
  1523  	if x.Kind() != Invalid {
  1524  		t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
  1525  	}
  1526  
  1527  	// Check big value too.
  1528  	var mbig map[string][10 << 20]byte
  1529  	x = ValueOf(mbig).MapIndex(ValueOf("hello"))
  1530  	if x.Kind() != Invalid {
  1531  		t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
  1532  	}
  1533  
  1534  	// Test that deletes from a nil map succeed.
  1535  	mv.SetMapIndex(ValueOf("hi"), Value{})
  1536  }
  1537  
  1538  func TestChan(t *testing.T) {
  1539  	for loop := 0; loop < 2; loop++ {
  1540  		var c chan int
  1541  		var cv Value
  1542  
  1543  		// check both ways to allocate channels
  1544  		switch loop {
  1545  		case 1:
  1546  			c = make(chan int, 1)
  1547  			cv = ValueOf(c)
  1548  		case 0:
  1549  			cv = MakeChan(TypeOf(c), 1)
  1550  			c = cv.Interface().(chan int)
  1551  		}
  1552  
  1553  		// Send
  1554  		cv.Send(ValueOf(2))
  1555  		if i := <-c; i != 2 {
  1556  			t.Errorf("reflect Send 2, native recv %d", i)
  1557  		}
  1558  
  1559  		// Recv
  1560  		c <- 3
  1561  		if i, ok := cv.Recv(); i.Int() != 3 || !ok {
  1562  			t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
  1563  		}
  1564  
  1565  		// TryRecv fail
  1566  		val, ok := cv.TryRecv()
  1567  		if val.IsValid() || ok {
  1568  			t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
  1569  		}
  1570  
  1571  		// TryRecv success
  1572  		c <- 4
  1573  		val, ok = cv.TryRecv()
  1574  		if !val.IsValid() {
  1575  			t.Errorf("TryRecv on ready chan got nil")
  1576  		} else if i := val.Int(); i != 4 || !ok {
  1577  			t.Errorf("native send 4, TryRecv %d, %t", i, ok)
  1578  		}
  1579  
  1580  		// TrySend fail
  1581  		c <- 100
  1582  		ok = cv.TrySend(ValueOf(5))
  1583  		i := <-c
  1584  		if ok {
  1585  			t.Errorf("TrySend on full chan succeeded: value %d", i)
  1586  		}
  1587  
  1588  		// TrySend success
  1589  		ok = cv.TrySend(ValueOf(6))
  1590  		if !ok {
  1591  			t.Errorf("TrySend on empty chan failed")
  1592  			select {
  1593  			case x := <-c:
  1594  				t.Errorf("TrySend failed but it did send %d", x)
  1595  			default:
  1596  			}
  1597  		} else {
  1598  			if i = <-c; i != 6 {
  1599  				t.Errorf("TrySend 6, recv %d", i)
  1600  			}
  1601  		}
  1602  
  1603  		// Close
  1604  		c <- 123
  1605  		cv.Close()
  1606  		if i, ok := cv.Recv(); i.Int() != 123 || !ok {
  1607  			t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
  1608  		}
  1609  		if i, ok := cv.Recv(); i.Int() != 0 || ok {
  1610  			t.Errorf("after close Recv %d, %t", i.Int(), ok)
  1611  		}
  1612  	}
  1613  
  1614  	// check creation of unbuffered channel
  1615  	var c chan int
  1616  	cv := MakeChan(TypeOf(c), 0)
  1617  	c = cv.Interface().(chan int)
  1618  	if cv.TrySend(ValueOf(7)) {
  1619  		t.Errorf("TrySend on sync chan succeeded")
  1620  	}
  1621  	if v, ok := cv.TryRecv(); v.IsValid() || ok {
  1622  		t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
  1623  	}
  1624  
  1625  	// len/cap
  1626  	cv = MakeChan(TypeOf(c), 10)
  1627  	c = cv.Interface().(chan int)
  1628  	for i := 0; i < 3; i++ {
  1629  		c <- i
  1630  	}
  1631  	if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
  1632  		t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
  1633  	}
  1634  }
  1635  
  1636  // caseInfo describes a single case in a select test.
  1637  type caseInfo struct {
  1638  	desc      string
  1639  	canSelect bool
  1640  	recv      Value
  1641  	closed    bool
  1642  	helper    func()
  1643  	panic     bool
  1644  }
  1645  
  1646  var allselect = flag.Bool("allselect", false, "exhaustive select test")
  1647  
  1648  func TestSelect(t *testing.T) {
  1649  	selectWatch.once.Do(func() { go selectWatcher() })
  1650  
  1651  	var x exhaustive
  1652  	nch := 0
  1653  	newop := func(n int, cap int) (ch, val Value) {
  1654  		nch++
  1655  		if nch%101%2 == 1 {
  1656  			c := make(chan int, cap)
  1657  			ch = ValueOf(c)
  1658  			val = ValueOf(n)
  1659  		} else {
  1660  			c := make(chan string, cap)
  1661  			ch = ValueOf(c)
  1662  			val = ValueOf(fmt.Sprint(n))
  1663  		}
  1664  		return
  1665  	}
  1666  
  1667  	for n := 0; x.Next(); n++ {
  1668  		if testing.Short() && n >= 1000 {
  1669  			break
  1670  		}
  1671  		if n >= 100000 && !*allselect {
  1672  			break
  1673  		}
  1674  		if n%100000 == 0 && testing.Verbose() {
  1675  			println("TestSelect", n)
  1676  		}
  1677  		var cases []SelectCase
  1678  		var info []caseInfo
  1679  
  1680  		// Ready send.
  1681  		if x.Maybe() {
  1682  			ch, val := newop(len(cases), 1)
  1683  			cases = append(cases, SelectCase{
  1684  				Dir:  SelectSend,
  1685  				Chan: ch,
  1686  				Send: val,
  1687  			})
  1688  			info = append(info, caseInfo{desc: "ready send", canSelect: true})
  1689  		}
  1690  
  1691  		// Ready recv.
  1692  		if x.Maybe() {
  1693  			ch, val := newop(len(cases), 1)
  1694  			ch.Send(val)
  1695  			cases = append(cases, SelectCase{
  1696  				Dir:  SelectRecv,
  1697  				Chan: ch,
  1698  			})
  1699  			info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
  1700  		}
  1701  
  1702  		// Blocking send.
  1703  		if x.Maybe() {
  1704  			ch, val := newop(len(cases), 0)
  1705  			cases = append(cases, SelectCase{
  1706  				Dir:  SelectSend,
  1707  				Chan: ch,
  1708  				Send: val,
  1709  			})
  1710  			// Let it execute?
  1711  			if x.Maybe() {
  1712  				f := func() { ch.Recv() }
  1713  				info = append(info, caseInfo{desc: "blocking send", helper: f})
  1714  			} else {
  1715  				info = append(info, caseInfo{desc: "blocking send"})
  1716  			}
  1717  		}
  1718  
  1719  		// Blocking recv.
  1720  		if x.Maybe() {
  1721  			ch, val := newop(len(cases), 0)
  1722  			cases = append(cases, SelectCase{
  1723  				Dir:  SelectRecv,
  1724  				Chan: ch,
  1725  			})
  1726  			// Let it execute?
  1727  			if x.Maybe() {
  1728  				f := func() { ch.Send(val) }
  1729  				info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
  1730  			} else {
  1731  				info = append(info, caseInfo{desc: "blocking recv"})
  1732  			}
  1733  		}
  1734  
  1735  		// Zero Chan send.
  1736  		if x.Maybe() {
  1737  			// Maybe include value to send.
  1738  			var val Value
  1739  			if x.Maybe() {
  1740  				val = ValueOf(100)
  1741  			}
  1742  			cases = append(cases, SelectCase{
  1743  				Dir:  SelectSend,
  1744  				Send: val,
  1745  			})
  1746  			info = append(info, caseInfo{desc: "zero Chan send"})
  1747  		}
  1748  
  1749  		// Zero Chan receive.
  1750  		if x.Maybe() {
  1751  			cases = append(cases, SelectCase{
  1752  				Dir: SelectRecv,
  1753  			})
  1754  			info = append(info, caseInfo{desc: "zero Chan recv"})
  1755  		}
  1756  
  1757  		// nil Chan send.
  1758  		if x.Maybe() {
  1759  			cases = append(cases, SelectCase{
  1760  				Dir:  SelectSend,
  1761  				Chan: ValueOf((chan int)(nil)),
  1762  				Send: ValueOf(101),
  1763  			})
  1764  			info = append(info, caseInfo{desc: "nil Chan send"})
  1765  		}
  1766  
  1767  		// nil Chan recv.
  1768  		if x.Maybe() {
  1769  			cases = append(cases, SelectCase{
  1770  				Dir:  SelectRecv,
  1771  				Chan: ValueOf((chan int)(nil)),
  1772  			})
  1773  			info = append(info, caseInfo{desc: "nil Chan recv"})
  1774  		}
  1775  
  1776  		// closed Chan send.
  1777  		if x.Maybe() {
  1778  			ch := make(chan int)
  1779  			close(ch)
  1780  			cases = append(cases, SelectCase{
  1781  				Dir:  SelectSend,
  1782  				Chan: ValueOf(ch),
  1783  				Send: ValueOf(101),
  1784  			})
  1785  			info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
  1786  		}
  1787  
  1788  		// closed Chan recv.
  1789  		if x.Maybe() {
  1790  			ch, val := newop(len(cases), 0)
  1791  			ch.Close()
  1792  			val = Zero(val.Type())
  1793  			cases = append(cases, SelectCase{
  1794  				Dir:  SelectRecv,
  1795  				Chan: ch,
  1796  			})
  1797  			info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
  1798  		}
  1799  
  1800  		var helper func() // goroutine to help the select complete
  1801  
  1802  		// Add default? Must be last case here, but will permute.
  1803  		// Add the default if the select would otherwise
  1804  		// block forever, and maybe add it anyway.
  1805  		numCanSelect := 0
  1806  		canProceed := false
  1807  		canBlock := true
  1808  		canPanic := false
  1809  		helpers := []int{}
  1810  		for i, c := range info {
  1811  			if c.canSelect {
  1812  				canProceed = true
  1813  				canBlock = false
  1814  				numCanSelect++
  1815  				if c.panic {
  1816  					canPanic = true
  1817  				}
  1818  			} else if c.helper != nil {
  1819  				canProceed = true
  1820  				helpers = append(helpers, i)
  1821  			}
  1822  		}
  1823  		if !canProceed || x.Maybe() {
  1824  			cases = append(cases, SelectCase{
  1825  				Dir: SelectDefault,
  1826  			})
  1827  			info = append(info, caseInfo{desc: "default", canSelect: canBlock})
  1828  			numCanSelect++
  1829  		} else if canBlock {
  1830  			// Select needs to communicate with another goroutine.
  1831  			cas := &info[helpers[x.Choose(len(helpers))]]
  1832  			helper = cas.helper
  1833  			cas.canSelect = true
  1834  			numCanSelect++
  1835  		}
  1836  
  1837  		// Permute cases and case info.
  1838  		// Doing too much here makes the exhaustive loop
  1839  		// too exhausting, so just do two swaps.
  1840  		for loop := 0; loop < 2; loop++ {
  1841  			i := x.Choose(len(cases))
  1842  			j := x.Choose(len(cases))
  1843  			cases[i], cases[j] = cases[j], cases[i]
  1844  			info[i], info[j] = info[j], info[i]
  1845  		}
  1846  
  1847  		if helper != nil {
  1848  			// We wait before kicking off a goroutine to satisfy a blocked select.
  1849  			// The pause needs to be big enough to let the select block before
  1850  			// we run the helper, but if we lose that race once in a while it's okay: the
  1851  			// select will just proceed immediately. Not a big deal.
  1852  			// For short tests we can grow [sic] the timeout a bit without fear of taking too long
  1853  			pause := 10 * time.Microsecond
  1854  			if testing.Short() {
  1855  				pause = 100 * time.Microsecond
  1856  			}
  1857  			time.AfterFunc(pause, helper)
  1858  		}
  1859  
  1860  		// Run select.
  1861  		i, recv, recvOK, panicErr := runSelect(cases, info)
  1862  		if panicErr != nil && !canPanic {
  1863  			t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
  1864  		}
  1865  		if panicErr == nil && canPanic && numCanSelect == 1 {
  1866  			t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
  1867  		}
  1868  		if panicErr != nil {
  1869  			continue
  1870  		}
  1871  
  1872  		cas := info[i]
  1873  		if !cas.canSelect {
  1874  			recvStr := ""
  1875  			if recv.IsValid() {
  1876  				recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
  1877  			}
  1878  			t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
  1879  			continue
  1880  		}
  1881  		if cas.panic {
  1882  			t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
  1883  			continue
  1884  		}
  1885  
  1886  		if cases[i].Dir == SelectRecv {
  1887  			if !recv.IsValid() {
  1888  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
  1889  			}
  1890  			if !cas.recv.IsValid() {
  1891  				t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
  1892  			}
  1893  			if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
  1894  				if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
  1895  					t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
  1896  				}
  1897  				t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
  1898  			}
  1899  		} else {
  1900  			if recv.IsValid() || recvOK {
  1901  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
  1902  			}
  1903  		}
  1904  	}
  1905  }
  1906  
  1907  func TestSelectMaxCases(t *testing.T) {
  1908  	var sCases []SelectCase
  1909  	channel := make(chan int)
  1910  	close(channel)
  1911  	for i := 0; i < 65536; i++ {
  1912  		sCases = append(sCases, SelectCase{
  1913  			Dir:  SelectRecv,
  1914  			Chan: ValueOf(channel),
  1915  		})
  1916  	}
  1917  	// Should not panic
  1918  	_, _, _ = Select(sCases)
  1919  	sCases = append(sCases, SelectCase{
  1920  		Dir:  SelectRecv,
  1921  		Chan: ValueOf(channel),
  1922  	})
  1923  	defer func() {
  1924  		if err := recover(); err != nil {
  1925  			if err.(string) != "reflect.Select: too many cases (max 65536)" {
  1926  				t.Fatalf("unexpected error from select call with greater than max supported cases")
  1927  			}
  1928  		} else {
  1929  			t.Fatalf("expected select call to panic with greater than max supported cases")
  1930  		}
  1931  	}()
  1932  	// Should panic
  1933  	_, _, _ = Select(sCases)
  1934  }
  1935  
  1936  func TestSelectNop(t *testing.T) {
  1937  	// "select { default: }" should always return the default case.
  1938  	chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
  1939  	if chosen != 0 {
  1940  		t.Fatalf("expected Select to return 0, but got %#v", chosen)
  1941  	}
  1942  }
  1943  
  1944  func BenchmarkSelect(b *testing.B) {
  1945  	channel := make(chan int)
  1946  	close(channel)
  1947  	var cases []SelectCase
  1948  	for i := 0; i < 8; i++ {
  1949  		cases = append(cases, SelectCase{
  1950  			Dir:  SelectRecv,
  1951  			Chan: ValueOf(channel),
  1952  		})
  1953  	}
  1954  	for _, numCases := range []int{1, 4, 8} {
  1955  		b.Run(strconv.Itoa(numCases), func(b *testing.B) {
  1956  			b.ReportAllocs()
  1957  			for i := 0; i < b.N; i++ {
  1958  				_, _, _ = Select(cases[:numCases])
  1959  			}
  1960  		})
  1961  	}
  1962  }
  1963  
  1964  // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
  1965  // If the selectWatcher notices that the select has been blocked for >1 second, it prints
  1966  // an error describing the select and panics the entire test binary.
  1967  var selectWatch struct {
  1968  	sync.Mutex
  1969  	once sync.Once
  1970  	now  time.Time
  1971  	info []caseInfo
  1972  }
  1973  
  1974  func selectWatcher() {
  1975  	for {
  1976  		time.Sleep(1 * time.Second)
  1977  		selectWatch.Lock()
  1978  		if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
  1979  			fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
  1980  			panic("select stuck")
  1981  		}
  1982  		selectWatch.Unlock()
  1983  	}
  1984  }
  1985  
  1986  // runSelect runs a single select test.
  1987  // It returns the values returned by Select but also returns
  1988  // a panic value if the Select panics.
  1989  func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
  1990  	defer func() {
  1991  		panicErr = recover()
  1992  
  1993  		selectWatch.Lock()
  1994  		selectWatch.info = nil
  1995  		selectWatch.Unlock()
  1996  	}()
  1997  
  1998  	selectWatch.Lock()
  1999  	selectWatch.now = time.Now()
  2000  	selectWatch.info = info
  2001  	selectWatch.Unlock()
  2002  
  2003  	chosen, recv, recvOK = Select(cases)
  2004  	return
  2005  }
  2006  
  2007  // fmtSelect formats the information about a single select test.
  2008  func fmtSelect(info []caseInfo) string {
  2009  	var buf bytes.Buffer
  2010  	fmt.Fprintf(&buf, "\nselect {\n")
  2011  	for i, cas := range info {
  2012  		fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
  2013  		if cas.recv.IsValid() {
  2014  			fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
  2015  		}
  2016  		if cas.canSelect {
  2017  			fmt.Fprintf(&buf, " canselect")
  2018  		}
  2019  		if cas.panic {
  2020  			fmt.Fprintf(&buf, " panic")
  2021  		}
  2022  		fmt.Fprintf(&buf, "\n")
  2023  	}
  2024  	fmt.Fprintf(&buf, "}")
  2025  	return buf.String()
  2026  }
  2027  
  2028  type two [2]uintptr
  2029  
  2030  // Difficult test for function call because of
  2031  // implicit padding between arguments.
  2032  func dummy(b byte, c int, d byte, e two, f byte, g float32, h byte) (i byte, j int, k byte, l two, m byte, n float32, o byte) {
  2033  	return b, c, d, e, f, g, h
  2034  }
  2035  
  2036  func TestFunc(t *testing.T) {
  2037  	ret := ValueOf(dummy).Call([]Value{
  2038  		ValueOf(byte(10)),
  2039  		ValueOf(20),
  2040  		ValueOf(byte(30)),
  2041  		ValueOf(two{40, 50}),
  2042  		ValueOf(byte(60)),
  2043  		ValueOf(float32(70)),
  2044  		ValueOf(byte(80)),
  2045  	})
  2046  	if len(ret) != 7 {
  2047  		t.Fatalf("Call returned %d values, want 7", len(ret))
  2048  	}
  2049  
  2050  	i := byte(ret[0].Uint())
  2051  	j := int(ret[1].Int())
  2052  	k := byte(ret[2].Uint())
  2053  	l := ret[3].Interface().(two)
  2054  	m := byte(ret[4].Uint())
  2055  	n := float32(ret[5].Float())
  2056  	o := byte(ret[6].Uint())
  2057  
  2058  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  2059  		t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
  2060  	}
  2061  
  2062  	for i, v := range ret {
  2063  		if v.CanAddr() {
  2064  			t.Errorf("result %d is addressable", i)
  2065  		}
  2066  	}
  2067  }
  2068  
  2069  func TestCallConvert(t *testing.T) {
  2070  	v := ValueOf(new(io.ReadWriter)).Elem()
  2071  	f := ValueOf(func(r io.Reader) io.Reader { return r })
  2072  	out := f.Call([]Value{v})
  2073  	if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
  2074  		t.Errorf("expected [nil], got %v", out)
  2075  	}
  2076  }
  2077  
  2078  type emptyStruct struct{}
  2079  
  2080  type nonEmptyStruct struct {
  2081  	member int
  2082  }
  2083  
  2084  func returnEmpty() emptyStruct {
  2085  	return emptyStruct{}
  2086  }
  2087  
  2088  func takesEmpty(e emptyStruct) {
  2089  }
  2090  
  2091  func returnNonEmpty(i int) nonEmptyStruct {
  2092  	return nonEmptyStruct{member: i}
  2093  }
  2094  
  2095  func takesNonEmpty(n nonEmptyStruct) int {
  2096  	return n.member
  2097  }
  2098  
  2099  func TestCallWithStruct(t *testing.T) {
  2100  	r := ValueOf(returnEmpty).Call(nil)
  2101  	if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
  2102  		t.Errorf("returning empty struct returned %#v instead", r)
  2103  	}
  2104  	r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
  2105  	if len(r) != 0 {
  2106  		t.Errorf("takesEmpty returned values: %#v", r)
  2107  	}
  2108  	r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
  2109  	if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
  2110  		t.Errorf("returnNonEmpty returned %#v", r)
  2111  	}
  2112  	r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
  2113  	if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
  2114  		t.Errorf("takesNonEmpty returned %#v", r)
  2115  	}
  2116  }
  2117  
  2118  func TestCallReturnsEmpty(t *testing.T) {
  2119  	// Issue 21717: past-the-end pointer write in Call with
  2120  	// nonzero-sized frame and zero-sized return value.
  2121  	runtime.GC()
  2122  	var finalized uint32
  2123  	f := func() (emptyStruct, *[2]int64) {
  2124  		i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
  2125  		runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
  2126  		return emptyStruct{}, i
  2127  	}
  2128  	v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
  2129  	timeout := time.After(5 * time.Second)
  2130  	for atomic.LoadUint32(&finalized) == 0 {
  2131  		select {
  2132  		case <-timeout:
  2133  			t.Fatal("finalizer did not run")
  2134  		default:
  2135  		}
  2136  		runtime.Gosched()
  2137  		runtime.GC()
  2138  	}
  2139  	runtime.KeepAlive(v)
  2140  }
  2141  
  2142  func BenchmarkCall(b *testing.B) {
  2143  	fv := ValueOf(func(a, b string) {})
  2144  	b.ReportAllocs()
  2145  	b.RunParallel(func(pb *testing.PB) {
  2146  		args := []Value{ValueOf("a"), ValueOf("b")}
  2147  		for pb.Next() {
  2148  			fv.Call(args)
  2149  		}
  2150  	})
  2151  }
  2152  
  2153  type myint int64
  2154  
  2155  func (i *myint) inc() {
  2156  	*i = *i + 1
  2157  }
  2158  
  2159  func BenchmarkCallMethod(b *testing.B) {
  2160  	b.ReportAllocs()
  2161  	z := new(myint)
  2162  
  2163  	v := ValueOf(z.inc)
  2164  	for i := 0; i < b.N; i++ {
  2165  		v.Call(nil)
  2166  	}
  2167  }
  2168  
  2169  func BenchmarkCallArgCopy(b *testing.B) {
  2170  	byteArray := func(n int) Value {
  2171  		return Zero(ArrayOf(n, TypeOf(byte(0))))
  2172  	}
  2173  	sizes := [...]struct {
  2174  		fv  Value
  2175  		arg Value
  2176  	}{
  2177  		{ValueOf(func(a [128]byte) {}), byteArray(128)},
  2178  		{ValueOf(func(a [256]byte) {}), byteArray(256)},
  2179  		{ValueOf(func(a [1024]byte) {}), byteArray(1024)},
  2180  		{ValueOf(func(a [4096]byte) {}), byteArray(4096)},
  2181  		{ValueOf(func(a [65536]byte) {}), byteArray(65536)},
  2182  	}
  2183  	for _, size := range sizes {
  2184  		bench := func(b *testing.B) {
  2185  			args := []Value{size.arg}
  2186  			b.SetBytes(int64(size.arg.Len()))
  2187  			b.ResetTimer()
  2188  			b.RunParallel(func(pb *testing.PB) {
  2189  				for pb.Next() {
  2190  					size.fv.Call(args)
  2191  				}
  2192  			})
  2193  		}
  2194  		name := fmt.Sprintf("size=%v", size.arg.Len())
  2195  		b.Run(name, bench)
  2196  	}
  2197  }
  2198  
  2199  func TestMakeFunc(t *testing.T) {
  2200  	f := dummy
  2201  	fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
  2202  	ValueOf(&f).Elem().Set(fv)
  2203  
  2204  	// Call g with small arguments so that there is
  2205  	// something predictable (and different from the
  2206  	// correct results) in those positions on the stack.
  2207  	g := dummy
  2208  	g(1, 2, 3, two{4, 5}, 6, 7, 8)
  2209  
  2210  	// Call constructed function f.
  2211  	i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
  2212  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  2213  		t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
  2214  	}
  2215  }
  2216  
  2217  func TestMakeFuncInterface(t *testing.T) {
  2218  	fn := func(i int) int { return i }
  2219  	incr := func(in []Value) []Value {
  2220  		return []Value{ValueOf(int(in[0].Int() + 1))}
  2221  	}
  2222  	fv := MakeFunc(TypeOf(fn), incr)
  2223  	ValueOf(&fn).Elem().Set(fv)
  2224  	if r := fn(2); r != 3 {
  2225  		t.Errorf("Call returned %d, want 3", r)
  2226  	}
  2227  	if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
  2228  		t.Errorf("Call returned %d, want 15", r)
  2229  	}
  2230  	if r := fv.Interface().(func(int) int)(26); r != 27 {
  2231  		t.Errorf("Call returned %d, want 27", r)
  2232  	}
  2233  }
  2234  
  2235  func TestMakeFuncVariadic(t *testing.T) {
  2236  	// Test that variadic arguments are packed into a slice and passed as last arg
  2237  	fn := func(_ int, is ...int) []int { return nil }
  2238  	fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
  2239  	ValueOf(&fn).Elem().Set(fv)
  2240  
  2241  	r := fn(1, 2, 3)
  2242  	if r[0] != 2 || r[1] != 3 {
  2243  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  2244  	}
  2245  
  2246  	r = fn(1, []int{2, 3}...)
  2247  	if r[0] != 2 || r[1] != 3 {
  2248  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  2249  	}
  2250  
  2251  	r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
  2252  	if r[0] != 2 || r[1] != 3 {
  2253  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  2254  	}
  2255  
  2256  	r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
  2257  	if r[0] != 2 || r[1] != 3 {
  2258  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  2259  	}
  2260  
  2261  	f := fv.Interface().(func(int, ...int) []int)
  2262  
  2263  	r = f(1, 2, 3)
  2264  	if r[0] != 2 || r[1] != 3 {
  2265  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  2266  	}
  2267  	r = f(1, []int{2, 3}...)
  2268  	if r[0] != 2 || r[1] != 3 {
  2269  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  2270  	}
  2271  }
  2272  
  2273  // Dummy type that implements io.WriteCloser
  2274  type WC struct {
  2275  }
  2276  
  2277  func (w *WC) Write(p []byte) (n int, err error) {
  2278  	return 0, nil
  2279  }
  2280  func (w *WC) Close() error {
  2281  	return nil
  2282  }
  2283  
  2284  func TestMakeFuncValidReturnAssignments(t *testing.T) {
  2285  	// reflect.Values returned from the wrapped function should be assignment-converted
  2286  	// to the types returned by the result of MakeFunc.
  2287  
  2288  	// Concrete types should be promotable to interfaces they implement.
  2289  	var f func() error
  2290  	f = MakeFunc(TypeOf(f), func([]Value) []Value {
  2291  		return []Value{ValueOf(io.EOF)}
  2292  	}).Interface().(func() error)
  2293  	f()
  2294  
  2295  	// Super-interfaces should be promotable to simpler interfaces.
  2296  	var g func() io.Writer
  2297  	g = MakeFunc(TypeOf(g), func([]Value) []Value {
  2298  		var w io.WriteCloser = &WC{}
  2299  		return []Value{ValueOf(&w).Elem()}
  2300  	}).Interface().(func() io.Writer)
  2301  	g()
  2302  
  2303  	// Channels should be promotable to directional channels.
  2304  	var h func() <-chan int
  2305  	h = MakeFunc(TypeOf(h), func([]Value) []Value {
  2306  		return []Value{ValueOf(make(chan int))}
  2307  	}).Interface().(func() <-chan int)
  2308  	h()
  2309  
  2310  	// Unnamed types should be promotable to named types.
  2311  	type T struct{ a, b, c int }
  2312  	var i func() T
  2313  	i = MakeFunc(TypeOf(i), func([]Value) []Value {
  2314  		return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
  2315  	}).Interface().(func() T)
  2316  	i()
  2317  }
  2318  
  2319  func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
  2320  	// Type doesn't implement the required interface.
  2321  	shouldPanic("", func() {
  2322  		var f func() error
  2323  		f = MakeFunc(TypeOf(f), func([]Value) []Value {
  2324  			return []Value{ValueOf(int(7))}
  2325  		}).Interface().(func() error)
  2326  		f()
  2327  	})
  2328  	// Assigning to an interface with additional methods.
  2329  	shouldPanic("", func() {
  2330  		var f func() io.ReadWriteCloser
  2331  		f = MakeFunc(TypeOf(f), func([]Value) []Value {
  2332  			var w io.WriteCloser = &WC{}
  2333  			return []Value{ValueOf(&w).Elem()}
  2334  		}).Interface().(func() io.ReadWriteCloser)
  2335  		f()
  2336  	})
  2337  	// Directional channels can't be assigned to bidirectional ones.
  2338  	shouldPanic("", func() {
  2339  		var f func() chan int
  2340  		f = MakeFunc(TypeOf(f), func([]Value) []Value {
  2341  			var c <-chan int = make(chan int)
  2342  			return []Value{ValueOf(c)}
  2343  		}).Interface().(func() chan int)
  2344  		f()
  2345  	})
  2346  	// Two named types which are otherwise identical.
  2347  	shouldPanic("", func() {
  2348  		type T struct{ a, b, c int }
  2349  		type U struct{ a, b, c int }
  2350  		var f func() T
  2351  		f = MakeFunc(TypeOf(f), func([]Value) []Value {
  2352  			return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
  2353  		}).Interface().(func() T)
  2354  		f()
  2355  	})
  2356  }
  2357  
  2358  type Point struct {
  2359  	x, y int
  2360  }
  2361  
  2362  // This will be index 0.
  2363  func (p Point) AnotherMethod(scale int) int {
  2364  	return -1
  2365  }
  2366  
  2367  // This will be index 1.
  2368  func (p Point) Dist(scale int) int {
  2369  	//println("Point.Dist", p.x, p.y, scale)
  2370  	return p.x*p.x*scale + p.y*p.y*scale
  2371  }
  2372  
  2373  // This will be index 2.
  2374  func (p Point) GCMethod(k int) int {
  2375  	runtime.GC()
  2376  	return k + p.x
  2377  }
  2378  
  2379  // This will be index 3.
  2380  func (p Point) NoArgs() {
  2381  	// Exercise no-argument/no-result paths.
  2382  }
  2383  
  2384  // This will be index 4.
  2385  func (p Point) TotalDist(points ...Point) int {
  2386  	tot := 0
  2387  	for _, q := range points {
  2388  		dx := q.x - p.x
  2389  		dy := q.y - p.y
  2390  		tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
  2391  
  2392  	}
  2393  	return tot
  2394  }
  2395  
  2396  // This will be index 5.
  2397  func (p *Point) Int64Method(x int64) int64 {
  2398  	return x
  2399  }
  2400  
  2401  // This will be index 6.
  2402  func (p *Point) Int32Method(x int32) int32 {
  2403  	return x
  2404  }
  2405  
  2406  func TestMethod(t *testing.T) {
  2407  	// Non-curried method of type.
  2408  	p := Point{3, 4}
  2409  	i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
  2410  	if i != 250 {
  2411  		t.Errorf("Type Method returned %d; want 250", i)
  2412  	}
  2413  
  2414  	m, ok := TypeOf(p).MethodByName("Dist")
  2415  	if !ok {
  2416  		t.Fatalf("method by name failed")
  2417  	}
  2418  	i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
  2419  	if i != 275 {
  2420  		t.Errorf("Type MethodByName returned %d; want 275", i)
  2421  	}
  2422  
  2423  	m, ok = TypeOf(p).MethodByName("NoArgs")
  2424  	if !ok {
  2425  		t.Fatalf("method by name failed")
  2426  	}
  2427  	n := len(m.Func.Call([]Value{ValueOf(p)}))
  2428  	if n != 0 {
  2429  		t.Errorf("NoArgs returned %d values; want 0", n)
  2430  	}
  2431  
  2432  	i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
  2433  	if i != 300 {
  2434  		t.Errorf("Pointer Type Method returned %d; want 300", i)
  2435  	}
  2436  
  2437  	m, ok = TypeOf(&p).MethodByName("Dist")
  2438  	if !ok {
  2439  		t.Fatalf("ptr method by name failed")
  2440  	}
  2441  	i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
  2442  	if i != 325 {
  2443  		t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
  2444  	}
  2445  
  2446  	m, ok = TypeOf(&p).MethodByName("NoArgs")
  2447  	if !ok {
  2448  		t.Fatalf("method by name failed")
  2449  	}
  2450  	n = len(m.Func.Call([]Value{ValueOf(&p)}))
  2451  	if n != 0 {
  2452  		t.Errorf("NoArgs returned %d values; want 0", n)
  2453  	}
  2454  
  2455  	// Curried method of value.
  2456  	tfunc := TypeOf((func(int) int)(nil))
  2457  	v := ValueOf(p).Method(1)
  2458  	if tt := v.Type(); tt != tfunc {
  2459  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  2460  	}
  2461  	i = v.Call([]Value{ValueOf(14)})[0].Int()
  2462  	if i != 350 {
  2463  		t.Errorf("Value Method returned %d; want 350", i)
  2464  	}
  2465  	v = ValueOf(p).MethodByName("Dist")
  2466  	if tt := v.Type(); tt != tfunc {
  2467  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  2468  	}
  2469  	i = v.Call([]Value{ValueOf(15)})[0].Int()
  2470  	if i != 375 {
  2471  		t.Errorf("Value MethodByName returned %d; want 375", i)
  2472  	}
  2473  	v = ValueOf(p).MethodByName("NoArgs")
  2474  	v.Call(nil)
  2475  
  2476  	// Curried method of pointer.
  2477  	v = ValueOf(&p).Method(1)
  2478  	if tt := v.Type(); tt != tfunc {
  2479  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  2480  	}
  2481  	i = v.Call([]Value{ValueOf(16)})[0].Int()
  2482  	if i != 400 {
  2483  		t.Errorf("Pointer Value Method returned %d; want 400", i)
  2484  	}
  2485  	v = ValueOf(&p).MethodByName("Dist")
  2486  	if tt := v.Type(); tt != tfunc {
  2487  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  2488  	}
  2489  	i = v.Call([]Value{ValueOf(17)})[0].Int()
  2490  	if i != 425 {
  2491  		t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
  2492  	}
  2493  	v = ValueOf(&p).MethodByName("NoArgs")
  2494  	v.Call(nil)
  2495  
  2496  	// Curried method of interface value.
  2497  	// Have to wrap interface value in a struct to get at it.
  2498  	// Passing it to ValueOf directly would
  2499  	// access the underlying Point, not the interface.
  2500  	var x interface {
  2501  		Dist(int) int
  2502  	} = p
  2503  	pv := ValueOf(&x).Elem()
  2504  	v = pv.Method(0)
  2505  	if tt := v.Type(); tt != tfunc {
  2506  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  2507  	}
  2508  	i = v.Call([]Value{ValueOf(18)})[0].Int()
  2509  	if i != 450 {
  2510  		t.Errorf("Interface Method returned %d; want 450", i)
  2511  	}
  2512  	v = pv.MethodByName("Dist")
  2513  	if tt := v.Type(); tt != tfunc {
  2514  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  2515  	}
  2516  	i = v.Call([]Value{ValueOf(19)})[0].Int()
  2517  	if i != 475 {
  2518  		t.Errorf("Interface MethodByName returned %d; want 475", i)
  2519  	}
  2520  }
  2521  
  2522  func TestMethodValue(t *testing.T) {
  2523  	p := Point{3, 4}
  2524  	var i int64
  2525  
  2526  	// Check that method value have the same underlying code pointers.
  2527  	if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
  2528  		t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
  2529  	}
  2530  
  2531  	// Curried method of value.
  2532  	tfunc := TypeOf((func(int) int)(nil))
  2533  	v := ValueOf(p).Method(1)
  2534  	if tt := v.Type(); tt != tfunc {
  2535  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  2536  	}
  2537  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
  2538  	if i != 250 {
  2539  		t.Errorf("Value Method returned %d; want 250", i)
  2540  	}
  2541  	v = ValueOf(p).MethodByName("Dist")
  2542  	if tt := v.Type(); tt != tfunc {
  2543  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  2544  	}
  2545  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
  2546  	if i != 275 {
  2547  		t.Errorf("Value MethodByName returned %d; want 275", i)
  2548  	}
  2549  	v = ValueOf(p).MethodByName("NoArgs")
  2550  	ValueOf(v.Interface()).Call(nil)
  2551  	v.Interface().(func())()
  2552  
  2553  	// Curried method of pointer.
  2554  	v = ValueOf(&p).Method(1)
  2555  	if tt := v.Type(); tt != tfunc {
  2556  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  2557  	}
  2558  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
  2559  	if i != 300 {
  2560  		t.Errorf("Pointer Value Method returned %d; want 300", i)
  2561  	}
  2562  	v = ValueOf(&p).MethodByName("Dist")
  2563  	if tt := v.Type(); tt != tfunc {
  2564  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  2565  	}
  2566  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
  2567  	if i != 325 {
  2568  		t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
  2569  	}
  2570  	v = ValueOf(&p).MethodByName("NoArgs")
  2571  	ValueOf(v.Interface()).Call(nil)
  2572  	v.Interface().(func())()
  2573  
  2574  	// Curried method of pointer to pointer.
  2575  	pp := &p
  2576  	v = ValueOf(&pp).Elem().Method(1)
  2577  	if tt := v.Type(); tt != tfunc {
  2578  		t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
  2579  	}
  2580  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
  2581  	if i != 350 {
  2582  		t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
  2583  	}
  2584  	v = ValueOf(&pp).Elem().MethodByName("Dist")
  2585  	if tt := v.Type(); tt != tfunc {
  2586  		t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  2587  	}
  2588  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
  2589  	if i != 375 {
  2590  		t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
  2591  	}
  2592  
  2593  	// Curried method of interface value.
  2594  	// Have to wrap interface value in a struct to get at it.
  2595  	// Passing it to ValueOf directly would
  2596  	// access the underlying Point, not the interface.
  2597  	var s = struct {
  2598  		X interface {
  2599  			Dist(int) int
  2600  		}
  2601  	}{p}
  2602  	pv := ValueOf(s).Field(0)
  2603  	v = pv.Method(0)
  2604  	if tt := v.Type(); tt != tfunc {
  2605  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  2606  	}
  2607  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
  2608  	if i != 400 {
  2609  		t.Errorf("Interface Method returned %d; want 400", i)
  2610  	}
  2611  	v = pv.MethodByName("Dist")
  2612  	if tt := v.Type(); tt != tfunc {
  2613  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  2614  	}
  2615  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
  2616  	if i != 425 {
  2617  		t.Errorf("Interface MethodByName returned %d; want 425", i)
  2618  	}
  2619  
  2620  	// For issue #33628: method args are not stored at the right offset
  2621  	// on amd64p32.
  2622  	m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
  2623  	if x := m64(123); x != 123 {
  2624  		t.Errorf("Int64Method returned %d; want 123", x)
  2625  	}
  2626  	m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
  2627  	if x := m32(456); x != 456 {
  2628  		t.Errorf("Int32Method returned %d; want 456", x)
  2629  	}
  2630  }
  2631  
  2632  func TestVariadicMethodValue(t *testing.T) {
  2633  	p := Point{3, 4}
  2634  	points := []Point{{20, 21}, {22, 23}, {24, 25}}
  2635  	want := int64(p.TotalDist(points[0], points[1], points[2]))
  2636  
  2637  	// Variadic method of type.
  2638  	tfunc := TypeOf((func(Point, ...Point) int)(nil))
  2639  	if tt := TypeOf(p).Method(4).Type; tt != tfunc {
  2640  		t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
  2641  	}
  2642  
  2643  	// Curried method of value.
  2644  	tfunc = TypeOf((func(...Point) int)(nil))
  2645  	v := ValueOf(p).Method(4)
  2646  	if tt := v.Type(); tt != tfunc {
  2647  		t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
  2648  	}
  2649  	i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
  2650  	if i != want {
  2651  		t.Errorf("Variadic Method returned %d; want %d", i, want)
  2652  	}
  2653  	i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
  2654  	if i != want {
  2655  		t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
  2656  	}
  2657  
  2658  	f := v.Interface().(func(...Point) int)
  2659  	i = int64(f(points[0], points[1], points[2]))
  2660  	if i != want {
  2661  		t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
  2662  	}
  2663  	i = int64(f(points...))
  2664  	if i != want {
  2665  		t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
  2666  	}
  2667  }
  2668  
  2669  type DirectIfaceT struct {
  2670  	p *int
  2671  }
  2672  
  2673  func (d DirectIfaceT) M() int { return *d.p }
  2674  
  2675  func TestDirectIfaceMethod(t *testing.T) {
  2676  	x := 42
  2677  	v := DirectIfaceT{&x}
  2678  	typ := TypeOf(v)
  2679  	m, ok := typ.MethodByName("M")
  2680  	if !ok {
  2681  		t.Fatalf("cannot find method M")
  2682  	}
  2683  	in := []Value{ValueOf(v)}
  2684  	out := m.Func.Call(in)
  2685  	if got := out[0].Int(); got != 42 {
  2686  		t.Errorf("Call with value receiver got %d, want 42", got)
  2687  	}
  2688  
  2689  	pv := &v
  2690  	typ = TypeOf(pv)
  2691  	m, ok = typ.MethodByName("M")
  2692  	if !ok {
  2693  		t.Fatalf("cannot find method M")
  2694  	}
  2695  	in = []Value{ValueOf(pv)}
  2696  	out = m.Func.Call(in)
  2697  	if got := out[0].Int(); got != 42 {
  2698  		t.Errorf("Call with pointer receiver got %d, want 42", got)
  2699  	}
  2700  }
  2701  
  2702  // Reflect version of $GOROOT/test/method5.go
  2703  
  2704  // Concrete types implementing M method.
  2705  // Smaller than a word, word-sized, larger than a word.
  2706  // Value and pointer receivers.
  2707  
  2708  type Tinter interface {
  2709  	M(int, byte) (byte, int)
  2710  }
  2711  
  2712  type Tsmallv byte
  2713  
  2714  func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  2715  
  2716  type Tsmallp byte
  2717  
  2718  func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  2719  
  2720  type Twordv uintptr
  2721  
  2722  func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  2723  
  2724  type Twordp uintptr
  2725  
  2726  func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  2727  
  2728  type Tbigv [2]uintptr
  2729  
  2730  func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  2731  
  2732  type Tbigp [2]uintptr
  2733  
  2734  func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  2735  
  2736  type tinter interface {
  2737  	m(int, byte) (byte, int)
  2738  }
  2739  
  2740  // Embedding via pointer.
  2741  
  2742  type Tm1 struct {
  2743  	Tm2
  2744  }
  2745  
  2746  type Tm2 struct {
  2747  	*Tm3
  2748  }
  2749  
  2750  type Tm3 struct {
  2751  	*Tm4
  2752  }
  2753  
  2754  type Tm4 struct {
  2755  }
  2756  
  2757  func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
  2758  
  2759  func TestMethod5(t *testing.T) {
  2760  	CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
  2761  		b, x := f(1000, 99)
  2762  		if b != 99 || x != 1000+inc {
  2763  			t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  2764  		}
  2765  	}
  2766  
  2767  	CheckV := func(name string, i Value, inc int) {
  2768  		bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
  2769  		b := bx[0].Interface()
  2770  		x := bx[1].Interface()
  2771  		if b != byte(99) || x != 1000+inc {
  2772  			t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  2773  		}
  2774  
  2775  		CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
  2776  	}
  2777  
  2778  	var TinterType = TypeOf(new(Tinter)).Elem()
  2779  
  2780  	CheckI := func(name string, i any, inc int) {
  2781  		v := ValueOf(i)
  2782  		CheckV(name, v, inc)
  2783  		CheckV("(i="+name+")", v.Convert(TinterType), inc)
  2784  	}
  2785  
  2786  	sv := Tsmallv(1)
  2787  	CheckI("sv", sv, 1)
  2788  	CheckI("&sv", &sv, 1)
  2789  
  2790  	sp := Tsmallp(2)
  2791  	CheckI("&sp", &sp, 2)
  2792  
  2793  	wv := Twordv(3)
  2794  	CheckI("wv", wv, 3)
  2795  	CheckI("&wv", &wv, 3)
  2796  
  2797  	wp := Twordp(4)
  2798  	CheckI("&wp", &wp, 4)
  2799  
  2800  	bv := Tbigv([2]uintptr{5, 6})
  2801  	CheckI("bv", bv, 11)
  2802  	CheckI("&bv", &bv, 11)
  2803  
  2804  	bp := Tbigp([2]uintptr{7, 8})
  2805  	CheckI("&bp", &bp, 15)
  2806  
  2807  	t4 := Tm4{}
  2808  	t3 := Tm3{&t4}
  2809  	t2 := Tm2{&t3}
  2810  	t1 := Tm1{t2}
  2811  	CheckI("t4", t4, 40)
  2812  	CheckI("&t4", &t4, 40)
  2813  	CheckI("t3", t3, 40)
  2814  	CheckI("&t3", &t3, 40)
  2815  	CheckI("t2", t2, 40)
  2816  	CheckI("&t2", &t2, 40)
  2817  	CheckI("t1", t1, 40)
  2818  	CheckI("&t1", &t1, 40)
  2819  
  2820  	var tnil Tinter
  2821  	vnil := ValueOf(&tnil).Elem()
  2822  	shouldPanic("Method", func() { vnil.Method(0) })
  2823  }
  2824  
  2825  func TestInterfaceSet(t *testing.T) {
  2826  	p := &Point{3, 4}
  2827  
  2828  	var s struct {
  2829  		I any
  2830  		P interface {
  2831  			Dist(int) int
  2832  		}
  2833  	}
  2834  	sv := ValueOf(&s).Elem()
  2835  	sv.Field(0).Set(ValueOf(p))
  2836  	if q := s.I.(*Point); q != p {
  2837  		t.Errorf("i: have %p want %p", q, p)
  2838  	}
  2839  
  2840  	pv := sv.Field(1)
  2841  	pv.Set(ValueOf(p))
  2842  	if q := s.P.(*Point); q != p {
  2843  		t.Errorf("i: have %p want %p", q, p)
  2844  	}
  2845  
  2846  	i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
  2847  	if i != 250 {
  2848  		t.Errorf("Interface Method returned %d; want 250", i)
  2849  	}
  2850  }
  2851  
  2852  type T1 struct {
  2853  	a string
  2854  	int
  2855  }
  2856  
  2857  func TestAnonymousFields(t *testing.T) {
  2858  	var field StructField
  2859  	var ok bool
  2860  	var t1 T1
  2861  	type1 := TypeOf(t1)
  2862  	if field, ok = type1.FieldByName("int"); !ok {
  2863  		t.Fatal("no field 'int'")
  2864  	}
  2865  	if field.Index[0] != 1 {
  2866  		t.Error("field index should be 1; is", field.Index)
  2867  	}
  2868  }
  2869  
  2870  type FTest struct {
  2871  	s     any
  2872  	name  string
  2873  	index []int
  2874  	value int
  2875  }
  2876  
  2877  type D1 struct {
  2878  	d int
  2879  }
  2880  type D2 struct {
  2881  	d int
  2882  }
  2883  
  2884  type S0 struct {
  2885  	A, B, C int
  2886  	D1
  2887  	D2
  2888  }
  2889  
  2890  type S1 struct {
  2891  	B int
  2892  	S0
  2893  }
  2894  
  2895  type S2 struct {
  2896  	A int
  2897  	*S1
  2898  }
  2899  
  2900  type S1x struct {
  2901  	S1
  2902  }
  2903  
  2904  type S1y struct {
  2905  	S1
  2906  }
  2907  
  2908  type S3 struct {
  2909  	S1x
  2910  	S2
  2911  	D, E int
  2912  	*S1y
  2913  }
  2914  
  2915  type S4 struct {
  2916  	*S4
  2917  	A int
  2918  }
  2919  
  2920  // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
  2921  type S5 struct {
  2922  	S6
  2923  	S7
  2924  	S8
  2925  }
  2926  
  2927  type S6 struct {
  2928  	X int
  2929  }
  2930  
  2931  type S7 S6
  2932  
  2933  type S8 struct {
  2934  	S9
  2935  }
  2936  
  2937  type S9 struct {
  2938  	X int
  2939  	Y int
  2940  }
  2941  
  2942  // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
  2943  type S10 struct {
  2944  	S11
  2945  	S12
  2946  	S13
  2947  }
  2948  
  2949  type S11 struct {
  2950  	S6
  2951  }
  2952  
  2953  type S12 struct {
  2954  	S6
  2955  }
  2956  
  2957  type S13 struct {
  2958  	S8
  2959  }
  2960  
  2961  // The X in S15.S11.S1 and S16.S11.S1 annihilate.
  2962  type S14 struct {
  2963  	S15
  2964  	S16
  2965  }
  2966  
  2967  type S15 struct {
  2968  	S11
  2969  }
  2970  
  2971  type S16 struct {
  2972  	S11
  2973  }
  2974  
  2975  var fieldTests = []FTest{
  2976  	{struct{}{}, "", nil, 0},
  2977  	{struct{}{}, "Foo", nil, 0},
  2978  	{S0{A: 'a'}, "A", []int{0}, 'a'},
  2979  	{S0{}, "D", nil, 0},
  2980  	{S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
  2981  	{S1{B: 'b'}, "B", []int{0}, 'b'},
  2982  	{S1{}, "S0", []int{1}, 0},
  2983  	{S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
  2984  	{S2{A: 'a'}, "A", []int{0}, 'a'},
  2985  	{S2{}, "S1", []int{1}, 0},
  2986  	{S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
  2987  	{S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
  2988  	{S2{}, "D", nil, 0},
  2989  	{S3{}, "S1", nil, 0},
  2990  	{S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
  2991  	{S3{}, "B", nil, 0},
  2992  	{S3{D: 'd'}, "D", []int{2}, 0},
  2993  	{S3{E: 'e'}, "E", []int{3}, 'e'},
  2994  	{S4{A: 'a'}, "A", []int{1}, 'a'},
  2995  	{S4{}, "B", nil, 0},
  2996  	{S5{}, "X", nil, 0},
  2997  	{S5{}, "Y", []int{2, 0, 1}, 0},
  2998  	{S10{}, "X", nil, 0},
  2999  	{S10{}, "Y", []int{2, 0, 0, 1}, 0},
  3000  	{S14{}, "X", nil, 0},
  3001  }
  3002  
  3003  func TestFieldByIndex(t *testing.T) {
  3004  	for _, test := range fieldTests {
  3005  		s := TypeOf(test.s)
  3006  		f := s.FieldByIndex(test.index)
  3007  		if f.Name != "" {
  3008  			if test.index != nil {
  3009  				if f.Name != test.name {
  3010  					t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
  3011  				}
  3012  			} else {
  3013  				t.Errorf("%s.%s found", s.Name(), f.Name)
  3014  			}
  3015  		} else if len(test.index) > 0 {
  3016  			t.Errorf("%s.%s not found", s.Name(), test.name)
  3017  		}
  3018  
  3019  		if test.value != 0 {
  3020  			v := ValueOf(test.s).FieldByIndex(test.index)
  3021  			if v.IsValid() {
  3022  				if x, ok := v.Interface().(int); ok {
  3023  					if x != test.value {
  3024  						t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
  3025  					}
  3026  				} else {
  3027  					t.Errorf("%s%v value not an int", s.Name(), test.index)
  3028  				}
  3029  			} else {
  3030  				t.Errorf("%s%v value not found", s.Name(), test.index)
  3031  			}
  3032  		}
  3033  	}
  3034  }
  3035  
  3036  func TestFieldByName(t *testing.T) {
  3037  	for _, test := range fieldTests {
  3038  		s := TypeOf(test.s)
  3039  		f, found := s.FieldByName(test.name)
  3040  		if found {
  3041  			if test.index != nil {
  3042  				// Verify field depth and index.
  3043  				if len(f.Index) != len(test.index) {
  3044  					t.Errorf("%s.%s depth %d; want %d: %v vs %v", s.Name(), test.name, len(f.Index), len(test.index), f.Index, test.index)
  3045  				} else {
  3046  					for i, x := range f.Index {
  3047  						if x != test.index[i] {
  3048  							t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
  3049  						}
  3050  					}
  3051  				}
  3052  			} else {
  3053  				t.Errorf("%s.%s found", s.Name(), f.Name)
  3054  			}
  3055  		} else if len(test.index) > 0 {
  3056  			t.Errorf("%s.%s not found", s.Name(), test.name)
  3057  		}
  3058  
  3059  		if test.value != 0 {
  3060  			v := ValueOf(test.s).FieldByName(test.name)
  3061  			if v.IsValid() {
  3062  				if x, ok := v.Interface().(int); ok {
  3063  					if x != test.value {
  3064  						t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
  3065  					}
  3066  				} else {
  3067  					t.Errorf("%s.%s value not an int", s.Name(), test.name)
  3068  				}
  3069  			} else {
  3070  				t.Errorf("%s.%s value not found", s.Name(), test.name)
  3071  			}
  3072  		}
  3073  	}
  3074  }
  3075  
  3076  func TestImportPath(t *testing.T) {
  3077  	tests := []struct {
  3078  		t    Type
  3079  		path string
  3080  	}{
  3081  		{TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
  3082  		{TypeOf(int(0)), ""},
  3083  		{TypeOf(int8(0)), ""},
  3084  		{TypeOf(int16(0)), ""},
  3085  		{TypeOf(int32(0)), ""},
  3086  		{TypeOf(int64(0)), ""},
  3087  		{TypeOf(uint(0)), ""},
  3088  		{TypeOf(uint8(0)), ""},
  3089  		{TypeOf(uint16(0)), ""},
  3090  		{TypeOf(uint32(0)), ""},
  3091  		{TypeOf(uint64(0)), ""},
  3092  		{TypeOf(uintptr(0)), ""},
  3093  		{TypeOf(float32(0)), ""},
  3094  		{TypeOf(float64(0)), ""},
  3095  		{TypeOf(complex64(0)), ""},
  3096  		{TypeOf(complex128(0)), ""},
  3097  		{TypeOf(byte(0)), ""},
  3098  		{TypeOf(rune(0)), ""},
  3099  		{TypeOf([]byte(nil)), ""},
  3100  		{TypeOf([]rune(nil)), ""},
  3101  		{TypeOf(string("")), ""},
  3102  		{TypeOf((*any)(nil)).Elem(), ""},
  3103  		{TypeOf((*byte)(nil)), ""},
  3104  		{TypeOf((*rune)(nil)), ""},
  3105  		{TypeOf((*int64)(nil)), ""},
  3106  		{TypeOf(map[string]int{}), ""},
  3107  		{TypeOf((*error)(nil)).Elem(), ""},
  3108  		{TypeOf((*Point)(nil)), ""},
  3109  		{TypeOf((*Point)(nil)).Elem(), "reflect_test"},
  3110  	}
  3111  	for _, test := range tests {
  3112  		if path := test.t.PkgPath(); path != test.path {
  3113  			t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
  3114  		}
  3115  	}
  3116  }
  3117  
  3118  func TestFieldPkgPath(t *testing.T) {
  3119  	type x int
  3120  	typ := TypeOf(struct {
  3121  		Exported   string
  3122  		unexported string
  3123  		OtherPkgFields
  3124  		int // issue 21702
  3125  		*x  // issue 21122
  3126  	}{})
  3127  
  3128  	type pkgpathTest struct {
  3129  		index    []int
  3130  		pkgPath  string
  3131  		embedded bool
  3132  		exported bool
  3133  	}
  3134  
  3135  	checkPkgPath := func(name string, s []pkgpathTest) {
  3136  		for _, test := range s {
  3137  			f := typ.FieldByIndex(test.index)
  3138  			if got, want := f.PkgPath, test.pkgPath; got != want {
  3139  				t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
  3140  			}
  3141  			if got, want := f.Anonymous, test.embedded; got != want {
  3142  				t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
  3143  			}
  3144  			if got, want := f.IsExported(), test.exported; got != want {
  3145  				t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
  3146  			}
  3147  		}
  3148  	}
  3149  
  3150  	checkPkgPath("testStruct", []pkgpathTest{
  3151  		{[]int{0}, "", false, true},              // Exported
  3152  		{[]int{1}, "reflect_test", false, false}, // unexported
  3153  		{[]int{2}, "", true, true},               // OtherPkgFields
  3154  		{[]int{2, 0}, "", false, true},           // OtherExported
  3155  		{[]int{2, 1}, "reflect", false, false},   // otherUnexported
  3156  		{[]int{3}, "reflect_test", true, false},  // int
  3157  		{[]int{4}, "reflect_test", true, false},  // *x
  3158  	})
  3159  
  3160  	type localOtherPkgFields OtherPkgFields
  3161  	typ = TypeOf(localOtherPkgFields{})
  3162  	checkPkgPath("localOtherPkgFields", []pkgpathTest{
  3163  		{[]int{0}, "", false, true},         // OtherExported
  3164  		{[]int{1}, "reflect", false, false}, // otherUnexported
  3165  	})
  3166  }
  3167  
  3168  func TestMethodPkgPath(t *testing.T) {
  3169  	type I interface {
  3170  		x()
  3171  		X()
  3172  	}
  3173  	typ := TypeOf((*interface {
  3174  		I
  3175  		y()
  3176  		Y()
  3177  	})(nil)).Elem()
  3178  
  3179  	tests := []struct {
  3180  		name     string
  3181  		pkgPath  string
  3182  		exported bool
  3183  	}{
  3184  		{"X", "", true},
  3185  		{"Y", "", true},
  3186  		{"x", "reflect_test", false},
  3187  		{"y", "reflect_test", false},
  3188  	}
  3189  
  3190  	for _, test := range tests {
  3191  		m, _ := typ.MethodByName(test.name)
  3192  		if got, want := m.PkgPath, test.pkgPath; got != want {
  3193  			t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
  3194  		}
  3195  		if got, want := m.IsExported(), test.exported; got != want {
  3196  			t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
  3197  		}
  3198  	}
  3199  }
  3200  
  3201  func TestVariadicType(t *testing.T) {
  3202  	// Test example from Type documentation.
  3203  	var f func(x int, y ...float64)
  3204  	typ := TypeOf(f)
  3205  	if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
  3206  		sl := typ.In(1)
  3207  		if sl.Kind() == Slice {
  3208  			if sl.Elem() == TypeOf(0.0) {
  3209  				// ok
  3210  				return
  3211  			}
  3212  		}
  3213  	}
  3214  
  3215  	// Failed
  3216  	t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
  3217  	s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
  3218  	for i := 0; i < typ.NumIn(); i++ {
  3219  		s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
  3220  	}
  3221  	t.Error(s)
  3222  }
  3223  
  3224  type inner struct {
  3225  	x int
  3226  }
  3227  
  3228  type outer struct {
  3229  	y int
  3230  	inner
  3231  }
  3232  
  3233  func (*inner) M() {}
  3234  func (*outer) M() {}
  3235  
  3236  func TestNestedMethods(t *testing.T) {
  3237  	typ := TypeOf((*outer)(nil))
  3238  	if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
  3239  		t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
  3240  		for i := 0; i < typ.NumMethod(); i++ {
  3241  			m := typ.Method(i)
  3242  			t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
  3243  		}
  3244  	}
  3245  }
  3246  
  3247  type unexp struct{}
  3248  
  3249  func (*unexp) f() (int32, int8) { return 7, 7 }
  3250  func (*unexp) g() (int64, int8) { return 8, 8 }
  3251  
  3252  type unexpI interface {
  3253  	f() (int32, int8)
  3254  }
  3255  
  3256  var unexpi unexpI = new(unexp)
  3257  
  3258  func TestUnexportedMethods(t *testing.T) {
  3259  	typ := TypeOf(unexpi)
  3260  
  3261  	if got := typ.NumMethod(); got != 0 {
  3262  		t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
  3263  	}
  3264  }
  3265  
  3266  type InnerInt struct {
  3267  	X int
  3268  }
  3269  
  3270  type OuterInt struct {
  3271  	Y int
  3272  	InnerInt
  3273  }
  3274  
  3275  func (i *InnerInt) M() int {
  3276  	return i.X
  3277  }
  3278  
  3279  func TestEmbeddedMethods(t *testing.T) {
  3280  	typ := TypeOf((*OuterInt)(nil))
  3281  	if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
  3282  		t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
  3283  		for i := 0; i < typ.NumMethod(); i++ {
  3284  			m := typ.Method(i)
  3285  			t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
  3286  		}
  3287  	}
  3288  
  3289  	i := &InnerInt{3}
  3290  	if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
  3291  		t.Errorf("i.M() = %d, want 3", v)
  3292  	}
  3293  
  3294  	o := &OuterInt{1, InnerInt{2}}
  3295  	if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
  3296  		t.Errorf("i.M() = %d, want 2", v)
  3297  	}
  3298  
  3299  	f := (*OuterInt).M
  3300  	if v := f(o); v != 2 {
  3301  		t.Errorf("f(o) = %d, want 2", v)
  3302  	}
  3303  }
  3304  
  3305  type FuncDDD func(...any) error
  3306  
  3307  func (f FuncDDD) M() {}
  3308  
  3309  func TestNumMethodOnDDD(t *testing.T) {
  3310  	rv := ValueOf((FuncDDD)(nil))
  3311  	if n := rv.NumMethod(); n != 1 {
  3312  		t.Fatalf("NumMethod()=%d, want 1", n)
  3313  	}
  3314  }
  3315  
  3316  func TestPtrTo(t *testing.T) {
  3317  	// This block of code means that the ptrToThis field of the
  3318  	// reflect data for *unsafe.Pointer is non zero, see
  3319  	// https://golang.org/issue/19003
  3320  	var x unsafe.Pointer
  3321  	var y = &x
  3322  	var z = &y
  3323  
  3324  	var i int
  3325  
  3326  	typ := TypeOf(z)
  3327  	for i = 0; i < 100; i++ {
  3328  		typ = PointerTo(typ)
  3329  	}
  3330  	for i = 0; i < 100; i++ {
  3331  		typ = typ.Elem()
  3332  	}
  3333  	if typ != TypeOf(z) {
  3334  		t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
  3335  	}
  3336  }
  3337  
  3338  func TestPtrToGC(t *testing.T) {
  3339  	type T *uintptr
  3340  	tt := TypeOf(T(nil))
  3341  	pt := PointerTo(tt)
  3342  	const n = 100
  3343  	var x []any
  3344  	for i := 0; i < n; i++ {
  3345  		v := New(pt)
  3346  		p := new(*uintptr)
  3347  		*p = new(uintptr)
  3348  		**p = uintptr(i)
  3349  		v.Elem().Set(ValueOf(p).Convert(pt))
  3350  		x = append(x, v.Interface())
  3351  	}
  3352  	runtime.GC()
  3353  
  3354  	for i, xi := range x {
  3355  		k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
  3356  		if k != uintptr(i) {
  3357  			t.Errorf("lost x[%d] = %d, want %d", i, k, i)
  3358  		}
  3359  	}
  3360  }
  3361  
  3362  func BenchmarkPtrTo(b *testing.B) {
  3363  	// Construct a type with a zero ptrToThis.
  3364  	type T struct{ int }
  3365  	t := SliceOf(TypeOf(T{}))
  3366  	ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
  3367  	if !ptrToThis.IsValid() {
  3368  		b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
  3369  	}
  3370  	if ptrToThis.Int() != 0 {
  3371  		b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
  3372  	}
  3373  	b.ResetTimer()
  3374  
  3375  	// Now benchmark calling PointerTo on it: we'll have to hit the ptrMap cache on
  3376  	// every call.
  3377  	b.RunParallel(func(pb *testing.PB) {
  3378  		for pb.Next() {
  3379  			PointerTo(t)
  3380  		}
  3381  	})
  3382  }
  3383  
  3384  func TestAddr(t *testing.T) {
  3385  	var p struct {
  3386  		X, Y int
  3387  	}
  3388  
  3389  	v := ValueOf(&p)
  3390  	v = v.Elem()
  3391  	v = v.Addr()
  3392  	v = v.Elem()
  3393  	v = v.Field(0)
  3394  	v.SetInt(2)
  3395  	if p.X != 2 {
  3396  		t.Errorf("Addr.Elem.Set failed to set value")
  3397  	}
  3398  
  3399  	// Again but take address of the ValueOf value.
  3400  	// Exercises generation of PtrTypes not present in the binary.
  3401  	q := &p
  3402  	v = ValueOf(&q).Elem()
  3403  	v = v.Addr()
  3404  	v = v.Elem()
  3405  	v = v.Elem()
  3406  	v = v.Addr()
  3407  	v = v.Elem()
  3408  	v = v.Field(0)
  3409  	v.SetInt(3)
  3410  	if p.X != 3 {
  3411  		t.Errorf("Addr.Elem.Set failed to set value")
  3412  	}
  3413  
  3414  	// Starting without pointer we should get changed value
  3415  	// in interface.
  3416  	qq := p
  3417  	v = ValueOf(&qq).Elem()
  3418  	v0 := v
  3419  	v = v.Addr()
  3420  	v = v.Elem()
  3421  	v = v.Field(0)
  3422  	v.SetInt(4)
  3423  	if p.X != 3 { // should be unchanged from last time
  3424  		t.Errorf("somehow value Set changed original p")
  3425  	}
  3426  	p = v0.Interface().(struct {
  3427  		X, Y int
  3428  	})
  3429  	if p.X != 4 {
  3430  		t.Errorf("Addr.Elem.Set valued to set value in top value")
  3431  	}
  3432  
  3433  	// Verify that taking the address of a type gives us a pointer
  3434  	// which we can convert back using the usual interface
  3435  	// notation.
  3436  	var s struct {
  3437  		B *bool
  3438  	}
  3439  	ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
  3440  	*(ps.(**bool)) = new(bool)
  3441  	if s.B == nil {
  3442  		t.Errorf("Addr.Interface direct assignment failed")
  3443  	}
  3444  }
  3445  
  3446  func noAlloc(t *testing.T, n int, f func(int)) {
  3447  	if testing.Short() {
  3448  		t.Skip("skipping malloc count in short mode")
  3449  	}
  3450  	if runtime.GOMAXPROCS(0) > 1 {
  3451  		t.Skip("skipping; GOMAXPROCS>1")
  3452  	}
  3453  	i := -1
  3454  	allocs := testing.AllocsPerRun(n, func() {
  3455  		f(i)
  3456  		i++
  3457  	})
  3458  	if allocs > 0 {
  3459  		t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
  3460  	}
  3461  }
  3462  
  3463  func TestAllocations(t *testing.T) {
  3464  	noAlloc(t, 100, func(j int) {
  3465  		var i any
  3466  		var v Value
  3467  
  3468  		// We can uncomment this when compiler escape analysis
  3469  		// is good enough to see that the integer assigned to i
  3470  		// does not escape and therefore need not be allocated.
  3471  		//
  3472  		// i = 42 + j
  3473  		// v = ValueOf(i)
  3474  		// if int(v.Int()) != 42+j {
  3475  		// 	panic("wrong int")
  3476  		// }
  3477  
  3478  		i = func(j int) int { return j }
  3479  		v = ValueOf(i)
  3480  		if v.Interface().(func(int) int)(j) != j {
  3481  			panic("wrong result")
  3482  		}
  3483  	})
  3484  }
  3485  
  3486  func TestSmallNegativeInt(t *testing.T) {
  3487  	i := int16(-1)
  3488  	v := ValueOf(i)
  3489  	if v.Int() != -1 {
  3490  		t.Errorf("int16(-1).Int() returned %v", v.Int())
  3491  	}
  3492  }
  3493  
  3494  func TestIndex(t *testing.T) {
  3495  	xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
  3496  	v := ValueOf(xs).Index(3).Interface().(byte)
  3497  	if v != xs[3] {
  3498  		t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
  3499  	}
  3500  	xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
  3501  	v = ValueOf(xa).Index(2).Interface().(byte)
  3502  	if v != xa[2] {
  3503  		t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
  3504  	}
  3505  	s := "0123456789"
  3506  	v = ValueOf(s).Index(3).Interface().(byte)
  3507  	if v != s[3] {
  3508  		t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
  3509  	}
  3510  }
  3511  
  3512  func TestSlice(t *testing.T) {
  3513  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  3514  	v := ValueOf(xs).Slice(3, 5).Interface().([]int)
  3515  	if len(v) != 2 {
  3516  		t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
  3517  	}
  3518  	if cap(v) != 5 {
  3519  		t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
  3520  	}
  3521  	if !DeepEqual(v[0:5], xs[3:]) {
  3522  		t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
  3523  	}
  3524  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  3525  	v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
  3526  	if len(v) != 3 {
  3527  		t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
  3528  	}
  3529  	if cap(v) != 6 {
  3530  		t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
  3531  	}
  3532  	if !DeepEqual(v[0:6], xa[2:]) {
  3533  		t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
  3534  	}
  3535  	s := "0123456789"
  3536  	vs := ValueOf(s).Slice(3, 5).Interface().(string)
  3537  	if vs != s[3:5] {
  3538  		t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
  3539  	}
  3540  
  3541  	rv := ValueOf(&xs).Elem()
  3542  	rv = rv.Slice(3, 4)
  3543  	ptr2 := rv.UnsafePointer()
  3544  	rv = rv.Slice(5, 5)
  3545  	ptr3 := rv.UnsafePointer()
  3546  	if ptr3 != ptr2 {
  3547  		t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
  3548  	}
  3549  }
  3550  
  3551  func TestSlice3(t *testing.T) {
  3552  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  3553  	v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
  3554  	if len(v) != 2 {
  3555  		t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
  3556  	}
  3557  	if cap(v) != 4 {
  3558  		t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
  3559  	}
  3560  	if !DeepEqual(v[0:4], xs[3:7:7]) {
  3561  		t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
  3562  	}
  3563  	rv := ValueOf(&xs).Elem()
  3564  	shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
  3565  	shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
  3566  	shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
  3567  
  3568  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  3569  	v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
  3570  	if len(v) != 3 {
  3571  		t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
  3572  	}
  3573  	if cap(v) != 4 {
  3574  		t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
  3575  	}
  3576  	if !DeepEqual(v[0:4], xa[2:6:6]) {
  3577  		t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
  3578  	}
  3579  	rv = ValueOf(&xa).Elem()
  3580  	shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
  3581  	shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
  3582  	shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
  3583  
  3584  	s := "hello world"
  3585  	rv = ValueOf(&s).Elem()
  3586  	shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
  3587  
  3588  	rv = ValueOf(&xs).Elem()
  3589  	rv = rv.Slice3(3, 5, 7)
  3590  	ptr2 := rv.UnsafePointer()
  3591  	rv = rv.Slice3(4, 4, 4)
  3592  	ptr3 := rv.UnsafePointer()
  3593  	if ptr3 != ptr2 {
  3594  		t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
  3595  	}
  3596  }
  3597  
  3598  func TestSetLenCap(t *testing.T) {
  3599  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  3600  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  3601  
  3602  	vs := ValueOf(&xs).Elem()
  3603  	shouldPanic("SetLen", func() { vs.SetLen(10) })
  3604  	shouldPanic("SetCap", func() { vs.SetCap(10) })
  3605  	shouldPanic("SetLen", func() { vs.SetLen(-1) })
  3606  	shouldPanic("SetCap", func() { vs.SetCap(-1) })
  3607  	shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
  3608  	vs.SetLen(5)
  3609  	if len(xs) != 5 || cap(xs) != 8 {
  3610  		t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
  3611  	}
  3612  	vs.SetCap(6)
  3613  	if len(xs) != 5 || cap(xs) != 6 {
  3614  		t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
  3615  	}
  3616  	vs.SetCap(5)
  3617  	if len(xs) != 5 || cap(xs) != 5 {
  3618  		t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
  3619  	}
  3620  	shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
  3621  	shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
  3622  
  3623  	va := ValueOf(&xa).Elem()
  3624  	shouldPanic("SetLen", func() { va.SetLen(8) })
  3625  	shouldPanic("SetCap", func() { va.SetCap(8) })
  3626  }
  3627  
  3628  func TestVariadic(t *testing.T) {
  3629  	var b bytes.Buffer
  3630  	V := ValueOf
  3631  
  3632  	b.Reset()
  3633  	V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
  3634  	if b.String() != "hello, 42 world" {
  3635  		t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
  3636  	}
  3637  
  3638  	b.Reset()
  3639  	V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
  3640  	if b.String() != "hello, 42 world" {
  3641  		t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
  3642  	}
  3643  }
  3644  
  3645  func TestFuncArg(t *testing.T) {
  3646  	f1 := func(i int, f func(int) int) int { return f(i) }
  3647  	f2 := func(i int) int { return i + 1 }
  3648  	r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
  3649  	if r[0].Int() != 101 {
  3650  		t.Errorf("function returned %d, want 101", r[0].Int())
  3651  	}
  3652  }
  3653  
  3654  func TestStructArg(t *testing.T) {
  3655  	type padded struct {
  3656  		B string
  3657  		C int32
  3658  	}
  3659  	var (
  3660  		gotA  padded
  3661  		gotB  uint32
  3662  		wantA = padded{"3", 4}
  3663  		wantB = uint32(5)
  3664  	)
  3665  	f := func(a padded, b uint32) {
  3666  		gotA, gotB = a, b
  3667  	}
  3668  	ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
  3669  	if gotA != wantA || gotB != wantB {
  3670  		t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
  3671  	}
  3672  }
  3673  
  3674  var tagGetTests = []struct {
  3675  	Tag   StructTag
  3676  	Key   string
  3677  	Value string
  3678  }{
  3679  	{`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
  3680  	{`protobuf:"PB(1,2)"`, `foo`, ``},
  3681  	{`protobuf:"PB(1,2)"`, `rotobuf`, ``},
  3682  	{`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
  3683  	{`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
  3684  	{`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
  3685  	{`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
  3686  }
  3687  
  3688  func TestTagGet(t *testing.T) {
  3689  	for _, tt := range tagGetTests {
  3690  		if v := tt.Tag.Get(tt.Key); v != tt.Value {
  3691  			t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
  3692  		}
  3693  	}
  3694  }
  3695  
  3696  func TestBytes(t *testing.T) {
  3697  	shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
  3698  	shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
  3699  
  3700  	type S []byte
  3701  	x := S{1, 2, 3, 4}
  3702  	y := ValueOf(x).Bytes()
  3703  	if !bytes.Equal(x, y) {
  3704  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  3705  	}
  3706  	if &x[0] != &y[0] {
  3707  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  3708  	}
  3709  
  3710  	type A [4]byte
  3711  	a := A{1, 2, 3, 4}
  3712  	shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
  3713  	shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
  3714  	b := ValueOf(&a).Elem().Bytes()
  3715  	if !bytes.Equal(a[:], y) {
  3716  		t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
  3717  	}
  3718  	if &a[0] != &b[0] {
  3719  		t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
  3720  	}
  3721  
  3722  	// Per issue #24746, it was decided that Bytes can be called on byte slices
  3723  	// that normally cannot be converted from per Go language semantics.
  3724  	type B byte
  3725  	type SB []B
  3726  	type AB [4]B
  3727  	ValueOf([]B{1, 2, 3, 4}).Bytes()  // should not panic
  3728  	ValueOf(new([4]B)).Elem().Bytes() // should not panic
  3729  	ValueOf(SB{1, 2, 3, 4}).Bytes()   // should not panic
  3730  	ValueOf(new(AB)).Elem().Bytes()   // should not panic
  3731  }
  3732  
  3733  func TestSetBytes(t *testing.T) {
  3734  	type B []byte
  3735  	var x B
  3736  	y := []byte{1, 2, 3, 4}
  3737  	ValueOf(&x).Elem().SetBytes(y)
  3738  	if !bytes.Equal(x, y) {
  3739  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  3740  	}
  3741  	if &x[0] != &y[0] {
  3742  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  3743  	}
  3744  }
  3745  
  3746  type Private struct {
  3747  	x int
  3748  	y **int
  3749  	Z int
  3750  }
  3751  
  3752  func (p *Private) m() {
  3753  }
  3754  
  3755  type private struct {
  3756  	Z int
  3757  	z int
  3758  	S string
  3759  	A [1]Private
  3760  	T []Private
  3761  }
  3762  
  3763  func (p *private) P() {
  3764  }
  3765  
  3766  type Public struct {
  3767  	X int
  3768  	Y **int
  3769  	private
  3770  }
  3771  
  3772  func (p *Public) M() {
  3773  }
  3774  
  3775  func TestUnexported(t *testing.T) {
  3776  	var pub Public
  3777  	pub.S = "S"
  3778  	pub.T = pub.A[:]
  3779  	v := ValueOf(&pub)
  3780  	isValid(v.Elem().Field(0))
  3781  	isValid(v.Elem().Field(1))
  3782  	isValid(v.Elem().Field(2))
  3783  	isValid(v.Elem().FieldByName("X"))
  3784  	isValid(v.Elem().FieldByName("Y"))
  3785  	isValid(v.Elem().FieldByName("Z"))
  3786  	isValid(v.Type().Method(0).Func)
  3787  	m, _ := v.Type().MethodByName("M")
  3788  	isValid(m.Func)
  3789  	m, _ = v.Type().MethodByName("P")
  3790  	isValid(m.Func)
  3791  	isNonNil(v.Elem().Field(0).Interface())
  3792  	isNonNil(v.Elem().Field(1).Interface())
  3793  	isNonNil(v.Elem().Field(2).Field(2).Index(0))
  3794  	isNonNil(v.Elem().FieldByName("X").Interface())
  3795  	isNonNil(v.Elem().FieldByName("Y").Interface())
  3796  	isNonNil(v.Elem().FieldByName("Z").Interface())
  3797  	isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
  3798  	isNonNil(v.Type().Method(0).Func.Interface())
  3799  	m, _ = v.Type().MethodByName("P")
  3800  	isNonNil(m.Func.Interface())
  3801  
  3802  	var priv Private
  3803  	v = ValueOf(&priv)
  3804  	isValid(v.Elem().Field(0))
  3805  	isValid(v.Elem().Field(1))
  3806  	isValid(v.Elem().FieldByName("x"))
  3807  	isValid(v.Elem().FieldByName("y"))
  3808  	shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
  3809  	shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
  3810  	shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
  3811  	shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
  3812  	shouldPanic("Method", func() { v.Type().Method(0) })
  3813  }
  3814  
  3815  func TestSetPanic(t *testing.T) {
  3816  	ok := func(f func()) { f() }
  3817  	bad := func(f func()) { shouldPanic("Set", f) }
  3818  	clear := func(v Value) { v.Set(Zero(v.Type())) }
  3819  
  3820  	type t0 struct {
  3821  		W int
  3822  	}
  3823  
  3824  	type t1 struct {
  3825  		Y int
  3826  		t0
  3827  	}
  3828  
  3829  	type T2 struct {
  3830  		Z       int
  3831  		namedT0 t0
  3832  	}
  3833  
  3834  	type T struct {
  3835  		X int
  3836  		t1
  3837  		T2
  3838  		NamedT1 t1
  3839  		NamedT2 T2
  3840  		namedT1 t1
  3841  		namedT2 T2
  3842  	}
  3843  
  3844  	// not addressable
  3845  	v := ValueOf(T{})
  3846  	bad(func() { clear(v.Field(0)) })                   // .X
  3847  	bad(func() { clear(v.Field(1)) })                   // .t1
  3848  	bad(func() { clear(v.Field(1).Field(0)) })          // .t1.Y
  3849  	bad(func() { clear(v.Field(1).Field(1)) })          // .t1.t0
  3850  	bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
  3851  	bad(func() { clear(v.Field(2)) })                   // .T2
  3852  	bad(func() { clear(v.Field(2).Field(0)) })          // .T2.Z
  3853  	bad(func() { clear(v.Field(2).Field(1)) })          // .T2.namedT0
  3854  	bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
  3855  	bad(func() { clear(v.Field(3)) })                   // .NamedT1
  3856  	bad(func() { clear(v.Field(3).Field(0)) })          // .NamedT1.Y
  3857  	bad(func() { clear(v.Field(3).Field(1)) })          // .NamedT1.t0
  3858  	bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
  3859  	bad(func() { clear(v.Field(4)) })                   // .NamedT2
  3860  	bad(func() { clear(v.Field(4).Field(0)) })          // .NamedT2.Z
  3861  	bad(func() { clear(v.Field(4).Field(1)) })          // .NamedT2.namedT0
  3862  	bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
  3863  	bad(func() { clear(v.Field(5)) })                   // .namedT1
  3864  	bad(func() { clear(v.Field(5).Field(0)) })          // .namedT1.Y
  3865  	bad(func() { clear(v.Field(5).Field(1)) })          // .namedT1.t0
  3866  	bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
  3867  	bad(func() { clear(v.Field(6)) })                   // .namedT2
  3868  	bad(func() { clear(v.Field(6).Field(0)) })          // .namedT2.Z
  3869  	bad(func() { clear(v.Field(6).Field(1)) })          // .namedT2.namedT0
  3870  	bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
  3871  
  3872  	// addressable
  3873  	v = ValueOf(&T{}).Elem()
  3874  	ok(func() { clear(v.Field(0)) })                    // .X
  3875  	bad(func() { clear(v.Field(1)) })                   // .t1
  3876  	ok(func() { clear(v.Field(1).Field(0)) })           // .t1.Y
  3877  	bad(func() { clear(v.Field(1).Field(1)) })          // .t1.t0
  3878  	ok(func() { clear(v.Field(1).Field(1).Field(0)) })  // .t1.t0.W
  3879  	ok(func() { clear(v.Field(2)) })                    // .T2
  3880  	ok(func() { clear(v.Field(2).Field(0)) })           // .T2.Z
  3881  	bad(func() { clear(v.Field(2).Field(1)) })          // .T2.namedT0
  3882  	bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
  3883  	ok(func() { clear(v.Field(3)) })                    // .NamedT1
  3884  	ok(func() { clear(v.Field(3).Field(0)) })           // .NamedT1.Y
  3885  	bad(func() { clear(v.Field(3).Field(1)) })          // .NamedT1.t0
  3886  	ok(func() { clear(v.Field(3).Field(1).Field(0)) })  // .NamedT1.t0.W
  3887  	ok(func() { clear(v.Field(4)) })                    // .NamedT2
  3888  	ok(func() { clear(v.Field(4).Field(0)) })           // .NamedT2.Z
  3889  	bad(func() { clear(v.Field(4).Field(1)) })          // .NamedT2.namedT0
  3890  	bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
  3891  	bad(func() { clear(v.Field(5)) })                   // .namedT1
  3892  	bad(func() { clear(v.Field(5).Field(0)) })          // .namedT1.Y
  3893  	bad(func() { clear(v.Field(5).Field(1)) })          // .namedT1.t0
  3894  	bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
  3895  	bad(func() { clear(v.Field(6)) })                   // .namedT2
  3896  	bad(func() { clear(v.Field(6).Field(0)) })          // .namedT2.Z
  3897  	bad(func() { clear(v.Field(6).Field(1)) })          // .namedT2.namedT0
  3898  	bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
  3899  }
  3900  
  3901  type timp int
  3902  
  3903  func (t timp) W() {}
  3904  func (t timp) Y() {}
  3905  func (t timp) w() {}
  3906  func (t timp) y() {}
  3907  
  3908  func TestCallPanic(t *testing.T) {
  3909  	type t0 interface {
  3910  		W()
  3911  		w()
  3912  	}
  3913  	type T1 interface {
  3914  		Y()
  3915  		y()
  3916  	}
  3917  	type T2 struct {
  3918  		T1
  3919  		t0
  3920  	}
  3921  	type T struct {
  3922  		t0 // 0
  3923  		T1 // 1
  3924  
  3925  		NamedT0 t0 // 2
  3926  		NamedT1 T1 // 3
  3927  		NamedT2 T2 // 4
  3928  
  3929  		namedT0 t0 // 5
  3930  		namedT1 T1 // 6
  3931  		namedT2 T2 // 7
  3932  	}
  3933  	ok := func(f func()) { f() }
  3934  	badCall := func(f func()) { shouldPanic("Call", f) }
  3935  	badMethod := func(f func()) { shouldPanic("Method", f) }
  3936  	call := func(v Value) { v.Call(nil) }
  3937  
  3938  	i := timp(0)
  3939  	v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
  3940  	badCall(func() { call(v.Field(0).Method(0)) })          // .t0.W
  3941  	badCall(func() { call(v.Field(0).Elem().Method(0)) })   // .t0.W
  3942  	badCall(func() { call(v.Field(0).Method(1)) })          // .t0.w
  3943  	badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
  3944  	ok(func() { call(v.Field(1).Method(0)) })               // .T1.Y
  3945  	ok(func() { call(v.Field(1).Elem().Method(0)) })        // .T1.Y
  3946  	badCall(func() { call(v.Field(1).Method(1)) })          // .T1.y
  3947  	badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
  3948  
  3949  	ok(func() { call(v.Field(2).Method(0)) })               // .NamedT0.W
  3950  	ok(func() { call(v.Field(2).Elem().Method(0)) })        // .NamedT0.W
  3951  	badCall(func() { call(v.Field(2).Method(1)) })          // .NamedT0.w
  3952  	badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
  3953  
  3954  	ok(func() { call(v.Field(3).Method(0)) })               // .NamedT1.Y
  3955  	ok(func() { call(v.Field(3).Elem().Method(0)) })        // .NamedT1.Y
  3956  	badCall(func() { call(v.Field(3).Method(1)) })          // .NamedT1.y
  3957  	badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
  3958  
  3959  	ok(func() { call(v.Field(4).Field(0).Method(0)) })             // .NamedT2.T1.Y
  3960  	ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) })      // .NamedT2.T1.W
  3961  	badCall(func() { call(v.Field(4).Field(1).Method(0)) })        // .NamedT2.t0.W
  3962  	badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
  3963  
  3964  	badCall(func() { call(v.Field(5).Method(0)) })          // .namedT0.W
  3965  	badCall(func() { call(v.Field(5).Elem().Method(0)) })   // .namedT0.W
  3966  	badCall(func() { call(v.Field(5).Method(1)) })          // .namedT0.w
  3967  	badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
  3968  
  3969  	badCall(func() { call(v.Field(6).Method(0)) })        // .namedT1.Y
  3970  	badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
  3971  	badCall(func() { call(v.Field(6).Method(0)) })        // .namedT1.y
  3972  	badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
  3973  
  3974  	badCall(func() { call(v.Field(7).Field(0).Method(0)) })        // .namedT2.T1.Y
  3975  	badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
  3976  	badCall(func() { call(v.Field(7).Field(1).Method(0)) })        // .namedT2.t0.W
  3977  	badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
  3978  }
  3979  
  3980  func TestValuePanic(t *testing.T) {
  3981  	vo := ValueOf
  3982  	shouldPanic("reflect.Value.Addr of unaddressable value", func() { vo(0).Addr() })
  3983  	shouldPanic("call of reflect.Value.Bool on float64 Value", func() { vo(0.0).Bool() })
  3984  	shouldPanic("call of reflect.Value.Bytes on string Value", func() { vo("").Bytes() })
  3985  	shouldPanic("call of reflect.Value.Call on bool Value", func() { vo(true).Call(nil) })
  3986  	shouldPanic("call of reflect.Value.CallSlice on int Value", func() { vo(0).CallSlice(nil) })
  3987  	shouldPanic("call of reflect.Value.Close on string Value", func() { vo("").Close() })
  3988  	shouldPanic("call of reflect.Value.Complex on float64 Value", func() { vo(0.0).Complex() })
  3989  	shouldPanic("call of reflect.Value.Elem on bool Value", func() { vo(false).Elem() })
  3990  	shouldPanic("call of reflect.Value.Field on int Value", func() { vo(0).Field(0) })
  3991  	shouldPanic("call of reflect.Value.Float on string Value", func() { vo("").Float() })
  3992  	shouldPanic("call of reflect.Value.Index on float64 Value", func() { vo(0.0).Index(0) })
  3993  	shouldPanic("call of reflect.Value.Int on bool Value", func() { vo(false).Int() })
  3994  	shouldPanic("call of reflect.Value.IsNil on int Value", func() { vo(0).IsNil() })
  3995  	shouldPanic("call of reflect.Value.Len on bool Value", func() { vo(false).Len() })
  3996  	shouldPanic("call of reflect.Value.MapIndex on float64 Value", func() { vo(0.0).MapIndex(vo(0.0)) })
  3997  	shouldPanic("call of reflect.Value.MapKeys on string Value", func() { vo("").MapKeys() })
  3998  	shouldPanic("call of reflect.Value.MapRange on int Value", func() { vo(0).MapRange() })
  3999  	shouldPanic("call of reflect.Value.Method on zero Value", func() { vo(nil).Method(0) })
  4000  	shouldPanic("call of reflect.Value.NumField on string Value", func() { vo("").NumField() })
  4001  	shouldPanic("call of reflect.Value.NumMethod on zero Value", func() { vo(nil).NumMethod() })
  4002  	shouldPanic("call of reflect.Value.OverflowComplex on float64 Value", func() { vo(float64(0)).OverflowComplex(0) })
  4003  	shouldPanic("call of reflect.Value.OverflowFloat on int64 Value", func() { vo(int64(0)).OverflowFloat(0) })
  4004  	shouldPanic("call of reflect.Value.OverflowInt on uint64 Value", func() { vo(uint64(0)).OverflowInt(0) })
  4005  	shouldPanic("call of reflect.Value.OverflowUint on complex64 Value", func() { vo(complex64(0)).OverflowUint(0) })
  4006  	shouldPanic("call of reflect.Value.Recv on string Value", func() { vo("").Recv() })
  4007  	shouldPanic("call of reflect.Value.Send on bool Value", func() { vo(true).Send(vo(true)) })
  4008  	shouldPanic("value of type string is not assignable to type bool", func() { vo(new(bool)).Elem().Set(vo("")) })
  4009  	shouldPanic("call of reflect.Value.SetBool on string Value", func() { vo(new(string)).Elem().SetBool(false) })
  4010  	shouldPanic("reflect.Value.SetBytes using unaddressable value", func() { vo("").SetBytes(nil) })
  4011  	shouldPanic("call of reflect.Value.SetCap on string Value", func() { vo(new(string)).Elem().SetCap(0) })
  4012  	shouldPanic("call of reflect.Value.SetComplex on string Value", func() { vo(new(string)).Elem().SetComplex(0) })
  4013  	shouldPanic("call of reflect.Value.SetFloat on string Value", func() { vo(new(string)).Elem().SetFloat(0) })
  4014  	shouldPanic("call of reflect.Value.SetInt on string Value", func() { vo(new(string)).Elem().SetInt(0) })
  4015  	shouldPanic("call of reflect.Value.SetLen on string Value", func() { vo(new(string)).Elem().SetLen(0) })
  4016  	shouldPanic("call of reflect.Value.SetString on int Value", func() { vo(new(int)).Elem().SetString("") })
  4017  	shouldPanic("reflect.Value.SetUint using unaddressable value", func() { vo(0.0).SetUint(0) })
  4018  	shouldPanic("call of reflect.Value.Slice on bool Value", func() { vo(true).Slice(1, 2) })
  4019  	shouldPanic("call of reflect.Value.Slice3 on int Value", func() { vo(0).Slice3(1, 2, 3) })
  4020  	shouldPanic("call of reflect.Value.TryRecv on bool Value", func() { vo(true).TryRecv() })
  4021  	shouldPanic("call of reflect.Value.TrySend on string Value", func() { vo("").TrySend(vo("")) })
  4022  	shouldPanic("call of reflect.Value.Uint on float64 Value", func() { vo(0.0).Uint() })
  4023  }
  4024  
  4025  func shouldPanic(expect string, f func()) {
  4026  	defer func() {
  4027  		r := recover()
  4028  		if r == nil {
  4029  			panic("did not panic")
  4030  		}
  4031  		if expect != "" {
  4032  			var s string
  4033  			switch r := r.(type) {
  4034  			case string:
  4035  				s = r
  4036  			case *ValueError:
  4037  				s = r.Error()
  4038  			default:
  4039  				panic(fmt.Sprintf("panicked with unexpected type %T", r))
  4040  			}
  4041  			if !strings.HasPrefix(s, "reflect") {
  4042  				panic(`panic string does not start with "reflect": ` + s)
  4043  			}
  4044  			if !strings.Contains(s, expect) {
  4045  				panic(`panic string does not contain "` + expect + `": ` + s)
  4046  			}
  4047  		}
  4048  	}()
  4049  	f()
  4050  }
  4051  
  4052  func isNonNil(x any) {
  4053  	if x == nil {
  4054  		panic("nil interface")
  4055  	}
  4056  }
  4057  
  4058  func isValid(v Value) {
  4059  	if !v.IsValid() {
  4060  		panic("zero Value")
  4061  	}
  4062  }
  4063  
  4064  func TestAlias(t *testing.T) {
  4065  	x := string("hello")
  4066  	v := ValueOf(&x).Elem()
  4067  	oldvalue := v.Interface()
  4068  	v.SetString("world")
  4069  	newvalue := v.Interface()
  4070  
  4071  	if oldvalue != "hello" || newvalue != "world" {
  4072  		t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
  4073  	}
  4074  }
  4075  
  4076  var V = ValueOf
  4077  
  4078  func EmptyInterfaceV(x any) Value {
  4079  	return ValueOf(&x).Elem()
  4080  }
  4081  
  4082  func ReaderV(x io.Reader) Value {
  4083  	return ValueOf(&x).Elem()
  4084  }
  4085  
  4086  func ReadWriterV(x io.ReadWriter) Value {
  4087  	return ValueOf(&x).Elem()
  4088  }
  4089  
  4090  type Empty struct{}
  4091  type MyStruct struct {
  4092  	x int `some:"tag"`
  4093  }
  4094  type MyStruct1 struct {
  4095  	x struct {
  4096  		int `some:"bar"`
  4097  	}
  4098  }
  4099  type MyStruct2 struct {
  4100  	x struct {
  4101  		int `some:"foo"`
  4102  	}
  4103  }
  4104  type MyString string
  4105  type MyBytes []byte
  4106  type MyBytesArrayPtr0 *[0]byte
  4107  type MyBytesArrayPtr *[4]byte
  4108  type MyBytesArray0 [0]byte
  4109  type MyBytesArray [4]byte
  4110  type MyRunes []int32
  4111  type MyFunc func()
  4112  type MyByte byte
  4113  
  4114  type IntChan chan int
  4115  type IntChanRecv <-chan int
  4116  type IntChanSend chan<- int
  4117  type BytesChan chan []byte
  4118  type BytesChanRecv <-chan []byte
  4119  type BytesChanSend chan<- []byte
  4120  
  4121  var convertTests = []struct {
  4122  	in  Value
  4123  	out Value
  4124  }{
  4125  	// numbers
  4126  	/*
  4127  		Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
  4128  
  4129  		package main
  4130  
  4131  		import "fmt"
  4132  
  4133  		var numbers = []string{
  4134  			"int8", "uint8", "int16", "uint16",
  4135  			"int32", "uint32", "int64", "uint64",
  4136  			"int", "uint", "uintptr",
  4137  			"float32", "float64",
  4138  		}
  4139  
  4140  		func main() {
  4141  			// all pairs but in an unusual order,
  4142  			// to emit all the int8, uint8 cases
  4143  			// before n grows too big.
  4144  			n := 1
  4145  			for i, f := range numbers {
  4146  				for _, g := range numbers[i:] {
  4147  					fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
  4148  					n++
  4149  					if f != g {
  4150  						fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
  4151  						n++
  4152  					}
  4153  				}
  4154  			}
  4155  		}
  4156  	*/
  4157  	{V(int8(1)), V(int8(1))},
  4158  	{V(int8(2)), V(uint8(2))},
  4159  	{V(uint8(3)), V(int8(3))},
  4160  	{V(int8(4)), V(int16(4))},
  4161  	{V(int16(5)), V(int8(5))},
  4162  	{V(int8(6)), V(uint16(6))},
  4163  	{V(uint16(7)), V(int8(7))},
  4164  	{V(int8(8)), V(int32(8))},
  4165  	{V(int32(9)), V(int8(9))},
  4166  	{V(int8(10)), V(uint32(10))},
  4167  	{V(uint32(11)), V(int8(11))},
  4168  	{V(int8(12)), V(int64(12))},
  4169  	{V(int64(13)), V(int8(13))},
  4170  	{V(int8(14)), V(uint64(14))},
  4171  	{V(uint64(15)), V(int8(15))},
  4172  	{V(int8(16)), V(int(16))},
  4173  	{V(int(17)), V(int8(17))},
  4174  	{V(int8(18)), V(uint(18))},
  4175  	{V(uint(19)), V(int8(19))},
  4176  	{V(int8(20)), V(uintptr(20))},
  4177  	{V(uintptr(21)), V(int8(21))},
  4178  	{V(int8(22)), V(float32(22))},
  4179  	{V(float32(23)), V(int8(23))},
  4180  	{V(int8(24)), V(float64(24))},
  4181  	{V(float64(25)), V(int8(25))},
  4182  	{V(uint8(26)), V(uint8(26))},
  4183  	{V(uint8(27)), V(int16(27))},
  4184  	{V(int16(28)), V(uint8(28))},
  4185  	{V(uint8(29)), V(uint16(29))},
  4186  	{V(uint16(30)), V(uint8(30))},
  4187  	{V(uint8(31)), V(int32(31))},
  4188  	{V(int32(32)), V(uint8(32))},
  4189  	{V(uint8(33)), V(uint32(33))},
  4190  	{V(uint32(34)), V(uint8(34))},
  4191  	{V(uint8(35)), V(int64(35))},
  4192  	{V(int64(36)), V(uint8(36))},
  4193  	{V(uint8(37)), V(uint64(37))},
  4194  	{V(uint64(38)), V(uint8(38))},
  4195  	{V(uint8(39)), V(int(39))},
  4196  	{V(int(40)), V(uint8(40))},
  4197  	{V(uint8(41)), V(uint(41))},
  4198  	{V(uint(42)), V(uint8(42))},
  4199  	{V(uint8(43)), V(uintptr(43))},
  4200  	{V(uintptr(44)), V(uint8(44))},
  4201  	{V(uint8(45)), V(float32(45))},
  4202  	{V(float32(46)), V(uint8(46))},
  4203  	{V(uint8(47)), V(float64(47))},
  4204  	{V(float64(48)), V(uint8(48))},
  4205  	{V(int16(49)), V(int16(49))},
  4206  	{V(int16(50)), V(uint16(50))},
  4207  	{V(uint16(51)), V(int16(51))},
  4208  	{V(int16(52)), V(int32(52))},
  4209  	{V(int32(53)), V(int16(53))},
  4210  	{V(int16(54)), V(uint32(54))},
  4211  	{V(uint32(55)), V(int16(55))},
  4212  	{V(int16(56)), V(int64(56))},
  4213  	{V(int64(57)), V(int16(57))},
  4214  	{V(int16(58)), V(uint64(58))},
  4215  	{V(uint64(59)), V(int16(59))},
  4216  	{V(int16(60)), V(int(60))},
  4217  	{V(int(61)), V(int16(61))},
  4218  	{V(int16(62)), V(uint(62))},
  4219  	{V(uint(63)), V(int16(63))},
  4220  	{V(int16(64)), V(uintptr(64))},
  4221  	{V(uintptr(65)), V(int16(65))},
  4222  	{V(int16(66)), V(float32(66))},
  4223  	{V(float32(67)), V(int16(67))},
  4224  	{V(int16(68)), V(float64(68))},
  4225  	{V(float64(69)), V(int16(69))},
  4226  	{V(uint16(70)), V(uint16(70))},
  4227  	{V(uint16(71)), V(int32(71))},
  4228  	{V(int32(72)), V(uint16(72))},
  4229  	{V(uint16(73)), V(uint32(73))},
  4230  	{V(uint32(74)), V(uint16(74))},
  4231  	{V(uint16(75)), V(int64(75))},
  4232  	{V(int64(76)), V(uint16(76))},
  4233  	{V(uint16(77)), V(uint64(77))},
  4234  	{V(uint64(78)), V(uint16(78))},
  4235  	{V(uint16(79)), V(int(79))},
  4236  	{V(int(80)), V(uint16(80))},
  4237  	{V(uint16(81)), V(uint(81))},
  4238  	{V(uint(82)), V(uint16(82))},
  4239  	{V(uint16(83)), V(uintptr(83))},
  4240  	{V(uintptr(84)), V(uint16(84))},
  4241  	{V(uint16(85)), V(float32(85))},
  4242  	{V(float32(86)), V(uint16(86))},
  4243  	{V(uint16(87)), V(float64(87))},
  4244  	{V(float64(88)), V(uint16(88))},
  4245  	{V(int32(89)), V(int32(89))},
  4246  	{V(int32(90)), V(uint32(90))},
  4247  	{V(uint32(91)), V(int32(91))},
  4248  	{V(int32(92)), V(int64(92))},
  4249  	{V(int64(93)), V(int32(93))},
  4250  	{V(int32(94)), V(uint64(94))},
  4251  	{V(uint64(95)), V(int32(95))},
  4252  	{V(int32(96)), V(int(96))},
  4253  	{V(int(97)), V(int32(97))},
  4254  	{V(int32(98)), V(uint(98))},
  4255  	{V(uint(99)), V(int32(99))},
  4256  	{V(int32(100)), V(uintptr(100))},
  4257  	{V(uintptr(101)), V(int32(101))},
  4258  	{V(int32(102)), V(float32(102))},
  4259  	{V(float32(103)), V(int32(103))},
  4260  	{V(int32(104)), V(float64(104))},
  4261  	{V(float64(105)), V(int32(105))},
  4262  	{V(uint32(106)), V(uint32(106))},
  4263  	{V(uint32(107)), V(int64(107))},
  4264  	{V(int64(108)), V(uint32(108))},
  4265  	{V(uint32(109)), V(uint64(109))},
  4266  	{V(uint64(110)), V(uint32(110))},
  4267  	{V(uint32(111)), V(int(111))},
  4268  	{V(int(112)), V(uint32(112))},
  4269  	{V(uint32(113)), V(uint(113))},
  4270  	{V(uint(114)), V(uint32(114))},
  4271  	{V(uint32(115)), V(uintptr(115))},
  4272  	{V(uintptr(116)), V(uint32(116))},
  4273  	{V(uint32(117)), V(float32(117))},
  4274  	{V(float32(118)), V(uint32(118))},
  4275  	{V(uint32(119)), V(float64(119))},
  4276  	{V(float64(120)), V(uint32(120))},
  4277  	{V(int64(121)), V(int64(121))},
  4278  	{V(int64(122)), V(uint64(122))},
  4279  	{V(uint64(123)), V(int64(123))},
  4280  	{V(int64(124)), V(int(124))},
  4281  	{V(int(125)), V(int64(125))},
  4282  	{V(int64(126)), V(uint(126))},
  4283  	{V(uint(127)), V(int64(127))},
  4284  	{V(int64(128)), V(uintptr(128))},
  4285  	{V(uintptr(129)), V(int64(129))},
  4286  	{V(int64(130)), V(float32(130))},
  4287  	{V(float32(131)), V(int64(131))},
  4288  	{V(int64(132)), V(float64(132))},
  4289  	{V(float64(133)), V(int64(133))},
  4290  	{V(uint64(134)), V(uint64(134))},
  4291  	{V(uint64(135)), V(int(135))},
  4292  	{V(int(136)), V(uint64(136))},
  4293  	{V(uint64(137)), V(uint(137))},
  4294  	{V(uint(138)), V(uint64(138))},
  4295  	{V(uint64(139)), V(uintptr(139))},
  4296  	{V(uintptr(140)), V(uint64(140))},
  4297  	{V(uint64(141)), V(float32(141))},
  4298  	{V(float32(142)), V(uint64(142))},
  4299  	{V(uint64(143)), V(float64(143))},
  4300  	{V(float64(144)), V(uint64(144))},
  4301  	{V(int(145)), V(int(145))},
  4302  	{V(int(146)), V(uint(146))},
  4303  	{V(uint(147)), V(int(147))},
  4304  	{V(int(148)), V(uintptr(148))},
  4305  	{V(uintptr(149)), V(int(149))},
  4306  	{V(int(150)), V(float32(150))},
  4307  	{V(float32(151)), V(int(151))},
  4308  	{V(int(152)), V(float64(152))},
  4309  	{V(float64(153)), V(int(153))},
  4310  	{V(uint(154)), V(uint(154))},
  4311  	{V(uint(155)), V(uintptr(155))},
  4312  	{V(uintptr(156)), V(uint(156))},
  4313  	{V(uint(157)), V(float32(157))},
  4314  	{V(float32(158)), V(uint(158))},
  4315  	{V(uint(159)), V(float64(159))},
  4316  	{V(float64(160)), V(uint(160))},
  4317  	{V(uintptr(161)), V(uintptr(161))},
  4318  	{V(uintptr(162)), V(float32(162))},
  4319  	{V(float32(163)), V(uintptr(163))},
  4320  	{V(uintptr(164)), V(float64(164))},
  4321  	{V(float64(165)), V(uintptr(165))},
  4322  	{V(float32(166)), V(float32(166))},
  4323  	{V(float32(167)), V(float64(167))},
  4324  	{V(float64(168)), V(float32(168))},
  4325  	{V(float64(169)), V(float64(169))},
  4326  
  4327  	// truncation
  4328  	{V(float64(1.5)), V(int(1))},
  4329  
  4330  	// complex
  4331  	{V(complex64(1i)), V(complex64(1i))},
  4332  	{V(complex64(2i)), V(complex128(2i))},
  4333  	{V(complex128(3i)), V(complex64(3i))},
  4334  	{V(complex128(4i)), V(complex128(4i))},
  4335  
  4336  	// string
  4337  	{V(string("hello")), V(string("hello"))},
  4338  	{V(string("bytes1")), V([]byte("bytes1"))},
  4339  	{V([]byte("bytes2")), V(string("bytes2"))},
  4340  	{V([]byte("bytes3")), V([]byte("bytes3"))},
  4341  	{V(string("runes♝")), V([]rune("runes♝"))},
  4342  	{V([]rune("runes♕")), V(string("runes♕"))},
  4343  	{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  4344  	{V(int('a')), V(string("a"))},
  4345  	{V(int8('a')), V(string("a"))},
  4346  	{V(int16('a')), V(string("a"))},
  4347  	{V(int32('a')), V(string("a"))},
  4348  	{V(int64('a')), V(string("a"))},
  4349  	{V(uint('a')), V(string("a"))},
  4350  	{V(uint8('a')), V(string("a"))},
  4351  	{V(uint16('a')), V(string("a"))},
  4352  	{V(uint32('a')), V(string("a"))},
  4353  	{V(uint64('a')), V(string("a"))},
  4354  	{V(uintptr('a')), V(string("a"))},
  4355  	{V(int(-1)), V(string("\uFFFD"))},
  4356  	{V(int8(-2)), V(string("\uFFFD"))},
  4357  	{V(int16(-3)), V(string("\uFFFD"))},
  4358  	{V(int32(-4)), V(string("\uFFFD"))},
  4359  	{V(int64(-5)), V(string("\uFFFD"))},
  4360  	{V(int64(-1 << 32)), V(string("\uFFFD"))},
  4361  	{V(int64(1 << 32)), V(string("\uFFFD"))},
  4362  	{V(uint(0x110001)), V(string("\uFFFD"))},
  4363  	{V(uint32(0x110002)), V(string("\uFFFD"))},
  4364  	{V(uint64(0x110003)), V(string("\uFFFD"))},
  4365  	{V(uint64(1 << 32)), V(string("\uFFFD"))},
  4366  	{V(uintptr(0x110004)), V(string("\uFFFD"))},
  4367  
  4368  	// named string
  4369  	{V(MyString("hello")), V(string("hello"))},
  4370  	{V(string("hello")), V(MyString("hello"))},
  4371  	{V(string("hello")), V(string("hello"))},
  4372  	{V(MyString("hello")), V(MyString("hello"))},
  4373  	{V(MyString("bytes1")), V([]byte("bytes1"))},
  4374  	{V([]byte("bytes2")), V(MyString("bytes2"))},
  4375  	{V([]byte("bytes3")), V([]byte("bytes3"))},
  4376  	{V(MyString("runes♝")), V([]rune("runes♝"))},
  4377  	{V([]rune("runes♕")), V(MyString("runes♕"))},
  4378  	{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  4379  	{V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  4380  	{V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  4381  	{V(int('a')), V(MyString("a"))},
  4382  	{V(int8('a')), V(MyString("a"))},
  4383  	{V(int16('a')), V(MyString("a"))},
  4384  	{V(int32('a')), V(MyString("a"))},
  4385  	{V(int64('a')), V(MyString("a"))},
  4386  	{V(uint('a')), V(MyString("a"))},
  4387  	{V(uint8('a')), V(MyString("a"))},
  4388  	{V(uint16('a')), V(MyString("a"))},
  4389  	{V(uint32('a')), V(MyString("a"))},
  4390  	{V(uint64('a')), V(MyString("a"))},
  4391  	{V(uintptr('a')), V(MyString("a"))},
  4392  	{V(int(-1)), V(MyString("\uFFFD"))},
  4393  	{V(int8(-2)), V(MyString("\uFFFD"))},
  4394  	{V(int16(-3)), V(MyString("\uFFFD"))},
  4395  	{V(int32(-4)), V(MyString("\uFFFD"))},
  4396  	{V(int64(-5)), V(MyString("\uFFFD"))},
  4397  	{V(uint(0x110001)), V(MyString("\uFFFD"))},
  4398  	{V(uint32(0x110002)), V(MyString("\uFFFD"))},
  4399  	{V(uint64(0x110003)), V(MyString("\uFFFD"))},
  4400  	{V(uintptr(0x110004)), V(MyString("\uFFFD"))},
  4401  
  4402  	// named []byte
  4403  	{V(string("bytes1")), V(MyBytes("bytes1"))},
  4404  	{V(MyBytes("bytes2")), V(string("bytes2"))},
  4405  	{V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
  4406  	{V(MyString("bytes1")), V(MyBytes("bytes1"))},
  4407  	{V(MyBytes("bytes2")), V(MyString("bytes2"))},
  4408  
  4409  	// named []rune
  4410  	{V(string("runes♝")), V(MyRunes("runes♝"))},
  4411  	{V(MyRunes("runes♕")), V(string("runes♕"))},
  4412  	{V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  4413  	{V(MyString("runes♝")), V(MyRunes("runes♝"))},
  4414  	{V(MyRunes("runes♕")), V(MyString("runes♕"))},
  4415  
  4416  	// slice to array pointer
  4417  	{V([]byte(nil)), V((*[0]byte)(nil))},
  4418  	{V([]byte{}), V(new([0]byte))},
  4419  	{V([]byte{7}), V(&[1]byte{7})},
  4420  	{V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
  4421  	{V(MyBytes([]byte{})), V(new([0]byte))},
  4422  	{V(MyBytes([]byte{9})), V(&[1]byte{9})},
  4423  	{V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
  4424  	{V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
  4425  	{V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
  4426  	{V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
  4427  	{V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
  4428  
  4429  	{V([]byte(nil)), V((*MyBytesArray0)(nil))},
  4430  	{V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
  4431  	{V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
  4432  	{V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
  4433  	{V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
  4434  	{V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
  4435  	{V(new([0]byte)), V(new(MyBytesArray0))},
  4436  	{V(new(MyBytesArray0)), V(new([0]byte))},
  4437  	{V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
  4438  	{V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
  4439  
  4440  	// named types and equal underlying types
  4441  	{V(new(int)), V(new(integer))},
  4442  	{V(new(integer)), V(new(int))},
  4443  	{V(Empty{}), V(struct{}{})},
  4444  	{V(new(Empty)), V(new(struct{}))},
  4445  	{V(struct{}{}), V(Empty{})},
  4446  	{V(new(struct{})), V(new(Empty))},
  4447  	{V(Empty{}), V(Empty{})},
  4448  	{V(MyBytes{}), V([]byte{})},
  4449  	{V([]byte{}), V(MyBytes{})},
  4450  	{V((func())(nil)), V(MyFunc(nil))},
  4451  	{V((MyFunc)(nil)), V((func())(nil))},
  4452  
  4453  	// structs with different tags
  4454  	{V(struct {
  4455  		x int `some:"foo"`
  4456  	}{}), V(struct {
  4457  		x int `some:"bar"`
  4458  	}{})},
  4459  
  4460  	{V(struct {
  4461  		x int `some:"bar"`
  4462  	}{}), V(struct {
  4463  		x int `some:"foo"`
  4464  	}{})},
  4465  
  4466  	{V(MyStruct{}), V(struct {
  4467  		x int `some:"foo"`
  4468  	}{})},
  4469  
  4470  	{V(struct {
  4471  		x int `some:"foo"`
  4472  	}{}), V(MyStruct{})},
  4473  
  4474  	{V(MyStruct{}), V(struct {
  4475  		x int `some:"bar"`
  4476  	}{})},
  4477  
  4478  	{V(struct {
  4479  		x int `some:"bar"`
  4480  	}{}), V(MyStruct{})},
  4481  
  4482  	{V(MyStruct1{}), V(MyStruct2{})},
  4483  	{V(MyStruct2{}), V(MyStruct1{})},
  4484  
  4485  	// can convert *byte and *MyByte
  4486  	{V((*byte)(nil)), V((*MyByte)(nil))},
  4487  	{V((*MyByte)(nil)), V((*byte)(nil))},
  4488  
  4489  	// cannot convert mismatched array sizes
  4490  	{V([2]byte{}), V([2]byte{})},
  4491  	{V([3]byte{}), V([3]byte{})},
  4492  
  4493  	// cannot convert other instances
  4494  	{V((**byte)(nil)), V((**byte)(nil))},
  4495  	{V((**MyByte)(nil)), V((**MyByte)(nil))},
  4496  	{V((chan byte)(nil)), V((chan byte)(nil))},
  4497  	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  4498  	{V(([]byte)(nil)), V(([]byte)(nil))},
  4499  	{V(([]MyByte)(nil)), V(([]MyByte)(nil))},
  4500  	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  4501  	{V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
  4502  	{V((map[byte]int)(nil)), V((map[byte]int)(nil))},
  4503  	{V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
  4504  	{V([2]byte{}), V([2]byte{})},
  4505  	{V([2]MyByte{}), V([2]MyByte{})},
  4506  
  4507  	// other
  4508  	{V((***int)(nil)), V((***int)(nil))},
  4509  	{V((***byte)(nil)), V((***byte)(nil))},
  4510  	{V((***int32)(nil)), V((***int32)(nil))},
  4511  	{V((***int64)(nil)), V((***int64)(nil))},
  4512  	{V((chan byte)(nil)), V((chan byte)(nil))},
  4513  	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  4514  	{V((map[int]bool)(nil)), V((map[int]bool)(nil))},
  4515  	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  4516  	{V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
  4517  	{V([]uint(nil)), V([]uint(nil))},
  4518  	{V([]int(nil)), V([]int(nil))},
  4519  	{V(new(any)), V(new(any))},
  4520  	{V(new(io.Reader)), V(new(io.Reader))},
  4521  	{V(new(io.Writer)), V(new(io.Writer))},
  4522  
  4523  	// channels
  4524  	{V(IntChan(nil)), V((chan<- int)(nil))},
  4525  	{V(IntChan(nil)), V((<-chan int)(nil))},
  4526  	{V((chan int)(nil)), V(IntChanRecv(nil))},
  4527  	{V((chan int)(nil)), V(IntChanSend(nil))},
  4528  	{V(IntChanRecv(nil)), V((<-chan int)(nil))},
  4529  	{V((<-chan int)(nil)), V(IntChanRecv(nil))},
  4530  	{V(IntChanSend(nil)), V((chan<- int)(nil))},
  4531  	{V((chan<- int)(nil)), V(IntChanSend(nil))},
  4532  	{V(IntChan(nil)), V((chan int)(nil))},
  4533  	{V((chan int)(nil)), V(IntChan(nil))},
  4534  	{V((chan int)(nil)), V((<-chan int)(nil))},
  4535  	{V((chan int)(nil)), V((chan<- int)(nil))},
  4536  	{V(BytesChan(nil)), V((chan<- []byte)(nil))},
  4537  	{V(BytesChan(nil)), V((<-chan []byte)(nil))},
  4538  	{V((chan []byte)(nil)), V(BytesChanRecv(nil))},
  4539  	{V((chan []byte)(nil)), V(BytesChanSend(nil))},
  4540  	{V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
  4541  	{V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
  4542  	{V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
  4543  	{V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
  4544  	{V(BytesChan(nil)), V((chan []byte)(nil))},
  4545  	{V((chan []byte)(nil)), V(BytesChan(nil))},
  4546  	{V((chan []byte)(nil)), V((<-chan []byte)(nil))},
  4547  	{V((chan []byte)(nil)), V((chan<- []byte)(nil))},
  4548  
  4549  	// cannot convert other instances (channels)
  4550  	{V(IntChan(nil)), V(IntChan(nil))},
  4551  	{V(IntChanRecv(nil)), V(IntChanRecv(nil))},
  4552  	{V(IntChanSend(nil)), V(IntChanSend(nil))},
  4553  	{V(BytesChan(nil)), V(BytesChan(nil))},
  4554  	{V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
  4555  	{V(BytesChanSend(nil)), V(BytesChanSend(nil))},
  4556  
  4557  	// interfaces
  4558  	{V(int(1)), EmptyInterfaceV(int(1))},
  4559  	{V(string("hello")), EmptyInterfaceV(string("hello"))},
  4560  	{V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  4561  	{ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  4562  	{V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
  4563  }
  4564  
  4565  func TestConvert(t *testing.T) {
  4566  	canConvert := map[[2]Type]bool{}
  4567  	all := map[Type]bool{}
  4568  
  4569  	for _, tt := range convertTests {
  4570  		t1 := tt.in.Type()
  4571  		if !t1.ConvertibleTo(t1) {
  4572  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
  4573  			continue
  4574  		}
  4575  
  4576  		t2 := tt.out.Type()
  4577  		if !t1.ConvertibleTo(t2) {
  4578  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
  4579  			continue
  4580  		}
  4581  
  4582  		all[t1] = true
  4583  		all[t2] = true
  4584  		canConvert[[2]Type{t1, t2}] = true
  4585  
  4586  		// vout1 represents the in value converted to the in type.
  4587  		v1 := tt.in
  4588  		if !v1.CanConvert(t1) {
  4589  			t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
  4590  		}
  4591  		vout1 := v1.Convert(t1)
  4592  		out1 := vout1.Interface()
  4593  		if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
  4594  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
  4595  		}
  4596  
  4597  		// vout2 represents the in value converted to the out type.
  4598  		if !v1.CanConvert(t2) {
  4599  			t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
  4600  		}
  4601  		vout2 := v1.Convert(t2)
  4602  		out2 := vout2.Interface()
  4603  		if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
  4604  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
  4605  		}
  4606  		if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
  4607  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
  4608  		}
  4609  
  4610  		// vout3 represents a new value of the out type, set to vout2.  This makes
  4611  		// sure the converted value vout2 is really usable as a regular value.
  4612  		vout3 := New(t2).Elem()
  4613  		vout3.Set(vout2)
  4614  		out3 := vout3.Interface()
  4615  		if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
  4616  			t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
  4617  		}
  4618  
  4619  		if IsRO(v1) {
  4620  			t.Errorf("table entry %v is RO, should not be", v1)
  4621  		}
  4622  		if IsRO(vout1) {
  4623  			t.Errorf("self-conversion output %v is RO, should not be", vout1)
  4624  		}
  4625  		if IsRO(vout2) {
  4626  			t.Errorf("conversion output %v is RO, should not be", vout2)
  4627  		}
  4628  		if IsRO(vout3) {
  4629  			t.Errorf("set(conversion output) %v is RO, should not be", vout3)
  4630  		}
  4631  		if !IsRO(MakeRO(v1).Convert(t1)) {
  4632  			t.Errorf("RO self-conversion output %v is not RO, should be", v1)
  4633  		}
  4634  		if !IsRO(MakeRO(v1).Convert(t2)) {
  4635  			t.Errorf("RO conversion output %v is not RO, should be", v1)
  4636  		}
  4637  	}
  4638  
  4639  	// Assume that of all the types we saw during the tests,
  4640  	// if there wasn't an explicit entry for a conversion between
  4641  	// a pair of types, then it's not to be allowed. This checks for
  4642  	// things like 'int64' converting to '*int'.
  4643  	for t1 := range all {
  4644  		for t2 := range all {
  4645  			expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
  4646  			if ok := t1.ConvertibleTo(t2); ok != expectOK {
  4647  				t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
  4648  			}
  4649  		}
  4650  	}
  4651  }
  4652  
  4653  func TestConvertPanic(t *testing.T) {
  4654  	s := make([]byte, 4)
  4655  	p := new([8]byte)
  4656  	v := ValueOf(s)
  4657  	pt := TypeOf(p)
  4658  	if !v.Type().ConvertibleTo(pt) {
  4659  		t.Errorf("[]byte should be convertible to *[8]byte")
  4660  	}
  4661  	if v.CanConvert(pt) {
  4662  		t.Errorf("slice with length 4 should not be convertible to *[8]byte")
  4663  	}
  4664  	shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
  4665  		_ = v.Convert(pt)
  4666  	})
  4667  }
  4668  
  4669  var gFloat32 float32
  4670  
  4671  const snan uint32 = 0x7f800001
  4672  
  4673  func TestConvertNaNs(t *testing.T) {
  4674  	// Test to see if a store followed by a load of a signaling NaN
  4675  	// maintains the signaling bit. (This used to fail on the 387 port.)
  4676  	gFloat32 = math.Float32frombits(snan)
  4677  	runtime.Gosched() // make sure we don't optimize the store/load away
  4678  	if got := math.Float32bits(gFloat32); got != snan {
  4679  		t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
  4680  	}
  4681  	// Test reflect's conversion between float32s. See issue 36400.
  4682  	type myFloat32 float32
  4683  	x := V(myFloat32(math.Float32frombits(snan)))
  4684  	y := x.Convert(TypeOf(float32(0)))
  4685  	z := y.Interface().(float32)
  4686  	if got := math.Float32bits(z); got != snan {
  4687  		t.Errorf("signaling nan conversion got %x, want %x", got, snan)
  4688  	}
  4689  }
  4690  
  4691  type ComparableStruct struct {
  4692  	X int
  4693  }
  4694  
  4695  type NonComparableStruct struct {
  4696  	X int
  4697  	Y map[string]int
  4698  }
  4699  
  4700  var comparableTests = []struct {
  4701  	typ Type
  4702  	ok  bool
  4703  }{
  4704  	{TypeOf(1), true},
  4705  	{TypeOf("hello"), true},
  4706  	{TypeOf(new(byte)), true},
  4707  	{TypeOf((func())(nil)), false},
  4708  	{TypeOf([]byte{}), false},
  4709  	{TypeOf(map[string]int{}), false},
  4710  	{TypeOf(make(chan int)), true},
  4711  	{TypeOf(1.5), true},
  4712  	{TypeOf(false), true},
  4713  	{TypeOf(1i), true},
  4714  	{TypeOf(ComparableStruct{}), true},
  4715  	{TypeOf(NonComparableStruct{}), false},
  4716  	{TypeOf([10]map[string]int{}), false},
  4717  	{TypeOf([10]string{}), true},
  4718  	{TypeOf(new(any)).Elem(), true},
  4719  }
  4720  
  4721  func TestComparable(t *testing.T) {
  4722  	for _, tt := range comparableTests {
  4723  		if ok := tt.typ.Comparable(); ok != tt.ok {
  4724  			t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
  4725  		}
  4726  	}
  4727  }
  4728  
  4729  func TestOverflow(t *testing.T) {
  4730  	if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
  4731  		t.Errorf("%v wrongly overflows float64", 1e300)
  4732  	}
  4733  
  4734  	maxFloat32 := float64((1<<24 - 1) << (127 - 23))
  4735  	if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
  4736  		t.Errorf("%v wrongly overflows float32", maxFloat32)
  4737  	}
  4738  	ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
  4739  	if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
  4740  		t.Errorf("%v should overflow float32", ovfFloat32)
  4741  	}
  4742  	if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
  4743  		t.Errorf("%v should overflow float32", -ovfFloat32)
  4744  	}
  4745  
  4746  	maxInt32 := int64(0x7fffffff)
  4747  	if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
  4748  		t.Errorf("%v wrongly overflows int32", maxInt32)
  4749  	}
  4750  	if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
  4751  		t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
  4752  	}
  4753  	ovfInt32 := int64(1 << 31)
  4754  	if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
  4755  		t.Errorf("%v should overflow int32", ovfInt32)
  4756  	}
  4757  
  4758  	maxUint32 := uint64(0xffffffff)
  4759  	if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
  4760  		t.Errorf("%v wrongly overflows uint32", maxUint32)
  4761  	}
  4762  	ovfUint32 := uint64(1 << 32)
  4763  	if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
  4764  		t.Errorf("%v should overflow uint32", ovfUint32)
  4765  	}
  4766  }
  4767  
  4768  func checkSameType(t *testing.T, x Type, y any) {
  4769  	if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
  4770  		t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
  4771  	}
  4772  }
  4773  
  4774  func TestArrayOf(t *testing.T) {
  4775  	// check construction and use of type not in binary
  4776  	tests := []struct {
  4777  		n          int
  4778  		value      func(i int) any
  4779  		comparable bool
  4780  		want       string
  4781  	}{
  4782  		{
  4783  			n:          0,
  4784  			value:      func(i int) any { type Tint int; return Tint(i) },
  4785  			comparable: true,
  4786  			want:       "[]",
  4787  		},
  4788  		{
  4789  			n:          10,
  4790  			value:      func(i int) any { type Tint int; return Tint(i) },
  4791  			comparable: true,
  4792  			want:       "[0 1 2 3 4 5 6 7 8 9]",
  4793  		},
  4794  		{
  4795  			n:          10,
  4796  			value:      func(i int) any { type Tfloat float64; return Tfloat(i) },
  4797  			comparable: true,
  4798  			want:       "[0 1 2 3 4 5 6 7 8 9]",
  4799  		},
  4800  		{
  4801  			n:          10,
  4802  			value:      func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
  4803  			comparable: true,
  4804  			want:       "[0 1 2 3 4 5 6 7 8 9]",
  4805  		},
  4806  		{
  4807  			n:          10,
  4808  			value:      func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
  4809  			comparable: true,
  4810  			want:       "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
  4811  		},
  4812  		{
  4813  			n:          10,
  4814  			value:      func(i int) any { type Tint int; return []Tint{Tint(i)} },
  4815  			comparable: false,
  4816  			want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
  4817  		},
  4818  		{
  4819  			n:          10,
  4820  			value:      func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
  4821  			comparable: true,
  4822  			want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
  4823  		},
  4824  		{
  4825  			n:          10,
  4826  			value:      func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
  4827  			comparable: true,
  4828  			want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
  4829  		},
  4830  		{
  4831  			n:          10,
  4832  			value:      func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
  4833  			comparable: false,
  4834  			want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
  4835  		},
  4836  		{
  4837  			n:          10,
  4838  			value:      func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
  4839  			comparable: true,
  4840  			want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
  4841  		},
  4842  		{
  4843  			n: 10,
  4844  			value: func(i int) any {
  4845  				type TstructUV struct {
  4846  					U int
  4847  					V float64
  4848  				}
  4849  				return TstructUV{i, float64(i)}
  4850  			},
  4851  			comparable: true,
  4852  			want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
  4853  		},
  4854  	}
  4855  
  4856  	for _, table := range tests {
  4857  		at := ArrayOf(table.n, TypeOf(table.value(0)))
  4858  		v := New(at).Elem()
  4859  		vok := New(at).Elem()
  4860  		vnot := New(at).Elem()
  4861  		for i := 0; i < v.Len(); i++ {
  4862  			v.Index(i).Set(ValueOf(table.value(i)))
  4863  			vok.Index(i).Set(ValueOf(table.value(i)))
  4864  			j := i
  4865  			if i+1 == v.Len() {
  4866  				j = i + 1
  4867  			}
  4868  			vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
  4869  		}
  4870  		s := fmt.Sprint(v.Interface())
  4871  		if s != table.want {
  4872  			t.Errorf("constructed array = %s, want %s", s, table.want)
  4873  		}
  4874  
  4875  		if table.comparable != at.Comparable() {
  4876  			t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
  4877  		}
  4878  		if table.comparable {
  4879  			if table.n > 0 {
  4880  				if DeepEqual(vnot.Interface(), v.Interface()) {
  4881  					t.Errorf(
  4882  						"arrays (%#v) compare ok (but should not)",
  4883  						v.Interface(),
  4884  					)
  4885  				}
  4886  			}
  4887  			if !DeepEqual(vok.Interface(), v.Interface()) {
  4888  				t.Errorf(
  4889  					"arrays (%#v) compare NOT-ok (but should)",
  4890  					v.Interface(),
  4891  				)
  4892  			}
  4893  		}
  4894  	}
  4895  
  4896  	// check that type already in binary is found
  4897  	type T int
  4898  	checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
  4899  }
  4900  
  4901  func TestArrayOfGC(t *testing.T) {
  4902  	type T *uintptr
  4903  	tt := TypeOf(T(nil))
  4904  	const n = 100
  4905  	var x []any
  4906  	for i := 0; i < n; i++ {
  4907  		v := New(ArrayOf(n, tt)).Elem()
  4908  		for j := 0; j < v.Len(); j++ {
  4909  			p := new(uintptr)
  4910  			*p = uintptr(i*n + j)
  4911  			v.Index(j).Set(ValueOf(p).Convert(tt))
  4912  		}
  4913  		x = append(x, v.Interface())
  4914  	}
  4915  	runtime.GC()
  4916  
  4917  	for i, xi := range x {
  4918  		v := ValueOf(xi)
  4919  		for j := 0; j < v.Len(); j++ {
  4920  			k := v.Index(j).Elem().Interface()
  4921  			if k != uintptr(i*n+j) {
  4922  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  4923  			}
  4924  		}
  4925  	}
  4926  }
  4927  
  4928  func TestArrayOfAlg(t *testing.T) {
  4929  	at := ArrayOf(6, TypeOf(byte(0)))
  4930  	v1 := New(at).Elem()
  4931  	v2 := New(at).Elem()
  4932  	if v1.Interface() != v1.Interface() {
  4933  		t.Errorf("constructed array %v not equal to itself", v1.Interface())
  4934  	}
  4935  	v1.Index(5).Set(ValueOf(byte(1)))
  4936  	if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
  4937  		t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
  4938  	}
  4939  
  4940  	at = ArrayOf(6, TypeOf([]int(nil)))
  4941  	v1 = New(at).Elem()
  4942  	shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
  4943  }
  4944  
  4945  func TestArrayOfGenericAlg(t *testing.T) {
  4946  	at1 := ArrayOf(5, TypeOf(string("")))
  4947  	at := ArrayOf(6, at1)
  4948  	v1 := New(at).Elem()
  4949  	v2 := New(at).Elem()
  4950  	if v1.Interface() != v1.Interface() {
  4951  		t.Errorf("constructed array %v not equal to itself", v1.Interface())
  4952  	}
  4953  
  4954  	v1.Index(0).Index(0).Set(ValueOf("abc"))
  4955  	v2.Index(0).Index(0).Set(ValueOf("efg"))
  4956  	if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
  4957  		t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
  4958  	}
  4959  
  4960  	v1.Index(0).Index(0).Set(ValueOf("abc"))
  4961  	v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
  4962  	if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
  4963  		t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
  4964  	}
  4965  
  4966  	// Test hash
  4967  	m := MakeMap(MapOf(at, TypeOf(int(0))))
  4968  	m.SetMapIndex(v1, ValueOf(1))
  4969  	if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
  4970  		t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
  4971  	}
  4972  }
  4973  
  4974  func TestArrayOfDirectIface(t *testing.T) {
  4975  	{
  4976  		type T [1]*byte
  4977  		i1 := Zero(TypeOf(T{})).Interface()
  4978  		v1 := ValueOf(&i1).Elem()
  4979  		p1 := v1.InterfaceData()[1]
  4980  
  4981  		i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
  4982  		v2 := ValueOf(&i2).Elem()
  4983  		p2 := v2.InterfaceData()[1]
  4984  
  4985  		if p1 != 0 {
  4986  			t.Errorf("got p1=%v. want=%v", p1, nil)
  4987  		}
  4988  
  4989  		if p2 != 0 {
  4990  			t.Errorf("got p2=%v. want=%v", p2, nil)
  4991  		}
  4992  	}
  4993  	{
  4994  		type T [0]*byte
  4995  		i1 := Zero(TypeOf(T{})).Interface()
  4996  		v1 := ValueOf(&i1).Elem()
  4997  		p1 := v1.InterfaceData()[1]
  4998  
  4999  		i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
  5000  		v2 := ValueOf(&i2).Elem()
  5001  		p2 := v2.InterfaceData()[1]
  5002  
  5003  		if p1 == 0 {
  5004  			t.Errorf("got p1=%v. want=not-%v", p1, nil)
  5005  		}
  5006  
  5007  		if p2 == 0 {
  5008  			t.Errorf("got p2=%v. want=not-%v", p2, nil)
  5009  		}
  5010  	}
  5011  }
  5012  
  5013  // Ensure passing in negative lengths panics.
  5014  // See https://golang.org/issue/43603
  5015  func TestArrayOfPanicOnNegativeLength(t *testing.T) {
  5016  	shouldPanic("reflect: negative length passed to ArrayOf", func() {
  5017  		ArrayOf(-1, TypeOf(byte(0)))
  5018  	})
  5019  }
  5020  
  5021  func TestSliceOf(t *testing.T) {
  5022  	// check construction and use of type not in binary
  5023  	type T int
  5024  	st := SliceOf(TypeOf(T(1)))
  5025  	if got, want := st.String(), "[]reflect_test.T"; got != want {
  5026  		t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
  5027  	}
  5028  	v := MakeSlice(st, 10, 10)
  5029  	runtime.GC()
  5030  	for i := 0; i < v.Len(); i++ {
  5031  		v.Index(i).Set(ValueOf(T(i)))
  5032  		runtime.GC()
  5033  	}
  5034  	s := fmt.Sprint(v.Interface())
  5035  	want := "[0 1 2 3 4 5 6 7 8 9]"
  5036  	if s != want {
  5037  		t.Errorf("constructed slice = %s, want %s", s, want)
  5038  	}
  5039  
  5040  	// check that type already in binary is found
  5041  	type T1 int
  5042  	checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
  5043  }
  5044  
  5045  func TestSliceOverflow(t *testing.T) {
  5046  	// check that MakeSlice panics when size of slice overflows uint
  5047  	const S = 1e6
  5048  	s := uint(S)
  5049  	l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
  5050  	if l*s >= s {
  5051  		t.Fatal("slice size does not overflow")
  5052  	}
  5053  	var x [S]byte
  5054  	st := SliceOf(TypeOf(x))
  5055  	defer func() {
  5056  		err := recover()
  5057  		if err == nil {
  5058  			t.Fatal("slice overflow does not panic")
  5059  		}
  5060  	}()
  5061  	MakeSlice(st, int(l), int(l))
  5062  }
  5063  
  5064  func TestSliceOfGC(t *testing.T) {
  5065  	type T *uintptr
  5066  	tt := TypeOf(T(nil))
  5067  	st := SliceOf(tt)
  5068  	const n = 100
  5069  	var x []any
  5070  	for i := 0; i < n; i++ {
  5071  		v := MakeSlice(st, n, n)
  5072  		for j := 0; j < v.Len(); j++ {
  5073  			p := new(uintptr)
  5074  			*p = uintptr(i*n + j)
  5075  			v.Index(j).Set(ValueOf(p).Convert(tt))
  5076  		}
  5077  		x = append(x, v.Interface())
  5078  	}
  5079  	runtime.GC()
  5080  
  5081  	for i, xi := range x {
  5082  		v := ValueOf(xi)
  5083  		for j := 0; j < v.Len(); j++ {
  5084  			k := v.Index(j).Elem().Interface()
  5085  			if k != uintptr(i*n+j) {
  5086  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  5087  			}
  5088  		}
  5089  	}
  5090  }
  5091  
  5092  func TestStructOfFieldName(t *testing.T) {
  5093  	// invalid field name "1nvalid"
  5094  	shouldPanic("has invalid name", func() {
  5095  		StructOf([]StructField{
  5096  			{Name: "Valid", Type: TypeOf("")},
  5097  			{Name: "1nvalid", Type: TypeOf("")},
  5098  		})
  5099  	})
  5100  
  5101  	// invalid field name "+"
  5102  	shouldPanic("has invalid name", func() {
  5103  		StructOf([]StructField{
  5104  			{Name: "Val1d", Type: TypeOf("")},
  5105  			{Name: "+", Type: TypeOf("")},
  5106  		})
  5107  	})
  5108  
  5109  	// no field name
  5110  	shouldPanic("has no name", func() {
  5111  		StructOf([]StructField{
  5112  			{Name: "", Type: TypeOf("")},
  5113  		})
  5114  	})
  5115  
  5116  	// verify creation of a struct with valid struct fields
  5117  	validFields := []StructField{
  5118  		{
  5119  			Name: "φ",
  5120  			Type: TypeOf(""),
  5121  		},
  5122  		{
  5123  			Name: "ValidName",
  5124  			Type: TypeOf(""),
  5125  		},
  5126  		{
  5127  			Name: "Val1dNam5",
  5128  			Type: TypeOf(""),
  5129  		},
  5130  	}
  5131  
  5132  	validStruct := StructOf(validFields)
  5133  
  5134  	const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
  5135  	if got, want := validStruct.String(), structStr; got != want {
  5136  		t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
  5137  	}
  5138  }
  5139  
  5140  func TestStructOf(t *testing.T) {
  5141  	// check construction and use of type not in binary
  5142  	fields := []StructField{
  5143  		{
  5144  			Name: "S",
  5145  			Tag:  "s",
  5146  			Type: TypeOf(""),
  5147  		},
  5148  		{
  5149  			Name: "X",
  5150  			Tag:  "x",
  5151  			Type: TypeOf(byte(0)),
  5152  		},
  5153  		{
  5154  			Name: "Y",
  5155  			Type: TypeOf(uint64(0)),
  5156  		},
  5157  		{
  5158  			Name: "Z",
  5159  			Type: TypeOf([3]uint16{}),
  5160  		},
  5161  	}
  5162  
  5163  	st := StructOf(fields)
  5164  	v := New(st).Elem()
  5165  	runtime.GC()
  5166  	v.FieldByName("X").Set(ValueOf(byte(2)))
  5167  	v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
  5168  	runtime.GC()
  5169  
  5170  	s := fmt.Sprint(v.Interface())
  5171  	want := `{ 1 0 [0 0 0]}`
  5172  	if s != want {
  5173  		t.Errorf("constructed struct = %s, want %s", s, want)
  5174  	}
  5175  	const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
  5176  	if got, want := st.String(), stStr; got != want {
  5177  		t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
  5178  	}
  5179  
  5180  	// check the size, alignment and field offsets
  5181  	stt := TypeOf(struct {
  5182  		String string
  5183  		X      byte
  5184  		Y      uint64
  5185  		Z      [3]uint16
  5186  	}{})
  5187  	if st.Size() != stt.Size() {
  5188  		t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
  5189  	}
  5190  	if st.Align() != stt.Align() {
  5191  		t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
  5192  	}
  5193  	if st.FieldAlign() != stt.FieldAlign() {
  5194  		t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
  5195  	}
  5196  	for i := 0; i < st.NumField(); i++ {
  5197  		o1 := st.Field(i).Offset
  5198  		o2 := stt.Field(i).Offset
  5199  		if o1 != o2 {
  5200  			t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
  5201  		}
  5202  	}
  5203  
  5204  	// Check size and alignment with a trailing zero-sized field.
  5205  	st = StructOf([]StructField{
  5206  		{
  5207  			Name: "F1",
  5208  			Type: TypeOf(byte(0)),
  5209  		},
  5210  		{
  5211  			Name: "F2",
  5212  			Type: TypeOf([0]*byte{}),
  5213  		},
  5214  	})
  5215  	stt = TypeOf(struct {
  5216  		G1 byte
  5217  		G2 [0]*byte
  5218  	}{})
  5219  	if st.Size() != stt.Size() {
  5220  		t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
  5221  	}
  5222  	if st.Align() != stt.Align() {
  5223  		t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
  5224  	}
  5225  	if st.FieldAlign() != stt.FieldAlign() {
  5226  		t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
  5227  	}
  5228  	for i := 0; i < st.NumField(); i++ {
  5229  		o1 := st.Field(i).Offset
  5230  		o2 := stt.Field(i).Offset
  5231  		if o1 != o2 {
  5232  			t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
  5233  		}
  5234  	}
  5235  
  5236  	// check duplicate names
  5237  	shouldPanic("duplicate field", func() {
  5238  		StructOf([]StructField{
  5239  			{Name: "string", PkgPath: "p", Type: TypeOf("")},
  5240  			{Name: "string", PkgPath: "p", Type: TypeOf("")},
  5241  		})
  5242  	})
  5243  	shouldPanic("has no name", func() {
  5244  		StructOf([]StructField{
  5245  			{Type: TypeOf("")},
  5246  			{Name: "string", PkgPath: "p", Type: TypeOf("")},
  5247  		})
  5248  	})
  5249  	shouldPanic("has no name", func() {
  5250  		StructOf([]StructField{
  5251  			{Type: TypeOf("")},
  5252  			{Type: TypeOf("")},
  5253  		})
  5254  	})
  5255  	// check that type already in binary is found
  5256  	checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
  5257  
  5258  	// gccgo used to fail this test.
  5259  	type structFieldType any
  5260  	checkSameType(t,
  5261  		StructOf([]StructField{
  5262  			{
  5263  				Name: "F",
  5264  				Type: TypeOf((*structFieldType)(nil)).Elem(),
  5265  			},
  5266  		}),
  5267  		struct{ F structFieldType }{})
  5268  }
  5269  
  5270  func TestStructOfExportRules(t *testing.T) {
  5271  	type S1 struct{}
  5272  	type s2 struct{}
  5273  	type ΦType struct{}
  5274  	type φType struct{}
  5275  
  5276  	testPanic := func(i int, mustPanic bool, f func()) {
  5277  		defer func() {
  5278  			err := recover()
  5279  			if err == nil && mustPanic {
  5280  				t.Errorf("test-%d did not panic", i)
  5281  			}
  5282  			if err != nil && !mustPanic {
  5283  				t.Errorf("test-%d panicked: %v\n", i, err)
  5284  			}
  5285  		}()
  5286  		f()
  5287  	}
  5288  
  5289  	tests := []struct {
  5290  		field     StructField
  5291  		mustPanic bool
  5292  		exported  bool
  5293  	}{
  5294  		{
  5295  			field:    StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
  5296  			exported: true,
  5297  		},
  5298  		{
  5299  			field:    StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
  5300  			exported: true,
  5301  		},
  5302  		{
  5303  			field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
  5304  			mustPanic: true,
  5305  		},
  5306  		{
  5307  			field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
  5308  			mustPanic: true,
  5309  		},
  5310  		{
  5311  			field:     StructField{Name: "Name", Type: nil, PkgPath: ""},
  5312  			mustPanic: true,
  5313  		},
  5314  		{
  5315  			field:     StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
  5316  			mustPanic: true,
  5317  		},
  5318  		{
  5319  			field:     StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
  5320  			mustPanic: true,
  5321  		},
  5322  		{
  5323  			field:     StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
  5324  			mustPanic: true,
  5325  		},
  5326  		{
  5327  			field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
  5328  			mustPanic: true,
  5329  		},
  5330  		{
  5331  			field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
  5332  			mustPanic: true,
  5333  		},
  5334  		{
  5335  			field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
  5336  		},
  5337  		{
  5338  			field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
  5339  		},
  5340  		{
  5341  			field:    StructField{Name: "S", Type: TypeOf(S1{})},
  5342  			exported: true,
  5343  		},
  5344  		{
  5345  			field:    StructField{Name: "S", Type: TypeOf((*S1)(nil))},
  5346  			exported: true,
  5347  		},
  5348  		{
  5349  			field:    StructField{Name: "S", Type: TypeOf(s2{})},
  5350  			exported: true,
  5351  		},
  5352  		{
  5353  			field:    StructField{Name: "S", Type: TypeOf((*s2)(nil))},
  5354  			exported: true,
  5355  		},
  5356  		{
  5357  			field:     StructField{Name: "s", Type: TypeOf(S1{})},
  5358  			mustPanic: true,
  5359  		},
  5360  		{
  5361  			field:     StructField{Name: "s", Type: TypeOf((*S1)(nil))},
  5362  			mustPanic: true,
  5363  		},
  5364  		{
  5365  			field:     StructField{Name: "s", Type: TypeOf(s2{})},
  5366  			mustPanic: true,
  5367  		},
  5368  		{
  5369  			field:     StructField{Name: "s", Type: TypeOf((*s2)(nil))},
  5370  			mustPanic: true,
  5371  		},
  5372  		{
  5373  			field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
  5374  		},
  5375  		{
  5376  			field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
  5377  		},
  5378  		{
  5379  			field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
  5380  		},
  5381  		{
  5382  			field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
  5383  		},
  5384  		{
  5385  			field:     StructField{Name: "", Type: TypeOf(ΦType{})},
  5386  			mustPanic: true,
  5387  		},
  5388  		{
  5389  			field:     StructField{Name: "", Type: TypeOf(φType{})},
  5390  			mustPanic: true,
  5391  		},
  5392  		{
  5393  			field:    StructField{Name: "Φ", Type: TypeOf(0)},
  5394  			exported: true,
  5395  		},
  5396  		{
  5397  			field:    StructField{Name: "φ", Type: TypeOf(0)},
  5398  			exported: false,
  5399  		},
  5400  	}
  5401  
  5402  	for i, test := range tests {
  5403  		testPanic(i, test.mustPanic, func() {
  5404  			typ := StructOf([]StructField{test.field})
  5405  			if typ == nil {
  5406  				t.Errorf("test-%d: error creating struct type", i)
  5407  				return
  5408  			}
  5409  			field := typ.Field(0)
  5410  			n := field.Name
  5411  			if n == "" {
  5412  				panic("field.Name must not be empty")
  5413  			}
  5414  			exported := token.IsExported(n)
  5415  			if exported != test.exported {
  5416  				t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
  5417  			}
  5418  			if field.PkgPath != test.field.PkgPath {
  5419  				t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
  5420  			}
  5421  		})
  5422  	}
  5423  }
  5424  
  5425  func TestStructOfGC(t *testing.T) {
  5426  	type T *uintptr
  5427  	tt := TypeOf(T(nil))
  5428  	fields := []StructField{
  5429  		{Name: "X", Type: tt},
  5430  		{Name: "Y", Type: tt},
  5431  	}
  5432  	st := StructOf(fields)
  5433  
  5434  	const n = 10000
  5435  	var x []any
  5436  	for i := 0; i < n; i++ {
  5437  		v := New(st).Elem()
  5438  		for j := 0; j < v.NumField(); j++ {
  5439  			p := new(uintptr)
  5440  			*p = uintptr(i*n + j)
  5441  			v.Field(j).Set(ValueOf(p).Convert(tt))
  5442  		}
  5443  		x = append(x, v.Interface())
  5444  	}
  5445  	runtime.GC()
  5446  
  5447  	for i, xi := range x {
  5448  		v := ValueOf(xi)
  5449  		for j := 0; j < v.NumField(); j++ {
  5450  			k := v.Field(j).Elem().Interface()
  5451  			if k != uintptr(i*n+j) {
  5452  				t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
  5453  			}
  5454  		}
  5455  	}
  5456  }
  5457  
  5458  func TestStructOfAlg(t *testing.T) {
  5459  	st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
  5460  	v1 := New(st).Elem()
  5461  	v2 := New(st).Elem()
  5462  	if !DeepEqual(v1.Interface(), v1.Interface()) {
  5463  		t.Errorf("constructed struct %v not equal to itself", v1.Interface())
  5464  	}
  5465  	v1.FieldByName("X").Set(ValueOf(int(1)))
  5466  	if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
  5467  		t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
  5468  	}
  5469  
  5470  	st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
  5471  	v1 = New(st).Elem()
  5472  	shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
  5473  }
  5474  
  5475  func TestStructOfGenericAlg(t *testing.T) {
  5476  	st1 := StructOf([]StructField{
  5477  		{Name: "X", Tag: "x", Type: TypeOf(int64(0))},
  5478  		{Name: "Y", Type: TypeOf(string(""))},
  5479  	})
  5480  	st := StructOf([]StructField{
  5481  		{Name: "S0", Type: st1},
  5482  		{Name: "S1", Type: st1},
  5483  	})
  5484  
  5485  	tests := []struct {
  5486  		rt  Type
  5487  		idx []int
  5488  	}{
  5489  		{
  5490  			rt:  st,
  5491  			idx: []int{0, 1},
  5492  		},
  5493  		{
  5494  			rt:  st1,
  5495  			idx: []int{1},
  5496  		},
  5497  		{
  5498  			rt: StructOf(
  5499  				[]StructField{
  5500  					{Name: "XX", Type: TypeOf([0]int{})},
  5501  					{Name: "YY", Type: TypeOf("")},
  5502  				},
  5503  			),
  5504  			idx: []int{1},
  5505  		},
  5506  		{
  5507  			rt: StructOf(
  5508  				[]StructField{
  5509  					{Name: "XX", Type: TypeOf([0]int{})},
  5510  					{Name: "YY", Type: TypeOf("")},
  5511  					{Name: "ZZ", Type: TypeOf([2]int{})},
  5512  				},
  5513  			),
  5514  			idx: []int{1},
  5515  		},
  5516  		{
  5517  			rt: StructOf(
  5518  				[]StructField{
  5519  					{Name: "XX", Type: TypeOf([1]int{})},
  5520  					{Name: "YY", Type: TypeOf("")},
  5521  				},
  5522  			),
  5523  			idx: []int{1},
  5524  		},
  5525  		{
  5526  			rt: StructOf(
  5527  				[]StructField{
  5528  					{Name: "XX", Type: TypeOf([1]int{})},
  5529  					{Name: "YY", Type: TypeOf("")},
  5530  					{Name: "ZZ", Type: TypeOf([1]int{})},
  5531  				},
  5532  			),
  5533  			idx: []int{1},
  5534  		},
  5535  		{
  5536  			rt: StructOf(
  5537  				[]StructField{
  5538  					{Name: "XX", Type: TypeOf([2]int{})},
  5539  					{Name: "YY", Type: TypeOf("")},
  5540  					{Name: "ZZ", Type: TypeOf([2]int{})},
  5541  				},
  5542  			),
  5543  			idx: []int{1},
  5544  		},
  5545  		{
  5546  			rt: StructOf(
  5547  				[]StructField{
  5548  					{Name: "XX", Type: TypeOf(int64(0))},
  5549  					{Name: "YY", Type: TypeOf(byte(0))},
  5550  					{Name: "ZZ", Type: TypeOf("")},
  5551  				},
  5552  			),
  5553  			idx: []int{2},
  5554  		},
  5555  		{
  5556  			rt: StructOf(
  5557  				[]StructField{
  5558  					{Name: "XX", Type: TypeOf(int64(0))},
  5559  					{Name: "YY", Type: TypeOf(int64(0))},
  5560  					{Name: "ZZ", Type: TypeOf("")},
  5561  					{Name: "AA", Type: TypeOf([1]int64{})},
  5562  				},
  5563  			),
  5564  			idx: []int{2},
  5565  		},
  5566  	}
  5567  
  5568  	for _, table := range tests {
  5569  		v1 := New(table.rt).Elem()
  5570  		v2 := New(table.rt).Elem()
  5571  
  5572  		if !DeepEqual(v1.Interface(), v1.Interface()) {
  5573  			t.Errorf("constructed struct %v not equal to itself", v1.Interface())
  5574  		}
  5575  
  5576  		v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
  5577  		v2.FieldByIndex(table.idx).Set(ValueOf("def"))
  5578  		if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
  5579  			t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
  5580  		}
  5581  
  5582  		abc := "abc"
  5583  		v1.FieldByIndex(table.idx).Set(ValueOf(abc))
  5584  		val := "+" + abc + "-"
  5585  		v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
  5586  		if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
  5587  			t.Errorf("constructed structs %v and %v should be equal", i1, i2)
  5588  		}
  5589  
  5590  		// Test hash
  5591  		m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
  5592  		m.SetMapIndex(v1, ValueOf(1))
  5593  		if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
  5594  			t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
  5595  		}
  5596  
  5597  		v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
  5598  		if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
  5599  			t.Errorf("constructed structs %v and %v should be equal", i1, i2)
  5600  		}
  5601  
  5602  		if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
  5603  			t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
  5604  		}
  5605  	}
  5606  }
  5607  
  5608  func TestStructOfDirectIface(t *testing.T) {
  5609  	{
  5610  		type T struct{ X [1]*byte }
  5611  		i1 := Zero(TypeOf(T{})).Interface()
  5612  		v1 := ValueOf(&i1).Elem()
  5613  		p1 := v1.InterfaceData()[1]
  5614  
  5615  		i2 := Zero(StructOf([]StructField{
  5616  			{
  5617  				Name: "X",
  5618  				Type: ArrayOf(1, TypeOf((*int8)(nil))),
  5619  			},
  5620  		})).Interface()
  5621  		v2 := ValueOf(&i2).Elem()
  5622  		p2 := v2.InterfaceData()[1]
  5623  
  5624  		if p1 != 0 {
  5625  			t.Errorf("got p1=%v. want=%v", p1, nil)
  5626  		}
  5627  
  5628  		if p2 != 0 {
  5629  			t.Errorf("got p2=%v. want=%v", p2, nil)
  5630  		}
  5631  	}
  5632  	{
  5633  		type T struct{ X [0]*byte }
  5634  		i1 := Zero(TypeOf(T{})).Interface()
  5635  		v1 := ValueOf(&i1).Elem()
  5636  		p1 := v1.InterfaceData()[1]
  5637  
  5638  		i2 := Zero(StructOf([]StructField{
  5639  			{
  5640  				Name: "X",
  5641  				Type: ArrayOf(0, TypeOf((*int8)(nil))),
  5642  			},
  5643  		})).Interface()
  5644  		v2 := ValueOf(&i2).Elem()
  5645  		p2 := v2.InterfaceData()[1]
  5646  
  5647  		if p1 == 0 {
  5648  			t.Errorf("got p1=%v. want=not-%v", p1, nil)
  5649  		}
  5650  
  5651  		if p2 == 0 {
  5652  			t.Errorf("got p2=%v. want=not-%v", p2, nil)
  5653  		}
  5654  	}
  5655  }
  5656  
  5657  type StructI int
  5658  
  5659  func (i StructI) Get() int { return int(i) }
  5660  
  5661  type StructIPtr int
  5662  
  5663  func (i *StructIPtr) Get() int  { return int(*i) }
  5664  func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
  5665  
  5666  type SettableStruct struct {
  5667  	SettableField int
  5668  }
  5669  
  5670  func (p *SettableStruct) Set(v int) { p.SettableField = v }
  5671  
  5672  type SettablePointer struct {
  5673  	SettableField *int
  5674  }
  5675  
  5676  func (p *SettablePointer) Set(v int) { *p.SettableField = v }
  5677  
  5678  func TestStructOfWithInterface(t *testing.T) {
  5679  	const want = 42
  5680  	type Iface interface {
  5681  		Get() int
  5682  	}
  5683  	type IfaceSet interface {
  5684  		Set(int)
  5685  	}
  5686  	tests := []struct {
  5687  		name string
  5688  		typ  Type
  5689  		val  Value
  5690  		impl bool
  5691  	}{
  5692  		{
  5693  			name: "StructI",
  5694  			typ:  TypeOf(StructI(want)),
  5695  			val:  ValueOf(StructI(want)),
  5696  			impl: true,
  5697  		},
  5698  		{
  5699  			name: "StructI",
  5700  			typ:  PointerTo(TypeOf(StructI(want))),
  5701  			val: ValueOf(func() any {
  5702  				v := StructI(want)
  5703  				return &v
  5704  			}()),
  5705  			impl: true,
  5706  		},
  5707  		{
  5708  			name: "StructIPtr",
  5709  			typ:  PointerTo(TypeOf(StructIPtr(want))),
  5710  			val: ValueOf(func() any {
  5711  				v := StructIPtr(want)
  5712  				return &v
  5713  			}()),
  5714  			impl: true,
  5715  		},
  5716  		{
  5717  			name: "StructIPtr",
  5718  			typ:  TypeOf(StructIPtr(want)),
  5719  			val:  ValueOf(StructIPtr(want)),
  5720  			impl: false,
  5721  		},
  5722  		// {
  5723  		//	typ:  TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
  5724  		//	val:  ValueOf(StructI(want)),
  5725  		//	impl: true,
  5726  		// },
  5727  	}
  5728  
  5729  	for i, table := range tests {
  5730  		for j := 0; j < 2; j++ {
  5731  			var fields []StructField
  5732  			if j == 1 {
  5733  				fields = append(fields, StructField{
  5734  					Name:    "Dummy",
  5735  					PkgPath: "",
  5736  					Type:    TypeOf(int(0)),
  5737  				})
  5738  			}
  5739  			fields = append(fields, StructField{
  5740  				Name:      table.name,
  5741  				Anonymous: true,
  5742  				PkgPath:   "",
  5743  				Type:      table.typ,
  5744  			})
  5745  
  5746  			// We currently do not correctly implement methods
  5747  			// for embedded fields other than the first.
  5748  			// Therefore, for now, we expect those methods
  5749  			// to not exist.  See issues 15924 and 20824.
  5750  			// When those issues are fixed, this test of panic
  5751  			// should be removed.
  5752  			if j == 1 && table.impl {
  5753  				func() {
  5754  					defer func() {
  5755  						if err := recover(); err == nil {
  5756  							t.Errorf("test-%d-%d did not panic", i, j)
  5757  						}
  5758  					}()
  5759  					_ = StructOf(fields)
  5760  				}()
  5761  				continue
  5762  			}
  5763  
  5764  			rt := StructOf(fields)
  5765  			rv := New(rt).Elem()
  5766  			rv.Field(j).Set(table.val)
  5767  
  5768  			if _, ok := rv.Interface().(Iface); ok != table.impl {
  5769  				if table.impl {
  5770  					t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
  5771  				} else {
  5772  					t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
  5773  				}
  5774  				continue
  5775  			}
  5776  
  5777  			if !table.impl {
  5778  				continue
  5779  			}
  5780  
  5781  			v := rv.Interface().(Iface).Get()
  5782  			if v != want {
  5783  				t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
  5784  			}
  5785  
  5786  			fct := rv.MethodByName("Get")
  5787  			out := fct.Call(nil)
  5788  			if !DeepEqual(out[0].Interface(), want) {
  5789  				t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
  5790  			}
  5791  		}
  5792  	}
  5793  
  5794  	// Test an embedded nil pointer with pointer methods.
  5795  	fields := []StructField{{
  5796  		Name:      "StructIPtr",
  5797  		Anonymous: true,
  5798  		Type:      PointerTo(TypeOf(StructIPtr(want))),
  5799  	}}
  5800  	rt := StructOf(fields)
  5801  	rv := New(rt).Elem()
  5802  	// This should panic since the pointer is nil.
  5803  	shouldPanic("", func() {
  5804  		rv.Interface().(IfaceSet).Set(want)
  5805  	})
  5806  
  5807  	// Test an embedded nil pointer to a struct with pointer methods.
  5808  
  5809  	fields = []StructField{{
  5810  		Name:      "SettableStruct",
  5811  		Anonymous: true,
  5812  		Type:      PointerTo(TypeOf(SettableStruct{})),
  5813  	}}
  5814  	rt = StructOf(fields)
  5815  	rv = New(rt).Elem()
  5816  	// This should panic since the pointer is nil.
  5817  	shouldPanic("", func() {
  5818  		rv.Interface().(IfaceSet).Set(want)
  5819  	})
  5820  
  5821  	// The behavior is different if there is a second field,
  5822  	// since now an interface value holds a pointer to the struct
  5823  	// rather than just holding a copy of the struct.
  5824  	fields = []StructField{
  5825  		{
  5826  			Name:      "SettableStruct",
  5827  			Anonymous: true,
  5828  			Type:      PointerTo(TypeOf(SettableStruct{})),
  5829  		},
  5830  		{
  5831  			Name:      "EmptyStruct",
  5832  			Anonymous: true,
  5833  			Type:      StructOf(nil),
  5834  		},
  5835  	}
  5836  	// With the current implementation this is expected to panic.
  5837  	// Ideally it should work and we should be able to see a panic
  5838  	// if we call the Set method.
  5839  	shouldPanic("", func() {
  5840  		StructOf(fields)
  5841  	})
  5842  
  5843  	// Embed a field that can be stored directly in an interface,
  5844  	// with a second field.
  5845  	fields = []StructField{
  5846  		{
  5847  			Name:      "SettablePointer",
  5848  			Anonymous: true,
  5849  			Type:      TypeOf(SettablePointer{}),
  5850  		},
  5851  		{
  5852  			Name:      "EmptyStruct",
  5853  			Anonymous: true,
  5854  			Type:      StructOf(nil),
  5855  		},
  5856  	}
  5857  	// With the current implementation this is expected to panic.
  5858  	// Ideally it should work and we should be able to call the
  5859  	// Set and Get methods.
  5860  	shouldPanic("", func() {
  5861  		StructOf(fields)
  5862  	})
  5863  }
  5864  
  5865  func TestStructOfTooManyFields(t *testing.T) {
  5866  	// Bug Fix: #25402 - this should not panic
  5867  	tt := StructOf([]StructField{
  5868  		{Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
  5869  	})
  5870  
  5871  	if _, present := tt.MethodByName("After"); !present {
  5872  		t.Errorf("Expected method `After` to be found")
  5873  	}
  5874  }
  5875  
  5876  func TestStructOfDifferentPkgPath(t *testing.T) {
  5877  	fields := []StructField{
  5878  		{
  5879  			Name:    "f1",
  5880  			PkgPath: "p1",
  5881  			Type:    TypeOf(int(0)),
  5882  		},
  5883  		{
  5884  			Name:    "f2",
  5885  			PkgPath: "p2",
  5886  			Type:    TypeOf(int(0)),
  5887  		},
  5888  	}
  5889  	shouldPanic("different PkgPath", func() {
  5890  		StructOf(fields)
  5891  	})
  5892  }
  5893  
  5894  func TestStructOfTooLarge(t *testing.T) {
  5895  	t1 := TypeOf(byte(0))
  5896  	t2 := TypeOf(int16(0))
  5897  	t4 := TypeOf(int32(0))
  5898  	t0 := ArrayOf(0, t1)
  5899  
  5900  	// 2^64-3 sized type (or 2^32-3 on 32-bit archs)
  5901  	bigType := StructOf([]StructField{
  5902  		{Name: "F1", Type: ArrayOf(int(^uintptr(0)>>1), t1)},
  5903  		{Name: "F2", Type: ArrayOf(int(^uintptr(0)>>1-1), t1)},
  5904  	})
  5905  
  5906  	type test struct {
  5907  		shouldPanic bool
  5908  		fields      []StructField
  5909  	}
  5910  
  5911  	tests := [...]test{
  5912  		{
  5913  			shouldPanic: false, // 2^64-1, ok
  5914  			fields: []StructField{
  5915  				{Name: "F1", Type: bigType},
  5916  				{Name: "F2", Type: ArrayOf(2, t1)},
  5917  			},
  5918  		},
  5919  		{
  5920  			shouldPanic: true, // overflow in total size
  5921  			fields: []StructField{
  5922  				{Name: "F1", Type: bigType},
  5923  				{Name: "F2", Type: ArrayOf(3, t1)},
  5924  			},
  5925  		},
  5926  		{
  5927  			shouldPanic: true, // overflow while aligning F2
  5928  			fields: []StructField{
  5929  				{Name: "F1", Type: bigType},
  5930  				{Name: "F2", Type: t4},
  5931  			},
  5932  		},
  5933  		{
  5934  			shouldPanic: true, // overflow while adding trailing byte for zero-sized fields
  5935  			fields: []StructField{
  5936  				{Name: "F1", Type: bigType},
  5937  				{Name: "F2", Type: ArrayOf(2, t1)},
  5938  				{Name: "F3", Type: t0},
  5939  			},
  5940  		},
  5941  		{
  5942  			shouldPanic: true, // overflow while aligning total size
  5943  			fields: []StructField{
  5944  				{Name: "F1", Type: t2},
  5945  				{Name: "F2", Type: bigType},
  5946  			},
  5947  		},
  5948  	}
  5949  
  5950  	for i, tt := range tests {
  5951  		func() {
  5952  			defer func() {
  5953  				err := recover()
  5954  				if !tt.shouldPanic {
  5955  					if err != nil {
  5956  						t.Errorf("test %d should not panic, got %s", i, err)
  5957  					}
  5958  					return
  5959  				}
  5960  				if err == nil {
  5961  					t.Errorf("test %d expected to panic", i)
  5962  					return
  5963  				}
  5964  				s := fmt.Sprintf("%s", err)
  5965  				if s != "reflect.StructOf: struct size would exceed virtual address space" {
  5966  					t.Errorf("test %d wrong panic message: %s", i, s)
  5967  					return
  5968  				}
  5969  			}()
  5970  			_ = StructOf(tt.fields)
  5971  		}()
  5972  	}
  5973  }
  5974  
  5975  func TestChanOf(t *testing.T) {
  5976  	// check construction and use of type not in binary
  5977  	type T string
  5978  	ct := ChanOf(BothDir, TypeOf(T("")))
  5979  	v := MakeChan(ct, 2)
  5980  	runtime.GC()
  5981  	v.Send(ValueOf(T("hello")))
  5982  	runtime.GC()
  5983  	v.Send(ValueOf(T("world")))
  5984  	runtime.GC()
  5985  
  5986  	sv1, _ := v.Recv()
  5987  	sv2, _ := v.Recv()
  5988  	s1 := sv1.String()
  5989  	s2 := sv2.String()
  5990  	if s1 != "hello" || s2 != "world" {
  5991  		t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
  5992  	}
  5993  
  5994  	// check that type already in binary is found
  5995  	type T1 int
  5996  	checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
  5997  
  5998  	// Check arrow token association in undefined chan types.
  5999  	var left chan<- chan T
  6000  	var right chan (<-chan T)
  6001  	tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
  6002  	tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
  6003  	if tLeft != TypeOf(left) {
  6004  		t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
  6005  	}
  6006  	if tRight != TypeOf(right) {
  6007  		t.Errorf("chan<-chan: have %s, want %T", tRight, right)
  6008  	}
  6009  }
  6010  
  6011  func TestChanOfDir(t *testing.T) {
  6012  	// check construction and use of type not in binary
  6013  	type T string
  6014  	crt := ChanOf(RecvDir, TypeOf(T("")))
  6015  	cst := ChanOf(SendDir, TypeOf(T("")))
  6016  
  6017  	// check that type already in binary is found
  6018  	type T1 int
  6019  	checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
  6020  	checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
  6021  
  6022  	// check String form of ChanDir
  6023  	if crt.ChanDir().String() != "<-chan" {
  6024  		t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
  6025  	}
  6026  	if cst.ChanDir().String() != "chan<-" {
  6027  		t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
  6028  	}
  6029  }
  6030  
  6031  func TestChanOfGC(t *testing.T) {
  6032  	done := make(chan bool, 1)
  6033  	go func() {
  6034  		select {
  6035  		case <-done:
  6036  		case <-time.After(5 * time.Second):
  6037  			panic("deadlock in TestChanOfGC")
  6038  		}
  6039  	}()
  6040  
  6041  	defer func() {
  6042  		done <- true
  6043  	}()
  6044  
  6045  	type T *uintptr
  6046  	tt := TypeOf(T(nil))
  6047  	ct := ChanOf(BothDir, tt)
  6048  
  6049  	// NOTE: The garbage collector handles allocated channels specially,
  6050  	// so we have to save pointers to channels in x; the pointer code will
  6051  	// use the gc info in the newly constructed chan type.
  6052  	const n = 100
  6053  	var x []any
  6054  	for i := 0; i < n; i++ {
  6055  		v := MakeChan(ct, n)
  6056  		for j := 0; j < n; j++ {
  6057  			p := new(uintptr)
  6058  			*p = uintptr(i*n + j)
  6059  			v.Send(ValueOf(p).Convert(tt))
  6060  		}
  6061  		pv := New(ct)
  6062  		pv.Elem().Set(v)
  6063  		x = append(x, pv.Interface())
  6064  	}
  6065  	runtime.GC()
  6066  
  6067  	for i, xi := range x {
  6068  		v := ValueOf(xi).Elem()
  6069  		for j := 0; j < n; j++ {
  6070  			pv, _ := v.Recv()
  6071  			k := pv.Elem().Interface()
  6072  			if k != uintptr(i*n+j) {
  6073  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  6074  			}
  6075  		}
  6076  	}
  6077  }
  6078  
  6079  func TestMapOf(t *testing.T) {
  6080  	// check construction and use of type not in binary
  6081  	type K string
  6082  	type V float64
  6083  
  6084  	v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
  6085  	runtime.GC()
  6086  	v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
  6087  	runtime.GC()
  6088  
  6089  	s := fmt.Sprint(v.Interface())
  6090  	want := "map[a:1]"
  6091  	if s != want {
  6092  		t.Errorf("constructed map = %s, want %s", s, want)
  6093  	}
  6094  
  6095  	// check that type already in binary is found
  6096  	checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
  6097  
  6098  	// check that invalid key type panics
  6099  	shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
  6100  }
  6101  
  6102  func TestMapOfGCKeys(t *testing.T) {
  6103  	type T *uintptr
  6104  	tt := TypeOf(T(nil))
  6105  	mt := MapOf(tt, TypeOf(false))
  6106  
  6107  	// NOTE: The garbage collector handles allocated maps specially,
  6108  	// so we have to save pointers to maps in x; the pointer code will
  6109  	// use the gc info in the newly constructed map type.
  6110  	const n = 100
  6111  	var x []any
  6112  	for i := 0; i < n; i++ {
  6113  		v := MakeMap(mt)
  6114  		for j := 0; j < n; j++ {
  6115  			p := new(uintptr)
  6116  			*p = uintptr(i*n + j)
  6117  			v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
  6118  		}
  6119  		pv := New(mt)
  6120  		pv.Elem().Set(v)
  6121  		x = append(x, pv.Interface())
  6122  	}
  6123  	runtime.GC()
  6124  
  6125  	for i, xi := range x {
  6126  		v := ValueOf(xi).Elem()
  6127  		var out []int
  6128  		for _, kv := range v.MapKeys() {
  6129  			out = append(out, int(kv.Elem().Interface().(uintptr)))
  6130  		}
  6131  		sort.Ints(out)
  6132  		for j, k := range out {
  6133  			if k != i*n+j {
  6134  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  6135  			}
  6136  		}
  6137  	}
  6138  }
  6139  
  6140  func TestMapOfGCValues(t *testing.T) {
  6141  	type T *uintptr
  6142  	tt := TypeOf(T(nil))
  6143  	mt := MapOf(TypeOf(1), tt)
  6144  
  6145  	// NOTE: The garbage collector handles allocated maps specially,
  6146  	// so we have to save pointers to maps in x; the pointer code will
  6147  	// use the gc info in the newly constructed map type.
  6148  	const n = 100
  6149  	var x []any
  6150  	for i := 0; i < n; i++ {
  6151  		v := MakeMap(mt)
  6152  		for j := 0; j < n; j++ {
  6153  			p := new(uintptr)
  6154  			*p = uintptr(i*n + j)
  6155  			v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
  6156  		}
  6157  		pv := New(mt)
  6158  		pv.Elem().Set(v)
  6159  		x = append(x, pv.Interface())
  6160  	}
  6161  	runtime.GC()
  6162  
  6163  	for i, xi := range x {
  6164  		v := ValueOf(xi).Elem()
  6165  		for j := 0; j < n; j++ {
  6166  			k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
  6167  			if k != uintptr(i*n+j) {
  6168  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  6169  			}
  6170  		}
  6171  	}
  6172  }
  6173  
  6174  func TestTypelinksSorted(t *testing.T) {
  6175  	var last string
  6176  	for i, n := range TypeLinks() {
  6177  		if n < last {
  6178  			t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
  6179  		}
  6180  		last = n
  6181  	}
  6182  }
  6183  
  6184  func TestFuncOf(t *testing.T) {
  6185  	// check construction and use of type not in binary
  6186  	type K string
  6187  	type V float64
  6188  
  6189  	fn := func(args []Value) []Value {
  6190  		if len(args) != 1 {
  6191  			t.Errorf("args == %v, want exactly one arg", args)
  6192  		} else if args[0].Type() != TypeOf(K("")) {
  6193  			t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
  6194  		} else if args[0].String() != "gopher" {
  6195  			t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
  6196  		}
  6197  		return []Value{ValueOf(V(3.14))}
  6198  	}
  6199  	v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
  6200  
  6201  	outs := v.Call([]Value{ValueOf(K("gopher"))})
  6202  	if len(outs) != 1 {
  6203  		t.Fatalf("v.Call returned %v, want exactly one result", outs)
  6204  	} else if outs[0].Type() != TypeOf(V(0)) {
  6205  		t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
  6206  	}
  6207  	f := outs[0].Float()
  6208  	if f != 3.14 {
  6209  		t.Errorf("constructed func returned %f, want %f", f, 3.14)
  6210  	}
  6211  
  6212  	// check that types already in binary are found
  6213  	type T1 int
  6214  	testCases := []struct {
  6215  		in, out  []Type
  6216  		variadic bool
  6217  		want     any
  6218  	}{
  6219  		{in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
  6220  		{in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
  6221  		{in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
  6222  		{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
  6223  		{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
  6224  	}
  6225  	for _, tt := range testCases {
  6226  		checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
  6227  	}
  6228  
  6229  	// check that variadic requires last element be a slice.
  6230  	FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
  6231  	shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
  6232  	shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
  6233  }
  6234  
  6235  type B1 struct {
  6236  	X int
  6237  	Y int
  6238  	Z int
  6239  }
  6240  
  6241  func BenchmarkFieldByName1(b *testing.B) {
  6242  	t := TypeOf(B1{})
  6243  	b.RunParallel(func(pb *testing.PB) {
  6244  		for pb.Next() {
  6245  			t.FieldByName("Z")
  6246  		}
  6247  	})
  6248  }
  6249  
  6250  func BenchmarkFieldByName2(b *testing.B) {
  6251  	t := TypeOf(S3{})
  6252  	b.RunParallel(func(pb *testing.PB) {
  6253  		for pb.Next() {
  6254  			t.FieldByName("B")
  6255  		}
  6256  	})
  6257  }
  6258  
  6259  type R0 struct {
  6260  	*R1
  6261  	*R2
  6262  	*R3
  6263  	*R4
  6264  }
  6265  
  6266  type R1 struct {
  6267  	*R5
  6268  	*R6
  6269  	*R7
  6270  	*R8
  6271  }
  6272  
  6273  type R2 R1
  6274  type R3 R1
  6275  type R4 R1
  6276  
  6277  type R5 struct {
  6278  	*R9
  6279  	*R10
  6280  	*R11
  6281  	*R12
  6282  }
  6283  
  6284  type R6 R5
  6285  type R7 R5
  6286  type R8 R5
  6287  
  6288  type R9 struct {
  6289  	*R13
  6290  	*R14
  6291  	*R15
  6292  	*R16
  6293  }
  6294  
  6295  type R10 R9
  6296  type R11 R9
  6297  type R12 R9
  6298  
  6299  type R13 struct {
  6300  	*R17
  6301  	*R18
  6302  	*R19
  6303  	*R20
  6304  }
  6305  
  6306  type R14 R13
  6307  type R15 R13
  6308  type R16 R13
  6309  
  6310  type R17 struct {
  6311  	*R21
  6312  	*R22
  6313  	*R23
  6314  	*R24
  6315  }
  6316  
  6317  type R18 R17
  6318  type R19 R17
  6319  type R20 R17
  6320  
  6321  type R21 struct {
  6322  	X int
  6323  }
  6324  
  6325  type R22 R21
  6326  type R23 R21
  6327  type R24 R21
  6328  
  6329  func TestEmbed(t *testing.T) {
  6330  	typ := TypeOf(R0{})
  6331  	f, ok := typ.FieldByName("X")
  6332  	if ok {
  6333  		t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
  6334  	}
  6335  }
  6336  
  6337  func BenchmarkFieldByName3(b *testing.B) {
  6338  	t := TypeOf(R0{})
  6339  	b.RunParallel(func(pb *testing.PB) {
  6340  		for pb.Next() {
  6341  			t.FieldByName("X")
  6342  		}
  6343  	})
  6344  }
  6345  
  6346  type S struct {
  6347  	i1 int64
  6348  	i2 int64
  6349  }
  6350  
  6351  func BenchmarkInterfaceBig(b *testing.B) {
  6352  	v := ValueOf(S{})
  6353  	b.RunParallel(func(pb *testing.PB) {
  6354  		for pb.Next() {
  6355  			v.Interface()
  6356  		}
  6357  	})
  6358  	b.StopTimer()
  6359  }
  6360  
  6361  func TestAllocsInterfaceBig(t *testing.T) {
  6362  	if testing.Short() {
  6363  		t.Skip("skipping malloc count in short mode")
  6364  	}
  6365  	v := ValueOf(S{})
  6366  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  6367  		t.Error("allocs:", allocs)
  6368  	}
  6369  }
  6370  
  6371  func BenchmarkInterfaceSmall(b *testing.B) {
  6372  	v := ValueOf(int64(0))
  6373  	b.RunParallel(func(pb *testing.PB) {
  6374  		for pb.Next() {
  6375  			v.Interface()
  6376  		}
  6377  	})
  6378  }
  6379  
  6380  func TestAllocsInterfaceSmall(t *testing.T) {
  6381  	if testing.Short() {
  6382  		t.Skip("skipping malloc count in short mode")
  6383  	}
  6384  	v := ValueOf(int64(0))
  6385  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  6386  		t.Error("allocs:", allocs)
  6387  	}
  6388  }
  6389  
  6390  // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
  6391  // The basic usage is:
  6392  //
  6393  //	for x.Next() {
  6394  //		... code using x.Maybe() or x.Choice(n) to create test cases ...
  6395  //	}
  6396  //
  6397  // Each iteration of the loop returns a different set of results, until all
  6398  // possible result sets have been explored. It is okay for different code paths
  6399  // to make different method call sequences on x, but there must be no
  6400  // other source of non-determinism in the call sequences.
  6401  //
  6402  // When faced with a new decision, x chooses randomly. Future explorations
  6403  // of that path will choose successive values for the result. Thus, stopping
  6404  // the loop after a fixed number of iterations gives somewhat stochastic
  6405  // testing.
  6406  //
  6407  // Example:
  6408  //
  6409  //	for x.Next() {
  6410  //		v := make([]bool, x.Choose(4))
  6411  //		for i := range v {
  6412  //			v[i] = x.Maybe()
  6413  //		}
  6414  //		fmt.Println(v)
  6415  //	}
  6416  //
  6417  // prints (in some order):
  6418  //
  6419  //	[]
  6420  //	[false]
  6421  //	[true]
  6422  //	[false false]
  6423  //	[false true]
  6424  //	...
  6425  //	[true true]
  6426  //	[false false false]
  6427  //	...
  6428  //	[true true true]
  6429  //	[false false false false]
  6430  //	...
  6431  //	[true true true true]
  6432  type exhaustive struct {
  6433  	r    *rand.Rand
  6434  	pos  int
  6435  	last []choice
  6436  }
  6437  
  6438  type choice struct {
  6439  	off int
  6440  	n   int
  6441  	max int
  6442  }
  6443  
  6444  func (x *exhaustive) Next() bool {
  6445  	if x.r == nil {
  6446  		x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
  6447  	}
  6448  	x.pos = 0
  6449  	if x.last == nil {
  6450  		x.last = []choice{}
  6451  		return true
  6452  	}
  6453  	for i := len(x.last) - 1; i >= 0; i-- {
  6454  		c := &x.last[i]
  6455  		if c.n+1 < c.max {
  6456  			c.n++
  6457  			x.last = x.last[:i+1]
  6458  			return true
  6459  		}
  6460  	}
  6461  	return false
  6462  }
  6463  
  6464  func (x *exhaustive) Choose(max int) int {
  6465  	if x.pos >= len(x.last) {
  6466  		x.last = append(x.last, choice{x.r.Intn(max), 0, max})
  6467  	}
  6468  	c := &x.last[x.pos]
  6469  	x.pos++
  6470  	if c.max != max {
  6471  		panic("inconsistent use of exhaustive tester")
  6472  	}
  6473  	return (c.n + c.off) % max
  6474  }
  6475  
  6476  func (x *exhaustive) Maybe() bool {
  6477  	return x.Choose(2) == 1
  6478  }
  6479  
  6480  func GCFunc(args []Value) []Value {
  6481  	runtime.GC()
  6482  	return []Value{}
  6483  }
  6484  
  6485  func TestReflectFuncTraceback(t *testing.T) {
  6486  	f := MakeFunc(TypeOf(func() {}), GCFunc)
  6487  	f.Call([]Value{})
  6488  }
  6489  
  6490  func TestReflectMethodTraceback(t *testing.T) {
  6491  	p := Point{3, 4}
  6492  	m := ValueOf(p).MethodByName("GCMethod")
  6493  	i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
  6494  	if i != 8 {
  6495  		t.Errorf("Call returned %d; want 8", i)
  6496  	}
  6497  }
  6498  
  6499  func TestSmallZero(t *testing.T) {
  6500  	type T [10]byte
  6501  	typ := TypeOf(T{})
  6502  	if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
  6503  		t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
  6504  	}
  6505  }
  6506  
  6507  func TestBigZero(t *testing.T) {
  6508  	const size = 1 << 10
  6509  	var v [size]byte
  6510  	z := Zero(ValueOf(v).Type()).Interface().([size]byte)
  6511  	for i := 0; i < size; i++ {
  6512  		if z[i] != 0 {
  6513  			t.Fatalf("Zero object not all zero, index %d", i)
  6514  		}
  6515  	}
  6516  }
  6517  
  6518  func TestZeroSet(t *testing.T) {
  6519  	type T [16]byte
  6520  	type S struct {
  6521  		a uint64
  6522  		T T
  6523  		b uint64
  6524  	}
  6525  	v := S{
  6526  		a: 0xaaaaaaaaaaaaaaaa,
  6527  		T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
  6528  		b: 0xbbbbbbbbbbbbbbbb,
  6529  	}
  6530  	ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
  6531  	if v != (S{
  6532  		a: 0xaaaaaaaaaaaaaaaa,
  6533  		b: 0xbbbbbbbbbbbbbbbb,
  6534  	}) {
  6535  		t.Fatalf("Setting a field to a Zero value didn't work")
  6536  	}
  6537  }
  6538  
  6539  func TestFieldByIndexNil(t *testing.T) {
  6540  	type P struct {
  6541  		F int
  6542  	}
  6543  	type T struct {
  6544  		*P
  6545  	}
  6546  	v := ValueOf(T{})
  6547  
  6548  	v.FieldByName("P") // should be fine
  6549  
  6550  	defer func() {
  6551  		if err := recover(); err == nil {
  6552  			t.Fatalf("no error")
  6553  		} else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
  6554  			t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
  6555  		}
  6556  	}()
  6557  	v.FieldByName("F") // should panic
  6558  
  6559  	t.Fatalf("did not panic")
  6560  }
  6561  
  6562  // Given
  6563  //	type Outer struct {
  6564  //		*Inner
  6565  //		...
  6566  //	}
  6567  // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
  6568  // The implementation is logically:
  6569  //	func (p *Outer) M() {
  6570  //		(p.Inner).M()
  6571  //	}
  6572  // but since the only change here is the replacement of one pointer receiver with another,
  6573  // the actual generated code overwrites the original receiver with the p.Inner pointer and
  6574  // then jumps to the M method expecting the *Inner receiver.
  6575  //
  6576  // During reflect.Value.Call, we create an argument frame and the associated data structures
  6577  // to describe it to the garbage collector, populate the frame, call reflect.call to
  6578  // run a function call using that frame, and then copy the results back out of the frame.
  6579  // The reflect.call function does a memmove of the frame structure onto the
  6580  // stack (to set up the inputs), runs the call, and the memmoves the stack back to
  6581  // the frame structure (to preserve the outputs).
  6582  //
  6583  // Originally reflect.call did not distinguish inputs from outputs: both memmoves
  6584  // were for the full stack frame. However, in the case where the called function was
  6585  // one of these wrappers, the rewritten receiver is almost certainly a different type
  6586  // than the original receiver. This is not a problem on the stack, where we use the
  6587  // program counter to determine the type information and understand that
  6588  // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
  6589  // memory word is now an *Inner. But in the statically typed argument frame created
  6590  // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
  6591  // off the stack into the frame will store an *Inner there, and then if a garbage collection
  6592  // happens to scan that argument frame before it is discarded, it will scan the *Inner
  6593  // memory as if it were an *Outer. If the two have different memory layouts, the
  6594  // collection will interpret the memory incorrectly.
  6595  //
  6596  // One such possible incorrect interpretation is to treat two arbitrary memory words
  6597  // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
  6598  // an interface requires dereferencing the itab word, the misinterpretation will try to
  6599  // deference Inner.P1, causing a crash during garbage collection.
  6600  //
  6601  // This came up in a real program in issue 7725.
  6602  
  6603  type Outer struct {
  6604  	*Inner
  6605  	R io.Reader
  6606  }
  6607  
  6608  type Inner struct {
  6609  	X  *Outer
  6610  	P1 uintptr
  6611  	P2 uintptr
  6612  }
  6613  
  6614  func (pi *Inner) M() {
  6615  	// Clear references to pi so that the only way the
  6616  	// garbage collection will find the pointer is in the
  6617  	// argument frame, typed as a *Outer.
  6618  	pi.X.Inner = nil
  6619  
  6620  	// Set up an interface value that will cause a crash.
  6621  	// P1 = 1 is a non-zero, so the interface looks non-nil.
  6622  	// P2 = pi ensures that the data word points into the
  6623  	// allocated heap; if not the collection skips the interface
  6624  	// value as irrelevant, without dereferencing P1.
  6625  	pi.P1 = 1
  6626  	pi.P2 = uintptr(unsafe.Pointer(pi))
  6627  }
  6628  
  6629  func TestCallMethodJump(t *testing.T) {
  6630  	// In reflect.Value.Call, trigger a garbage collection after reflect.call
  6631  	// returns but before the args frame has been discarded.
  6632  	// This is a little clumsy but makes the failure repeatable.
  6633  	*CallGC = true
  6634  
  6635  	p := &Outer{Inner: new(Inner)}
  6636  	p.Inner.X = p
  6637  	ValueOf(p).Method(0).Call(nil)
  6638  
  6639  	// Stop garbage collecting during reflect.call.
  6640  	*CallGC = false
  6641  }
  6642  
  6643  func TestCallArgLive(t *testing.T) {
  6644  	type T struct{ X, Y *string } // pointerful aggregate
  6645  
  6646  	F := func(t T) { *t.X = "ok" }
  6647  
  6648  	// In reflect.Value.Call, trigger a garbage collection in reflect.call
  6649  	// between marshaling argument and the actual call.
  6650  	*CallGC = true
  6651  
  6652  	x := new(string)
  6653  	runtime.SetFinalizer(x, func(p *string) {
  6654  		if *p != "ok" {
  6655  			t.Errorf("x dead prematurely")
  6656  		}
  6657  	})
  6658  	v := T{x, nil}
  6659  
  6660  	ValueOf(F).Call([]Value{ValueOf(v)})
  6661  
  6662  	// Stop garbage collecting during reflect.call.
  6663  	*CallGC = false
  6664  }
  6665  
  6666  func TestMakeFuncStackCopy(t *testing.T) {
  6667  	target := func(in []Value) []Value {
  6668  		runtime.GC()
  6669  		useStack(16)
  6670  		return []Value{ValueOf(9)}
  6671  	}
  6672  
  6673  	var concrete func(*int, int) int
  6674  	fn := MakeFunc(ValueOf(concrete).Type(), target)
  6675  	ValueOf(&concrete).Elem().Set(fn)
  6676  	x := concrete(nil, 7)
  6677  	if x != 9 {
  6678  		t.Errorf("have %#q want 9", x)
  6679  	}
  6680  }
  6681  
  6682  // use about n KB of stack
  6683  func useStack(n int) {
  6684  	if n == 0 {
  6685  		return
  6686  	}
  6687  	var b [1024]byte // makes frame about 1KB
  6688  	useStack(n - 1 + int(b[99]))
  6689  }
  6690  
  6691  type Impl struct{}
  6692  
  6693  func (Impl) F() {}
  6694  
  6695  func TestValueString(t *testing.T) {
  6696  	rv := ValueOf(Impl{})
  6697  	if rv.String() != "<reflect_test.Impl Value>" {
  6698  		t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
  6699  	}
  6700  
  6701  	method := rv.Method(0)
  6702  	if method.String() != "<func() Value>" {
  6703  		t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
  6704  	}
  6705  }
  6706  
  6707  func TestInvalid(t *testing.T) {
  6708  	// Used to have inconsistency between IsValid() and Kind() != Invalid.
  6709  	type T struct{ v any }
  6710  
  6711  	v := ValueOf(T{}).Field(0)
  6712  	if v.IsValid() != true || v.Kind() != Interface {
  6713  		t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
  6714  	}
  6715  	v = v.Elem()
  6716  	if v.IsValid() != false || v.Kind() != Invalid {
  6717  		t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
  6718  	}
  6719  }
  6720  
  6721  // Issue 8917.
  6722  func TestLargeGCProg(t *testing.T) {
  6723  	fv := ValueOf(func([256]*byte) {})
  6724  	fv.Call([]Value{ValueOf([256]*byte{})})
  6725  }
  6726  
  6727  func fieldIndexRecover(t Type, i int) (recovered any) {
  6728  	defer func() {
  6729  		recovered = recover()
  6730  	}()
  6731  
  6732  	t.Field(i)
  6733  	return
  6734  }
  6735  
  6736  // Issue 15046.
  6737  func TestTypeFieldOutOfRangePanic(t *testing.T) {
  6738  	typ := TypeOf(struct{ X int }{10})
  6739  	testIndices := [...]struct {
  6740  		i         int
  6741  		mustPanic bool
  6742  	}{
  6743  		0: {-2, true},
  6744  		1: {0, false},
  6745  		2: {1, true},
  6746  		3: {1 << 10, true},
  6747  	}
  6748  	for i, tt := range testIndices {
  6749  		recoveredErr := fieldIndexRecover(typ, tt.i)
  6750  		if tt.mustPanic {
  6751  			if recoveredErr == nil {
  6752  				t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
  6753  			}
  6754  		} else {
  6755  			if recoveredErr != nil {
  6756  				t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
  6757  			}
  6758  		}
  6759  	}
  6760  }
  6761  
  6762  // Issue 9179.
  6763  func TestCallGC(t *testing.T) {
  6764  	f := func(a, b, c, d, e string) {
  6765  	}
  6766  	g := func(in []Value) []Value {
  6767  		runtime.GC()
  6768  		return nil
  6769  	}
  6770  	typ := ValueOf(f).Type()
  6771  	f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
  6772  	f2("four", "five5", "six666", "seven77", "eight888")
  6773  }
  6774  
  6775  // Issue 18635 (function version).
  6776  func TestKeepFuncLive(t *testing.T) {
  6777  	// Test that we keep makeFuncImpl live as long as it is
  6778  	// referenced on the stack.
  6779  	typ := TypeOf(func(i int) {})
  6780  	var f, g func(in []Value) []Value
  6781  	f = func(in []Value) []Value {
  6782  		clobber()
  6783  		i := int(in[0].Int())
  6784  		if i > 0 {
  6785  			// We can't use Value.Call here because
  6786  			// runtime.call* will keep the makeFuncImpl
  6787  			// alive. However, by converting it to an
  6788  			// interface value and calling that,
  6789  			// reflect.callReflect is the only thing that
  6790  			// can keep the makeFuncImpl live.
  6791  			//
  6792  			// Alternate between f and g so that if we do
  6793  			// reuse the memory prematurely it's more
  6794  			// likely to get obviously corrupted.
  6795  			MakeFunc(typ, g).Interface().(func(i int))(i - 1)
  6796  		}
  6797  		return nil
  6798  	}
  6799  	g = func(in []Value) []Value {
  6800  		clobber()
  6801  		i := int(in[0].Int())
  6802  		MakeFunc(typ, f).Interface().(func(i int))(i)
  6803  		return nil
  6804  	}
  6805  	MakeFunc(typ, f).Call([]Value{ValueOf(10)})
  6806  }
  6807  
  6808  type UnExportedFirst int
  6809  
  6810  func (i UnExportedFirst) ΦExported()  {}
  6811  func (i UnExportedFirst) unexported() {}
  6812  
  6813  // Issue 21177
  6814  func TestMethodByNameUnExportedFirst(t *testing.T) {
  6815  	defer func() {
  6816  		if recover() != nil {
  6817  			t.Errorf("should not panic")
  6818  		}
  6819  	}()
  6820  	typ := TypeOf(UnExportedFirst(0))
  6821  	m, _ := typ.MethodByName("ΦExported")
  6822  	if m.Name != "ΦExported" {
  6823  		t.Errorf("got %s, expected ΦExported", m.Name)
  6824  	}
  6825  }
  6826  
  6827  // Issue 18635 (method version).
  6828  type KeepMethodLive struct{}
  6829  
  6830  func (k KeepMethodLive) Method1(i int) {
  6831  	clobber()
  6832  	if i > 0 {
  6833  		ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
  6834  	}
  6835  }
  6836  
  6837  func (k KeepMethodLive) Method2(i int) {
  6838  	clobber()
  6839  	ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
  6840  }
  6841  
  6842  func TestKeepMethodLive(t *testing.T) {
  6843  	// Test that we keep methodValue live as long as it is
  6844  	// referenced on the stack.
  6845  	KeepMethodLive{}.Method1(10)
  6846  }
  6847  
  6848  // clobber tries to clobber unreachable memory.
  6849  func clobber() {
  6850  	runtime.GC()
  6851  	for i := 1; i < 32; i++ {
  6852  		for j := 0; j < 10; j++ {
  6853  			obj := make([]*byte, i)
  6854  			sink = obj
  6855  		}
  6856  	}
  6857  	runtime.GC()
  6858  }
  6859  
  6860  func TestFuncLayout(t *testing.T) {
  6861  	align := func(x uintptr) uintptr {
  6862  		return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
  6863  	}
  6864  	var r []byte
  6865  	if goarch.PtrSize == 4 {
  6866  		r = []byte{0, 0, 0, 1}
  6867  	} else {
  6868  		r = []byte{0, 0, 1}
  6869  	}
  6870  
  6871  	type S struct {
  6872  		a, b uintptr
  6873  		c, d *byte
  6874  	}
  6875  
  6876  	type test struct {
  6877  		rcvr, typ                  Type
  6878  		size, argsize, retOffset   uintptr
  6879  		stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
  6880  		intRegs, floatRegs         int
  6881  		floatRegSize               uintptr
  6882  	}
  6883  	tests := []test{
  6884  		{
  6885  			typ:       ValueOf(func(a, b string) string { return "" }).Type(),
  6886  			size:      6 * goarch.PtrSize,
  6887  			argsize:   4 * goarch.PtrSize,
  6888  			retOffset: 4 * goarch.PtrSize,
  6889  			stack:     []byte{1, 0, 1, 0, 1},
  6890  			gc:        []byte{1, 0, 1, 0, 1},
  6891  		},
  6892  		{
  6893  			typ:       ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
  6894  			size:      align(align(3*4) + goarch.PtrSize + 2),
  6895  			argsize:   align(3*4) + goarch.PtrSize + 2,
  6896  			retOffset: align(align(3*4) + goarch.PtrSize + 2),
  6897  			stack:     r,
  6898  			gc:        r,
  6899  		},
  6900  		{
  6901  			typ:       ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
  6902  			size:      4 * goarch.PtrSize,
  6903  			argsize:   4 * goarch.PtrSize,
  6904  			retOffset: 4 * goarch.PtrSize,
  6905  			stack:     []byte{1, 0, 1, 1},
  6906  			gc:        []byte{1, 0, 1, 1},
  6907  		},
  6908  		{
  6909  			typ:       ValueOf(func(a S) {}).Type(),
  6910  			size:      4 * goarch.PtrSize,
  6911  			argsize:   4 * goarch.PtrSize,
  6912  			retOffset: 4 * goarch.PtrSize,
  6913  			stack:     []byte{0, 0, 1, 1},
  6914  			gc:        []byte{0, 0, 1, 1},
  6915  		},
  6916  		{
  6917  			rcvr:      ValueOf((*byte)(nil)).Type(),
  6918  			typ:       ValueOf(func(a uintptr, b *int) {}).Type(),
  6919  			size:      3 * goarch.PtrSize,
  6920  			argsize:   3 * goarch.PtrSize,
  6921  			retOffset: 3 * goarch.PtrSize,
  6922  			stack:     []byte{1, 0, 1},
  6923  			gc:        []byte{1, 0, 1},
  6924  		},
  6925  		{
  6926  			typ:       ValueOf(func(a uintptr) {}).Type(),
  6927  			size:      goarch.PtrSize,
  6928  			argsize:   goarch.PtrSize,
  6929  			retOffset: goarch.PtrSize,
  6930  			stack:     []byte{},
  6931  			gc:        []byte{},
  6932  		},
  6933  		{
  6934  			typ:       ValueOf(func() uintptr { return 0 }).Type(),
  6935  			size:      goarch.PtrSize,
  6936  			argsize:   0,
  6937  			retOffset: 0,
  6938  			stack:     []byte{},
  6939  			gc:        []byte{},
  6940  		},
  6941  		{
  6942  			rcvr:      ValueOf(uintptr(0)).Type(),
  6943  			typ:       ValueOf(func(a uintptr) {}).Type(),
  6944  			size:      2 * goarch.PtrSize,
  6945  			argsize:   2 * goarch.PtrSize,
  6946  			retOffset: 2 * goarch.PtrSize,
  6947  			stack:     []byte{1},
  6948  			gc:        []byte{1},
  6949  			// Note: this one is tricky, as the receiver is not a pointer. But we
  6950  			// pass the receiver by reference to the autogenerated pointer-receiver
  6951  			// version of the function.
  6952  		},
  6953  		// TODO(mknyszek): Add tests for non-zero register count.
  6954  	}
  6955  	for _, lt := range tests {
  6956  		name := lt.typ.String()
  6957  		if lt.rcvr != nil {
  6958  			name = lt.rcvr.String() + "." + name
  6959  		}
  6960  		t.Run(name, func(t *testing.T) {
  6961  			defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
  6962  
  6963  			typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
  6964  			if typ.Size() != lt.size {
  6965  				t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
  6966  			}
  6967  			if argsize != lt.argsize {
  6968  				t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
  6969  			}
  6970  			if retOffset != lt.retOffset {
  6971  				t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
  6972  			}
  6973  			if !bytes.Equal(stack, lt.stack) {
  6974  				t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
  6975  			}
  6976  			if !bytes.Equal(gc, lt.gc) {
  6977  				t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
  6978  			}
  6979  			if !bytes.Equal(inRegs, lt.inRegs) {
  6980  				t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
  6981  			}
  6982  			if !bytes.Equal(outRegs, lt.outRegs) {
  6983  				t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
  6984  			}
  6985  			if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
  6986  				t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
  6987  			}
  6988  		})
  6989  	}
  6990  }
  6991  
  6992  func verifyGCBits(t *testing.T, typ Type, bits []byte) {
  6993  	heapBits := GCBits(New(typ).Interface())
  6994  	if !bytes.Equal(heapBits, bits) {
  6995  		_, _, line, _ := runtime.Caller(1)
  6996  		t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
  6997  	}
  6998  }
  6999  
  7000  func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
  7001  	// Creating a slice causes the runtime to repeat a bitmap,
  7002  	// which exercises a different path from making the compiler
  7003  	// repeat a bitmap for a small array or executing a repeat in
  7004  	// a GC program.
  7005  	val := MakeSlice(typ, 0, cap)
  7006  	data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
  7007  	heapBits := GCBits(data.Interface())
  7008  	// Repeat the bitmap for the slice size, trimming scalars in
  7009  	// the last element.
  7010  	bits = rep(cap, bits)
  7011  	for len(bits) > 0 && bits[len(bits)-1] == 0 {
  7012  		bits = bits[:len(bits)-1]
  7013  	}
  7014  	if !bytes.Equal(heapBits, bits) {
  7015  		t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
  7016  	}
  7017  }
  7018  
  7019  func TestGCBits(t *testing.T) {
  7020  	verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
  7021  
  7022  	// Building blocks for types seen by the compiler (like [2]Xscalar).
  7023  	// The compiler will create the type structures for the derived types,
  7024  	// including their GC metadata.
  7025  	type Xscalar struct{ x uintptr }
  7026  	type Xptr struct{ x *byte }
  7027  	type Xptrscalar struct {
  7028  		*byte
  7029  		uintptr
  7030  	}
  7031  	type Xscalarptr struct {
  7032  		uintptr
  7033  		*byte
  7034  	}
  7035  	type Xbigptrscalar struct {
  7036  		_ [100]*byte
  7037  		_ [100]uintptr
  7038  	}
  7039  
  7040  	var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
  7041  	{
  7042  		// Building blocks for types constructed by reflect.
  7043  		// This code is in a separate block so that code below
  7044  		// cannot accidentally refer to these.
  7045  		// The compiler must NOT see types derived from these
  7046  		// (for example, [2]Scalar must NOT appear in the program),
  7047  		// or else reflect will use it instead of having to construct one.
  7048  		// The goal is to test the construction.
  7049  		type Scalar struct{ x uintptr }
  7050  		type Ptr struct{ x *byte }
  7051  		type Ptrscalar struct {
  7052  			*byte
  7053  			uintptr
  7054  		}
  7055  		type Scalarptr struct {
  7056  			uintptr
  7057  			*byte
  7058  		}
  7059  		type Bigptrscalar struct {
  7060  			_ [100]*byte
  7061  			_ [100]uintptr
  7062  		}
  7063  		type Int64 int64
  7064  		Tscalar = TypeOf(Scalar{})
  7065  		Tint64 = TypeOf(Int64(0))
  7066  		Tptr = TypeOf(Ptr{})
  7067  		Tscalarptr = TypeOf(Scalarptr{})
  7068  		Tptrscalar = TypeOf(Ptrscalar{})
  7069  		Tbigptrscalar = TypeOf(Bigptrscalar{})
  7070  	}
  7071  
  7072  	empty := []byte{}
  7073  
  7074  	verifyGCBits(t, TypeOf(Xscalar{}), empty)
  7075  	verifyGCBits(t, Tscalar, empty)
  7076  	verifyGCBits(t, TypeOf(Xptr{}), lit(1))
  7077  	verifyGCBits(t, Tptr, lit(1))
  7078  	verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
  7079  	verifyGCBits(t, Tscalarptr, lit(0, 1))
  7080  	verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
  7081  	verifyGCBits(t, Tptrscalar, lit(1))
  7082  
  7083  	verifyGCBits(t, TypeOf([0]Xptr{}), empty)
  7084  	verifyGCBits(t, ArrayOf(0, Tptr), empty)
  7085  	verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
  7086  	verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
  7087  	verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
  7088  	verifyGCBits(t, ArrayOf(2, Tscalar), empty)
  7089  	verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
  7090  	verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
  7091  	verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
  7092  	verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
  7093  	verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
  7094  	verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
  7095  	verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
  7096  	verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
  7097  	verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
  7098  	verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
  7099  	verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
  7100  	verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
  7101  	verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
  7102  	verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
  7103  	verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
  7104  	verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
  7105  	verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
  7106  	verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
  7107  	verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
  7108  	verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
  7109  
  7110  	verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
  7111  	verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
  7112  	verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
  7113  	verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
  7114  	verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
  7115  	verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
  7116  	verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
  7117  	verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
  7118  	verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
  7119  	verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
  7120  	verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
  7121  	verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
  7122  	verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
  7123  	verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
  7124  	verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
  7125  	verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
  7126  	verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
  7127  	verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
  7128  	verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
  7129  	verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
  7130  	verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
  7131  	verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
  7132  	verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
  7133  	verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
  7134  	verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
  7135  	verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
  7136  
  7137  	verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
  7138  	verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
  7139  
  7140  	verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
  7141  	verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
  7142  
  7143  	verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
  7144  	verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
  7145  
  7146  	verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
  7147  	verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
  7148  
  7149  	verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
  7150  	verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
  7151  
  7152  	hdr := make([]byte, 8/goarch.PtrSize)
  7153  
  7154  	verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
  7155  		verifyGCBits(t, MapBucketOf(k, e), want)
  7156  		verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
  7157  	}
  7158  	verifyMapBucket(t,
  7159  		Tscalar, Tptr,
  7160  		map[Xscalar]Xptr(nil),
  7161  		join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
  7162  	verifyMapBucket(t,
  7163  		Tscalarptr, Tptr,
  7164  		map[Xscalarptr]Xptr(nil),
  7165  		join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
  7166  	verifyMapBucket(t, Tint64, Tptr,
  7167  		map[int64]Xptr(nil),
  7168  		join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
  7169  	verifyMapBucket(t,
  7170  		Tscalar, Tscalar,
  7171  		map[Xscalar]Xscalar(nil),
  7172  		empty)
  7173  	verifyMapBucket(t,
  7174  		ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
  7175  		map[[2]Xscalarptr][3]Xptrscalar(nil),
  7176  		join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
  7177  	verifyMapBucket(t,
  7178  		ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
  7179  		map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
  7180  		join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
  7181  	verifyMapBucket(t,
  7182  		ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
  7183  		map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
  7184  		join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
  7185  	verifyMapBucket(t,
  7186  		ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
  7187  		map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
  7188  		join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
  7189  	verifyMapBucket(t,
  7190  		ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
  7191  		map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
  7192  		join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
  7193  }
  7194  
  7195  func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
  7196  func join(b ...[]byte) []byte    { return bytes.Join(b, nil) }
  7197  func lit(x ...byte) []byte       { return x }
  7198  
  7199  func TestTypeOfTypeOf(t *testing.T) {
  7200  	// Check that all the type constructors return concrete *rtype implementations.
  7201  	// It's difficult to test directly because the reflect package is only at arm's length.
  7202  	// The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
  7203  	check := func(name string, typ Type) {
  7204  		if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
  7205  			t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
  7206  		}
  7207  	}
  7208  
  7209  	type T struct{ int }
  7210  	check("TypeOf", TypeOf(T{}))
  7211  
  7212  	check("ArrayOf", ArrayOf(10, TypeOf(T{})))
  7213  	check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
  7214  	check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
  7215  	check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
  7216  	check("PtrTo", PointerTo(TypeOf(T{})))
  7217  	check("SliceOf", SliceOf(TypeOf(T{})))
  7218  }
  7219  
  7220  type XM struct{ _ bool }
  7221  
  7222  func (*XM) String() string { return "" }
  7223  
  7224  func TestPtrToMethods(t *testing.T) {
  7225  	var y struct{ XM }
  7226  	yp := New(TypeOf(y)).Interface()
  7227  	_, ok := yp.(fmt.Stringer)
  7228  	if !ok {
  7229  		t.Fatal("does not implement Stringer, but should")
  7230  	}
  7231  }
  7232  
  7233  func TestMapAlloc(t *testing.T) {
  7234  	m := ValueOf(make(map[int]int, 10))
  7235  	k := ValueOf(5)
  7236  	v := ValueOf(7)
  7237  	allocs := testing.AllocsPerRun(100, func() {
  7238  		m.SetMapIndex(k, v)
  7239  	})
  7240  	if allocs > 0.5 {
  7241  		t.Errorf("allocs per map assignment: want 0 got %f", allocs)
  7242  	}
  7243  
  7244  	const size = 1000
  7245  	tmp := 0
  7246  	val := ValueOf(&tmp).Elem()
  7247  	allocs = testing.AllocsPerRun(100, func() {
  7248  		mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
  7249  		// Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
  7250  		for i := 0; i < size/2; i++ {
  7251  			val.SetInt(int64(i))
  7252  			mv.SetMapIndex(val, val)
  7253  		}
  7254  	})
  7255  	if allocs > 10 {
  7256  		t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
  7257  	}
  7258  	// Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
  7259  	// the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
  7260  	// map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
  7261  }
  7262  
  7263  func TestChanAlloc(t *testing.T) {
  7264  	// Note: for a chan int, the return Value must be allocated, so we
  7265  	// use a chan *int instead.
  7266  	c := ValueOf(make(chan *int, 1))
  7267  	v := ValueOf(new(int))
  7268  	allocs := testing.AllocsPerRun(100, func() {
  7269  		c.Send(v)
  7270  		_, _ = c.Recv()
  7271  	})
  7272  	if allocs < 0.5 || allocs > 1.5 {
  7273  		t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
  7274  	}
  7275  	// Note: there is one allocation in reflect.recv which seems to be
  7276  	// a limitation of escape analysis. If that is ever fixed the
  7277  	// allocs < 0.5 condition will trigger and this test should be fixed.
  7278  }
  7279  
  7280  type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
  7281  
  7282  type nameTest struct {
  7283  	v    any
  7284  	want string
  7285  }
  7286  
  7287  var nameTests = []nameTest{
  7288  	{(*int32)(nil), "int32"},
  7289  	{(*D1)(nil), "D1"},
  7290  	{(*[]D1)(nil), ""},
  7291  	{(*chan D1)(nil), ""},
  7292  	{(*func() D1)(nil), ""},
  7293  	{(*<-chan D1)(nil), ""},
  7294  	{(*chan<- D1)(nil), ""},
  7295  	{(*any)(nil), ""},
  7296  	{(*interface {
  7297  		F()
  7298  	})(nil), ""},
  7299  	{(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
  7300  }
  7301  
  7302  func TestNames(t *testing.T) {
  7303  	for _, test := range nameTests {
  7304  		typ := TypeOf(test.v).Elem()
  7305  		if got := typ.Name(); got != test.want {
  7306  			t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
  7307  		}
  7308  	}
  7309  }
  7310  
  7311  func TestExported(t *testing.T) {
  7312  	type ΦExported struct{}
  7313  	type φUnexported struct{}
  7314  	type BigP *big
  7315  	type P int
  7316  	type p *P
  7317  	type P2 p
  7318  	type p3 p
  7319  
  7320  	type exportTest struct {
  7321  		v    any
  7322  		want bool
  7323  	}
  7324  	exportTests := []exportTest{
  7325  		{D1{}, true},
  7326  		{(*D1)(nil), true},
  7327  		{big{}, false},
  7328  		{(*big)(nil), false},
  7329  		{(BigP)(nil), true},
  7330  		{(*BigP)(nil), true},
  7331  		{ΦExported{}, true},
  7332  		{φUnexported{}, false},
  7333  		{P(0), true},
  7334  		{(p)(nil), false},
  7335  		{(P2)(nil), true},
  7336  		{(p3)(nil), false},
  7337  	}
  7338  
  7339  	for i, test := range exportTests {
  7340  		typ := TypeOf(test.v)
  7341  		if got := IsExported(typ); got != test.want {
  7342  			t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
  7343  		}
  7344  	}
  7345  }
  7346  
  7347  func TestTypeStrings(t *testing.T) {
  7348  	type stringTest struct {
  7349  		typ  Type
  7350  		want string
  7351  	}
  7352  	stringTests := []stringTest{
  7353  		{TypeOf(func(int) {}), "func(int)"},
  7354  		{FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
  7355  		{TypeOf(XM{}), "reflect_test.XM"},
  7356  		{TypeOf(new(XM)), "*reflect_test.XM"},
  7357  		{TypeOf(new(XM).String), "func() string"},
  7358  		{TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
  7359  		{ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
  7360  		{MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
  7361  		{ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
  7362  		{ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
  7363  	}
  7364  
  7365  	for i, test := range stringTests {
  7366  		if got, want := test.typ.String(), test.want; got != want {
  7367  			t.Errorf("type %d String()=%q, want %q", i, got, want)
  7368  		}
  7369  	}
  7370  }
  7371  
  7372  func TestOffsetLock(t *testing.T) {
  7373  	var wg sync.WaitGroup
  7374  	for i := 0; i < 4; i++ {
  7375  		i := i
  7376  		wg.Add(1)
  7377  		go func() {
  7378  			for j := 0; j < 50; j++ {
  7379  				ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
  7380  			}
  7381  			wg.Done()
  7382  		}()
  7383  	}
  7384  	wg.Wait()
  7385  }
  7386  
  7387  func BenchmarkNew(b *testing.B) {
  7388  	v := TypeOf(XM{})
  7389  	b.RunParallel(func(pb *testing.PB) {
  7390  		for pb.Next() {
  7391  			New(v)
  7392  		}
  7393  	})
  7394  }
  7395  
  7396  func BenchmarkMap(b *testing.B) {
  7397  	type V *int
  7398  	type S string
  7399  	value := ValueOf((V)(nil))
  7400  	stringKeys := []string{}
  7401  	mapOfStrings := map[string]V{}
  7402  	uint64Keys := []uint64{}
  7403  	mapOfUint64s := map[uint64]V{}
  7404  	userStringKeys := []S{}
  7405  	mapOfUserStrings := map[S]V{}
  7406  	for i := 0; i < 100; i++ {
  7407  		stringKey := fmt.Sprintf("key%d", i)
  7408  		stringKeys = append(stringKeys, stringKey)
  7409  		mapOfStrings[stringKey] = nil
  7410  
  7411  		uint64Key := uint64(i)
  7412  		uint64Keys = append(uint64Keys, uint64Key)
  7413  		mapOfUint64s[uint64Key] = nil
  7414  
  7415  		userStringKey := S(fmt.Sprintf("key%d", i))
  7416  		userStringKeys = append(userStringKeys, userStringKey)
  7417  		mapOfUserStrings[userStringKey] = nil
  7418  	}
  7419  
  7420  	tests := []struct {
  7421  		label          string
  7422  		m, keys, value Value
  7423  	}{
  7424  		{"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
  7425  		{"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
  7426  		{"UserStringKeys", ValueOf(mapOfUserStrings), ValueOf(userStringKeys), value},
  7427  	}
  7428  
  7429  	for _, tt := range tests {
  7430  		b.Run(tt.label, func(b *testing.B) {
  7431  			b.Run("MapIndex", func(b *testing.B) {
  7432  				b.ReportAllocs()
  7433  				for i := 0; i < b.N; i++ {
  7434  					for j := tt.keys.Len() - 1; j >= 0; j-- {
  7435  						tt.m.MapIndex(tt.keys.Index(j))
  7436  					}
  7437  				}
  7438  			})
  7439  			b.Run("SetMapIndex", func(b *testing.B) {
  7440  				b.ReportAllocs()
  7441  				for i := 0; i < b.N; i++ {
  7442  					for j := tt.keys.Len() - 1; j >= 0; j-- {
  7443  						tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
  7444  					}
  7445  				}
  7446  			})
  7447  		})
  7448  	}
  7449  }
  7450  
  7451  func TestSwapper(t *testing.T) {
  7452  	type I int
  7453  	var a, b, c I
  7454  	type pair struct {
  7455  		x, y int
  7456  	}
  7457  	type pairPtr struct {
  7458  		x, y int
  7459  		p    *I
  7460  	}
  7461  	type S string
  7462  
  7463  	tests := []struct {
  7464  		in   any
  7465  		i, j int
  7466  		want any
  7467  	}{
  7468  		{
  7469  			in:   []int{1, 20, 300},
  7470  			i:    0,
  7471  			j:    2,
  7472  			want: []int{300, 20, 1},
  7473  		},
  7474  		{
  7475  			in:   []uintptr{1, 20, 300},
  7476  			i:    0,
  7477  			j:    2,
  7478  			want: []uintptr{300, 20, 1},
  7479  		},
  7480  		{
  7481  			in:   []int16{1, 20, 300},
  7482  			i:    0,
  7483  			j:    2,
  7484  			want: []int16{300, 20, 1},
  7485  		},
  7486  		{
  7487  			in:   []int8{1, 20, 100},
  7488  			i:    0,
  7489  			j:    2,
  7490  			want: []int8{100, 20, 1},
  7491  		},
  7492  		{
  7493  			in:   []*I{&a, &b, &c},
  7494  			i:    0,
  7495  			j:    2,
  7496  			want: []*I{&c, &b, &a},
  7497  		},
  7498  		{
  7499  			in:   []string{"eric", "sergey", "larry"},
  7500  			i:    0,
  7501  			j:    2,
  7502  			want: []string{"larry", "sergey", "eric"},
  7503  		},
  7504  		{
  7505  			in:   []S{"eric", "sergey", "larry"},
  7506  			i:    0,
  7507  			j:    2,
  7508  			want: []S{"larry", "sergey", "eric"},
  7509  		},
  7510  		{
  7511  			in:   []pair{{1, 2}, {3, 4}, {5, 6}},
  7512  			i:    0,
  7513  			j:    2,
  7514  			want: []pair{{5, 6}, {3, 4}, {1, 2}},
  7515  		},
  7516  		{
  7517  			in:   []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
  7518  			i:    0,
  7519  			j:    2,
  7520  			want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
  7521  		},
  7522  	}
  7523  
  7524  	for i, tt := range tests {
  7525  		inStr := fmt.Sprint(tt.in)
  7526  		Swapper(tt.in)(tt.i, tt.j)
  7527  		if !DeepEqual(tt.in, tt.want) {
  7528  			t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
  7529  		}
  7530  	}
  7531  }
  7532  
  7533  // TestUnaddressableField tests that the reflect package will not allow
  7534  // a type from another package to be used as a named type with an
  7535  // unexported field.
  7536  //
  7537  // This ensures that unexported fields cannot be modified by other packages.
  7538  func TestUnaddressableField(t *testing.T) {
  7539  	var b Buffer // type defined in reflect, a different package
  7540  	var localBuffer struct {
  7541  		buf []byte
  7542  	}
  7543  	lv := ValueOf(&localBuffer).Elem()
  7544  	rv := ValueOf(b)
  7545  	shouldPanic("Set", func() {
  7546  		lv.Set(rv)
  7547  	})
  7548  }
  7549  
  7550  type Tint int
  7551  
  7552  type Tint2 = Tint
  7553  
  7554  type Talias1 struct {
  7555  	byte
  7556  	uint8
  7557  	int
  7558  	int32
  7559  	rune
  7560  }
  7561  
  7562  type Talias2 struct {
  7563  	Tint
  7564  	Tint2
  7565  }
  7566  
  7567  func TestAliasNames(t *testing.T) {
  7568  	t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
  7569  	out := fmt.Sprintf("%#v", t1)
  7570  	want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
  7571  	if out != want {
  7572  		t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
  7573  	}
  7574  
  7575  	t2 := Talias2{Tint: 1, Tint2: 2}
  7576  	out = fmt.Sprintf("%#v", t2)
  7577  	want = "reflect_test.Talias2{Tint:1, Tint2:2}"
  7578  	if out != want {
  7579  		t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
  7580  	}
  7581  }
  7582  
  7583  func TestIssue22031(t *testing.T) {
  7584  	type s []struct{ C int }
  7585  
  7586  	type t1 struct{ s }
  7587  	type t2 struct{ f s }
  7588  
  7589  	tests := []Value{
  7590  		ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
  7591  		ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
  7592  	}
  7593  
  7594  	for i, test := range tests {
  7595  		if test.CanSet() {
  7596  			t.Errorf("%d: CanSet: got true, want false", i)
  7597  		}
  7598  	}
  7599  }
  7600  
  7601  type NonExportedFirst int
  7602  
  7603  func (i NonExportedFirst) ΦExported()       {}
  7604  func (i NonExportedFirst) nonexported() int { panic("wrong") }
  7605  
  7606  func TestIssue22073(t *testing.T) {
  7607  	m := ValueOf(NonExportedFirst(0)).Method(0)
  7608  
  7609  	if got := m.Type().NumOut(); got != 0 {
  7610  		t.Errorf("NumOut: got %v, want 0", got)
  7611  	}
  7612  
  7613  	// Shouldn't panic.
  7614  	m.Call(nil)
  7615  }
  7616  
  7617  func TestMapIterNonEmptyMap(t *testing.T) {
  7618  	m := map[string]int{"one": 1, "two": 2, "three": 3}
  7619  	iter := ValueOf(m).MapRange()
  7620  	if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
  7621  		t.Errorf("iterator returned %s (after sorting), want %s", got, want)
  7622  	}
  7623  }
  7624  
  7625  func TestMapIterNilMap(t *testing.T) {
  7626  	var m map[string]int
  7627  	iter := ValueOf(m).MapRange()
  7628  	if got, want := iterateToString(iter), `[]`; got != want {
  7629  		t.Errorf("non-empty result iteratoring nil map: %s", got)
  7630  	}
  7631  }
  7632  
  7633  func TestMapIterReset(t *testing.T) {
  7634  	iter := new(MapIter)
  7635  
  7636  	// Use of zero iterator should panic.
  7637  	func() {
  7638  		defer func() { recover() }()
  7639  		iter.Next()
  7640  		t.Error("Next did not panic")
  7641  	}()
  7642  
  7643  	// Reset to new Map should work.
  7644  	m := map[string]int{"one": 1, "two": 2, "three": 3}
  7645  	iter.Reset(ValueOf(m))
  7646  	if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
  7647  		t.Errorf("iterator returned %s (after sorting), want %s", got, want)
  7648  	}
  7649  
  7650  	// Reset to Zero value should work, but iterating over it should panic.
  7651  	iter.Reset(Value{})
  7652  	func() {
  7653  		defer func() { recover() }()
  7654  		iter.Next()
  7655  		t.Error("Next did not panic")
  7656  	}()
  7657  
  7658  	// Reset to a different Map with different types should work.
  7659  	m2 := map[int]string{1: "one", 2: "two", 3: "three"}
  7660  	iter.Reset(ValueOf(m2))
  7661  	if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
  7662  		t.Errorf("iterator returned %s (after sorting), want %s", got, want)
  7663  	}
  7664  
  7665  	// Check that Reset, Next, and SetKey/SetValue play nicely together.
  7666  	m3 := map[uint64]uint64{
  7667  		1 << 0: 1 << 1,
  7668  		1 << 1: 1 << 2,
  7669  		1 << 2: 1 << 3,
  7670  	}
  7671  	kv := New(TypeOf(uint64(0))).Elem()
  7672  	for i := 0; i < 5; i++ {
  7673  		var seenk, seenv uint64
  7674  		iter.Reset(ValueOf(m3))
  7675  		for iter.Next() {
  7676  			kv.SetIterKey(iter)
  7677  			seenk ^= kv.Uint()
  7678  			kv.SetIterValue(iter)
  7679  			seenv ^= kv.Uint()
  7680  		}
  7681  		if seenk != 0b111 {
  7682  			t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
  7683  		}
  7684  		if seenv != 0b1110 {
  7685  			t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
  7686  		}
  7687  	}
  7688  
  7689  	// Reset should not allocate.
  7690  	n := int(testing.AllocsPerRun(10, func() {
  7691  		iter.Reset(ValueOf(m2))
  7692  		iter.Reset(Value{})
  7693  	}))
  7694  	if n > 0 {
  7695  		t.Errorf("MapIter.Reset allocated %d times", n)
  7696  	}
  7697  }
  7698  
  7699  func TestMapIterSafety(t *testing.T) {
  7700  	// Using a zero MapIter causes a panic, but not a crash.
  7701  	func() {
  7702  		defer func() { recover() }()
  7703  		new(MapIter).Key()
  7704  		t.Fatal("Key did not panic")
  7705  	}()
  7706  	func() {
  7707  		defer func() { recover() }()
  7708  		new(MapIter).Value()
  7709  		t.Fatal("Value did not panic")
  7710  	}()
  7711  	func() {
  7712  		defer func() { recover() }()
  7713  		new(MapIter).Next()
  7714  		t.Fatal("Next did not panic")
  7715  	}()
  7716  
  7717  	// Calling Key/Value on a MapIter before Next
  7718  	// causes a panic, but not a crash.
  7719  	var m map[string]int
  7720  	iter := ValueOf(m).MapRange()
  7721  
  7722  	func() {
  7723  		defer func() { recover() }()
  7724  		iter.Key()
  7725  		t.Fatal("Key did not panic")
  7726  	}()
  7727  	func() {
  7728  		defer func() { recover() }()
  7729  		iter.Value()
  7730  		t.Fatal("Value did not panic")
  7731  	}()
  7732  
  7733  	// Calling Next, Key, or Value on an exhausted iterator
  7734  	// causes a panic, but not a crash.
  7735  	iter.Next() // -> false
  7736  	func() {
  7737  		defer func() { recover() }()
  7738  		iter.Key()
  7739  		t.Fatal("Key did not panic")
  7740  	}()
  7741  	func() {
  7742  		defer func() { recover() }()
  7743  		iter.Value()
  7744  		t.Fatal("Value did not panic")
  7745  	}()
  7746  	func() {
  7747  		defer func() { recover() }()
  7748  		iter.Next()
  7749  		t.Fatal("Next did not panic")
  7750  	}()
  7751  }
  7752  
  7753  func TestMapIterNext(t *testing.T) {
  7754  	// The first call to Next should reflect any
  7755  	// insertions to the map since the iterator was created.
  7756  	m := map[string]int{}
  7757  	iter := ValueOf(m).MapRange()
  7758  	m["one"] = 1
  7759  	if got, want := iterateToString(iter), `[one: 1]`; got != want {
  7760  		t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
  7761  	}
  7762  }
  7763  
  7764  func BenchmarkMapIterNext(b *testing.B) {
  7765  	m := ValueOf(map[string]int{"a": 0, "b": 1, "c": 2, "d": 3})
  7766  	it := m.MapRange()
  7767  	for i := 0; i < b.N; i++ {
  7768  		for it.Next() {
  7769  		}
  7770  		it.Reset(m)
  7771  	}
  7772  }
  7773  
  7774  func TestMapIterDelete0(t *testing.T) {
  7775  	// Delete all elements before first iteration.
  7776  	m := map[string]int{"one": 1, "two": 2, "three": 3}
  7777  	iter := ValueOf(m).MapRange()
  7778  	delete(m, "one")
  7779  	delete(m, "two")
  7780  	delete(m, "three")
  7781  	if got, want := iterateToString(iter), `[]`; got != want {
  7782  		t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
  7783  	}
  7784  }
  7785  
  7786  func TestMapIterDelete1(t *testing.T) {
  7787  	// Delete all elements after first iteration.
  7788  	m := map[string]int{"one": 1, "two": 2, "three": 3}
  7789  	iter := ValueOf(m).MapRange()
  7790  	var got []string
  7791  	for iter.Next() {
  7792  		got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
  7793  		delete(m, "one")
  7794  		delete(m, "two")
  7795  		delete(m, "three")
  7796  	}
  7797  	if len(got) != 1 {
  7798  		t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
  7799  	}
  7800  }
  7801  
  7802  // iterateToString returns the set of elements
  7803  // returned by an iterator in readable form.
  7804  func iterateToString(it *MapIter) string {
  7805  	var got []string
  7806  	for it.Next() {
  7807  		line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
  7808  		got = append(got, line)
  7809  	}
  7810  	sort.Strings(got)
  7811  	return "[" + strings.Join(got, ", ") + "]"
  7812  }
  7813  
  7814  func TestConvertibleTo(t *testing.T) {
  7815  	t1 := ValueOf(example1.MyStruct{}).Type()
  7816  	t2 := ValueOf(example2.MyStruct{}).Type()
  7817  
  7818  	// Shouldn't raise stack overflow
  7819  	if t1.ConvertibleTo(t2) {
  7820  		t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
  7821  	}
  7822  
  7823  	t3 := ValueOf([]example1.MyStruct{}).Type()
  7824  	t4 := ValueOf([]example2.MyStruct{}).Type()
  7825  
  7826  	if t3.ConvertibleTo(t4) {
  7827  		t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
  7828  	}
  7829  }
  7830  
  7831  func TestSetIter(t *testing.T) {
  7832  	data := map[string]int{
  7833  		"foo": 1,
  7834  		"bar": 2,
  7835  		"baz": 3,
  7836  	}
  7837  
  7838  	m := ValueOf(data)
  7839  	i := m.MapRange()
  7840  	k := New(TypeOf("")).Elem()
  7841  	v := New(TypeOf(0)).Elem()
  7842  	shouldPanic("Value.SetIterKey called before Next", func() {
  7843  		k.SetIterKey(i)
  7844  	})
  7845  	shouldPanic("Value.SetIterValue called before Next", func() {
  7846  		v.SetIterValue(i)
  7847  	})
  7848  	data2 := map[string]int{}
  7849  	for i.Next() {
  7850  		k.SetIterKey(i)
  7851  		v.SetIterValue(i)
  7852  		data2[k.Interface().(string)] = v.Interface().(int)
  7853  	}
  7854  	if !DeepEqual(data, data2) {
  7855  		t.Errorf("maps not equal, got %v want %v", data2, data)
  7856  	}
  7857  	shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
  7858  		k.SetIterKey(i)
  7859  	})
  7860  	shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
  7861  		v.SetIterValue(i)
  7862  	})
  7863  
  7864  	i.Reset(m)
  7865  	i.Next()
  7866  	shouldPanic("Value.SetIterKey using unaddressable value", func() {
  7867  		ValueOf("").SetIterKey(i)
  7868  	})
  7869  	shouldPanic("Value.SetIterValue using unaddressable value", func() {
  7870  		ValueOf(0).SetIterValue(i)
  7871  	})
  7872  	shouldPanic("value of type string is not assignable to type int", func() {
  7873  		New(TypeOf(0)).Elem().SetIterKey(i)
  7874  	})
  7875  	shouldPanic("value of type int is not assignable to type string", func() {
  7876  		New(TypeOf("")).Elem().SetIterValue(i)
  7877  	})
  7878  
  7879  	// Make sure assignment conversion works.
  7880  	var x any
  7881  	y := ValueOf(&x).Elem()
  7882  	y.SetIterKey(i)
  7883  	if _, ok := data[x.(string)]; !ok {
  7884  		t.Errorf("got key %s which is not in map", x)
  7885  	}
  7886  	y.SetIterValue(i)
  7887  	if x.(int) < 1 || x.(int) > 3 {
  7888  		t.Errorf("got value %d which is not in map", x)
  7889  	}
  7890  
  7891  	// Try some key/value types which are direct interfaces.
  7892  	a := 88
  7893  	b := 99
  7894  	pp := map[*int]*int{
  7895  		&a: &b,
  7896  	}
  7897  	i = ValueOf(pp).MapRange()
  7898  	i.Next()
  7899  	y.SetIterKey(i)
  7900  	if got := *y.Interface().(*int); got != a {
  7901  		t.Errorf("pointer incorrect: got %d want %d", got, a)
  7902  	}
  7903  	y.SetIterValue(i)
  7904  	if got := *y.Interface().(*int); got != b {
  7905  		t.Errorf("pointer incorrect: got %d want %d", got, b)
  7906  	}
  7907  }
  7908  
  7909  //go:notinheap
  7910  type nih struct{ x int }
  7911  
  7912  var global_nih = nih{x: 7}
  7913  
  7914  func TestNotInHeapDeref(t *testing.T) {
  7915  	// See issue 48399.
  7916  	v := ValueOf((*nih)(nil))
  7917  	v.Elem()
  7918  	shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) })
  7919  
  7920  	v = ValueOf(&global_nih)
  7921  	if got := v.Elem().Field(0).Int(); got != 7 {
  7922  		t.Fatalf("got %d, want 7", got)
  7923  	}
  7924  
  7925  	v = ValueOf((*nih)(unsafe.Pointer(new(int))))
  7926  	shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() })
  7927  	shouldPanic("reflect: reflect.Value.Pointer on an invalid notinheap pointer", func() { v.Pointer() })
  7928  	shouldPanic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer", func() { v.UnsafePointer() })
  7929  }
  7930  
  7931  func TestMethodCallValueCodePtr(t *testing.T) {
  7932  	m := ValueOf(Point{}).Method(1)
  7933  	want := MethodValueCallCodePtr()
  7934  	if got := uintptr(m.UnsafePointer()); got != want {
  7935  		t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
  7936  	}
  7937  	if got := m.Pointer(); got != want {
  7938  		t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
  7939  	}
  7940  }
  7941  
  7942  type A struct{}
  7943  type B[T any] struct{}
  7944  
  7945  func TestIssue50208(t *testing.T) {
  7946  	want1 := "B[reflect_test.A]"
  7947  	if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
  7948  		t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
  7949  	}
  7950  	want2 := "B[reflect_test.B[reflect_test.A]]"
  7951  	if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
  7952  		t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
  7953  	}
  7954  }
  7955  
  7956  func TestNegativeKindString(t *testing.T) {
  7957  	x := -1
  7958  	s := Kind(x).String()
  7959  	want := "kind-1"
  7960  	if s != want {
  7961  		t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
  7962  	}
  7963  }
  7964  
  7965  type (
  7966  	namedBool  bool
  7967  	namedBytes []byte
  7968  )
  7969  
  7970  var sourceAll = struct {
  7971  	Bool         Value
  7972  	String       Value
  7973  	Bytes        Value
  7974  	NamedBytes   Value
  7975  	BytesArray   Value
  7976  	SliceAny     Value
  7977  	MapStringAny Value
  7978  }{
  7979  	Bool:         ValueOf(new(bool)).Elem(),
  7980  	String:       ValueOf(new(string)).Elem(),
  7981  	Bytes:        ValueOf(new([]byte)).Elem(),
  7982  	NamedBytes:   ValueOf(new(namedBytes)).Elem(),
  7983  	BytesArray:   ValueOf(new([32]byte)).Elem(),
  7984  	SliceAny:     ValueOf(new([]any)).Elem(),
  7985  	MapStringAny: ValueOf(new(map[string]any)).Elem(),
  7986  }
  7987  
  7988  var sinkAll struct {
  7989  	RawBool   bool
  7990  	RawString string
  7991  	RawBytes  []byte
  7992  	RawInt    int
  7993  }
  7994  
  7995  func BenchmarkBool(b *testing.B) {
  7996  	for i := 0; i < b.N; i++ {
  7997  		sinkAll.RawBool = sourceAll.Bool.Bool()
  7998  	}
  7999  }
  8000  
  8001  func BenchmarkString(b *testing.B) {
  8002  	for i := 0; i < b.N; i++ {
  8003  		sinkAll.RawString = sourceAll.String.String()
  8004  	}
  8005  }
  8006  
  8007  func BenchmarkBytes(b *testing.B) {
  8008  	for i := 0; i < b.N; i++ {
  8009  		sinkAll.RawBytes = sourceAll.Bytes.Bytes()
  8010  	}
  8011  }
  8012  
  8013  func BenchmarkNamedBytes(b *testing.B) {
  8014  	for i := 0; i < b.N; i++ {
  8015  		sinkAll.RawBytes = sourceAll.NamedBytes.Bytes()
  8016  	}
  8017  }
  8018  
  8019  func BenchmarkBytesArray(b *testing.B) {
  8020  	for i := 0; i < b.N; i++ {
  8021  		sinkAll.RawBytes = sourceAll.BytesArray.Bytes()
  8022  	}
  8023  }
  8024  
  8025  func BenchmarkSliceLen(b *testing.B) {
  8026  	for i := 0; i < b.N; i++ {
  8027  		sinkAll.RawInt = sourceAll.SliceAny.Len()
  8028  	}
  8029  }
  8030  
  8031  func BenchmarkMapLen(b *testing.B) {
  8032  	for i := 0; i < b.N; i++ {
  8033  		sinkAll.RawInt = sourceAll.MapStringAny.Len()
  8034  	}
  8035  }
  8036  
  8037  func BenchmarkStringLen(b *testing.B) {
  8038  	for i := 0; i < b.N; i++ {
  8039  		sinkAll.RawInt = sourceAll.String.Len()
  8040  	}
  8041  }
  8042  
  8043  func BenchmarkArrayLen(b *testing.B) {
  8044  	for i := 0; i < b.N; i++ {
  8045  		sinkAll.RawInt = sourceAll.BytesArray.Len()
  8046  	}
  8047  }
  8048  
  8049  func BenchmarkSliceCap(b *testing.B) {
  8050  	for i := 0; i < b.N; i++ {
  8051  		sinkAll.RawInt = sourceAll.SliceAny.Cap()
  8052  	}
  8053  }
  8054  
  8055  func TestValue_Cap(t *testing.T) {
  8056  	a := &[3]int{1, 2, 3}
  8057  	v := ValueOf(a)
  8058  	if v.Cap() != cap(a) {
  8059  		t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
  8060  	}
  8061  
  8062  	a = nil
  8063  	v = ValueOf(a)
  8064  	if v.Cap() != cap(a) {
  8065  		t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
  8066  	}
  8067  
  8068  	getError := func(f func()) (errorStr string) {
  8069  		defer func() {
  8070  			e := recover()
  8071  			if str, ok := e.(string); ok {
  8072  				errorStr = str
  8073  			}
  8074  		}()
  8075  		f()
  8076  		return
  8077  	}
  8078  	e := getError(func() {
  8079  		var ptr *int
  8080  		ValueOf(ptr).Cap()
  8081  	})
  8082  	wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
  8083  	if e != wantStr {
  8084  		t.Errorf("error is %q, want %q", e, wantStr)
  8085  	}
  8086  }
  8087  
  8088  func TestValue_Len(t *testing.T) {
  8089  	a := &[3]int{1, 2, 3}
  8090  	v := ValueOf(a)
  8091  	if v.Len() != len(a) {
  8092  		t.Errorf("Len = %d want %d", v.Len(), len(a))
  8093  	}
  8094  
  8095  	a = nil
  8096  	v = ValueOf(a)
  8097  	if v.Len() != len(a) {
  8098  		t.Errorf("Len = %d want %d", v.Len(), len(a))
  8099  	}
  8100  
  8101  	getError := func(f func()) (errorStr string) {
  8102  		defer func() {
  8103  			e := recover()
  8104  			if str, ok := e.(string); ok {
  8105  				errorStr = str
  8106  			}
  8107  		}()
  8108  		f()
  8109  		return
  8110  	}
  8111  	e := getError(func() {
  8112  		var ptr *int
  8113  		ValueOf(ptr).Len()
  8114  	})
  8115  	wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
  8116  	if e != wantStr {
  8117  		t.Errorf("error is %q, want %q", e, wantStr)
  8118  	}
  8119  }
  8120  

View as plain text