...
Run Format

Source file src/reflect/all_test.go

Documentation: reflect

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

View as plain text