github.com/filosottile/go@v0.0.0-20170906193555-dbed9972d994/src/reflect/all_test.go (about)

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