github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/reflect/all_test.go (about)

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