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

View as plain text