github.com/razvanm/vanadium-go-1.3@v0.0.0-20160721203343-4a65068e5915/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/rand"
    14  	"os"
    15  	. "reflect"
    16  	"runtime"
    17  	"sort"
    18  	"strings"
    19  	"sync"
    20  	"testing"
    21  	"time"
    22  	"unsafe"
    23  )
    24  
    25  func TestBool(t *testing.T) {
    26  	v := ValueOf(true)
    27  	if v.Bool() != true {
    28  		t.Fatal("ValueOf(true).Bool() = false")
    29  	}
    30  }
    31  
    32  type integer int
    33  type T struct {
    34  	a int
    35  	b float64
    36  	c string
    37  	d *int
    38  }
    39  
    40  type pair struct {
    41  	i interface{}
    42  	s string
    43  }
    44  
    45  func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
    46  
    47  func assert(t *testing.T, s, want string) {
    48  	if s != want {
    49  		t.Errorf("have %#q want %#q", s, want)
    50  	}
    51  }
    52  
    53  func typestring(i interface{}) string { return TypeOf(i).String() }
    54  
    55  var typeTests = []pair{
    56  	{struct{ x int }{}, "int"},
    57  	{struct{ x int8 }{}, "int8"},
    58  	{struct{ x int16 }{}, "int16"},
    59  	{struct{ x int32 }{}, "int32"},
    60  	{struct{ x int64 }{}, "int64"},
    61  	{struct{ x uint }{}, "uint"},
    62  	{struct{ x uint8 }{}, "uint8"},
    63  	{struct{ x uint16 }{}, "uint16"},
    64  	{struct{ x uint32 }{}, "uint32"},
    65  	{struct{ x uint64 }{}, "uint64"},
    66  	{struct{ x float32 }{}, "float32"},
    67  	{struct{ x float64 }{}, "float64"},
    68  	{struct{ x int8 }{}, "int8"},
    69  	{struct{ x (**int8) }{}, "**int8"},
    70  	{struct{ x (**integer) }{}, "**reflect_test.integer"},
    71  	{struct{ x ([32]int32) }{}, "[32]int32"},
    72  	{struct{ x ([]int8) }{}, "[]int8"},
    73  	{struct{ x (map[string]int32) }{}, "map[string]int32"},
    74  	{struct{ x (chan<- string) }{}, "chan<- string"},
    75  	{struct {
    76  		x struct {
    77  			c chan *int32
    78  			d float32
    79  		}
    80  	}{},
    81  		"struct { c chan *int32; d float32 }",
    82  	},
    83  	{struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
    84  	{struct {
    85  		x struct {
    86  			c func(chan *integer, *int8)
    87  		}
    88  	}{},
    89  		"struct { c func(chan *reflect_test.integer, *int8) }",
    90  	},
    91  	{struct {
    92  		x struct {
    93  			a int8
    94  			b int32
    95  		}
    96  	}{},
    97  		"struct { a int8; b int32 }",
    98  	},
    99  	{struct {
   100  		x struct {
   101  			a int8
   102  			b int8
   103  			c int32
   104  		}
   105  	}{},
   106  		"struct { a int8; b int8; c int32 }",
   107  	},
   108  	{struct {
   109  		x struct {
   110  			a int8
   111  			b int8
   112  			c int8
   113  			d int32
   114  		}
   115  	}{},
   116  		"struct { a int8; b int8; c int8; d int32 }",
   117  	},
   118  	{struct {
   119  		x struct {
   120  			a int8
   121  			b int8
   122  			c int8
   123  			d int8
   124  			e int32
   125  		}
   126  	}{},
   127  		"struct { a int8; b int8; c int8; d int8; e int32 }",
   128  	},
   129  	{struct {
   130  		x struct {
   131  			a int8
   132  			b int8
   133  			c int8
   134  			d int8
   135  			e int8
   136  			f int32
   137  		}
   138  	}{},
   139  		"struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
   140  	},
   141  	{struct {
   142  		x struct {
   143  			a int8 `reflect:"hi there"`
   144  		}
   145  	}{},
   146  		`struct { a int8 "reflect:\"hi there\"" }`,
   147  	},
   148  	{struct {
   149  		x struct {
   150  			a int8 `reflect:"hi \x00there\t\n\"\\"`
   151  		}
   152  	}{},
   153  		`struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
   154  	},
   155  	{struct {
   156  		x struct {
   157  			f func(args ...int)
   158  		}
   159  	}{},
   160  		"struct { f func(...int) }",
   161  	},
   162  	{struct {
   163  		x (interface {
   164  			a(func(func(int) int) func(func(int)) int)
   165  			b()
   166  		})
   167  	}{},
   168  		"interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
   169  	},
   170  }
   171  
   172  var valueTests = []pair{
   173  	{new(int), "132"},
   174  	{new(int8), "8"},
   175  	{new(int16), "16"},
   176  	{new(int32), "32"},
   177  	{new(int64), "64"},
   178  	{new(uint), "132"},
   179  	{new(uint8), "8"},
   180  	{new(uint16), "16"},
   181  	{new(uint32), "32"},
   182  	{new(uint64), "64"},
   183  	{new(float32), "256.25"},
   184  	{new(float64), "512.125"},
   185  	{new(complex64), "532.125+10i"},
   186  	{new(complex128), "564.25+1i"},
   187  	{new(string), "stringy cheese"},
   188  	{new(bool), "true"},
   189  	{new(*int8), "*int8(0)"},
   190  	{new(**int8), "**int8(0)"},
   191  	{new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
   192  	{new(**integer), "**reflect_test.integer(0)"},
   193  	{new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
   194  	{new(chan<- string), "chan<- string"},
   195  	{new(func(a int8, b int32)), "func(int8, int32)(0)"},
   196  	{new(struct {
   197  		c chan *int32
   198  		d float32
   199  	}),
   200  		"struct { c chan *int32; d float32 }{chan *int32, 0}",
   201  	},
   202  	{new(struct{ c func(chan *integer, *int8) }),
   203  		"struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
   204  	},
   205  	{new(struct {
   206  		a int8
   207  		b int32
   208  	}),
   209  		"struct { a int8; b int32 }{0, 0}",
   210  	},
   211  	{new(struct {
   212  		a int8
   213  		b int8
   214  		c int32
   215  	}),
   216  		"struct { a int8; b int8; c int32 }{0, 0, 0}",
   217  	},
   218  }
   219  
   220  func testType(t *testing.T, i int, typ Type, want string) {
   221  	s := typ.String()
   222  	if s != want {
   223  		t.Errorf("#%d: have %#q, want %#q", i, s, want)
   224  	}
   225  }
   226  
   227  func TestTypes(t *testing.T) {
   228  	for i, tt := range typeTests {
   229  		testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
   230  	}
   231  }
   232  
   233  func TestSet(t *testing.T) {
   234  	for i, tt := range valueTests {
   235  		v := ValueOf(tt.i)
   236  		v = v.Elem()
   237  		switch v.Kind() {
   238  		case Int:
   239  			v.SetInt(132)
   240  		case Int8:
   241  			v.SetInt(8)
   242  		case Int16:
   243  			v.SetInt(16)
   244  		case Int32:
   245  			v.SetInt(32)
   246  		case Int64:
   247  			v.SetInt(64)
   248  		case Uint:
   249  			v.SetUint(132)
   250  		case Uint8:
   251  			v.SetUint(8)
   252  		case Uint16:
   253  			v.SetUint(16)
   254  		case Uint32:
   255  			v.SetUint(32)
   256  		case Uint64:
   257  			v.SetUint(64)
   258  		case Float32:
   259  			v.SetFloat(256.25)
   260  		case Float64:
   261  			v.SetFloat(512.125)
   262  		case Complex64:
   263  			v.SetComplex(532.125 + 10i)
   264  		case Complex128:
   265  			v.SetComplex(564.25 + 1i)
   266  		case String:
   267  			v.SetString("stringy cheese")
   268  		case Bool:
   269  			v.SetBool(true)
   270  		}
   271  		s := valueToString(v)
   272  		if s != tt.s {
   273  			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
   274  		}
   275  	}
   276  }
   277  
   278  func TestSetValue(t *testing.T) {
   279  	for i, tt := range valueTests {
   280  		v := ValueOf(tt.i).Elem()
   281  		switch v.Kind() {
   282  		case Int:
   283  			v.Set(ValueOf(int(132)))
   284  		case Int8:
   285  			v.Set(ValueOf(int8(8)))
   286  		case Int16:
   287  			v.Set(ValueOf(int16(16)))
   288  		case Int32:
   289  			v.Set(ValueOf(int32(32)))
   290  		case Int64:
   291  			v.Set(ValueOf(int64(64)))
   292  		case Uint:
   293  			v.Set(ValueOf(uint(132)))
   294  		case Uint8:
   295  			v.Set(ValueOf(uint8(8)))
   296  		case Uint16:
   297  			v.Set(ValueOf(uint16(16)))
   298  		case Uint32:
   299  			v.Set(ValueOf(uint32(32)))
   300  		case Uint64:
   301  			v.Set(ValueOf(uint64(64)))
   302  		case Float32:
   303  			v.Set(ValueOf(float32(256.25)))
   304  		case Float64:
   305  			v.Set(ValueOf(512.125))
   306  		case Complex64:
   307  			v.Set(ValueOf(complex64(532.125 + 10i)))
   308  		case Complex128:
   309  			v.Set(ValueOf(complex128(564.25 + 1i)))
   310  		case String:
   311  			v.Set(ValueOf("stringy cheese"))
   312  		case Bool:
   313  			v.Set(ValueOf(true))
   314  		}
   315  		s := valueToString(v)
   316  		if s != tt.s {
   317  			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
   318  		}
   319  	}
   320  }
   321  
   322  var _i = 7
   323  
   324  var valueToStringTests = []pair{
   325  	{123, "123"},
   326  	{123.5, "123.5"},
   327  	{byte(123), "123"},
   328  	{"abc", "abc"},
   329  	{T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
   330  	{new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
   331  	{[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
   332  	{&[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})"},
   333  	{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
   334  	{&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
   335  }
   336  
   337  func TestValueToString(t *testing.T) {
   338  	for i, test := range valueToStringTests {
   339  		s := valueToString(ValueOf(test.i))
   340  		if s != test.s {
   341  			t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
   342  		}
   343  	}
   344  }
   345  
   346  func TestArrayElemSet(t *testing.T) {
   347  	v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
   348  	v.Index(4).SetInt(123)
   349  	s := valueToString(v)
   350  	const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
   351  	if s != want {
   352  		t.Errorf("[10]int: have %#q want %#q", s, want)
   353  	}
   354  
   355  	v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
   356  	v.Index(4).SetInt(123)
   357  	s = valueToString(v)
   358  	const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
   359  	if s != want1 {
   360  		t.Errorf("[]int: have %#q want %#q", s, want1)
   361  	}
   362  }
   363  
   364  func TestPtrPointTo(t *testing.T) {
   365  	var ip *int32
   366  	var i int32 = 1234
   367  	vip := ValueOf(&ip)
   368  	vi := ValueOf(&i).Elem()
   369  	vip.Elem().Set(vi.Addr())
   370  	if *ip != 1234 {
   371  		t.Errorf("got %d, want 1234", *ip)
   372  	}
   373  
   374  	ip = nil
   375  	vp := ValueOf(&ip).Elem()
   376  	vp.Set(Zero(vp.Type()))
   377  	if ip != nil {
   378  		t.Errorf("got non-nil (%p), want nil", ip)
   379  	}
   380  }
   381  
   382  func TestPtrSetNil(t *testing.T) {
   383  	var i int32 = 1234
   384  	ip := &i
   385  	vip := ValueOf(&ip)
   386  	vip.Elem().Set(Zero(vip.Elem().Type()))
   387  	if ip != nil {
   388  		t.Errorf("got non-nil (%d), want nil", *ip)
   389  	}
   390  }
   391  
   392  func TestMapSetNil(t *testing.T) {
   393  	m := make(map[string]int)
   394  	vm := ValueOf(&m)
   395  	vm.Elem().Set(Zero(vm.Elem().Type()))
   396  	if m != nil {
   397  		t.Errorf("got non-nil (%p), want nil", m)
   398  	}
   399  }
   400  
   401  func TestAll(t *testing.T) {
   402  	testType(t, 1, TypeOf((int8)(0)), "int8")
   403  	testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
   404  
   405  	typ := TypeOf((*struct {
   406  		c chan *int32
   407  		d float32
   408  	})(nil))
   409  	testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
   410  	etyp := typ.Elem()
   411  	testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
   412  	styp := etyp
   413  	f := styp.Field(0)
   414  	testType(t, 5, f.Type, "chan *int32")
   415  
   416  	f, present := styp.FieldByName("d")
   417  	if !present {
   418  		t.Errorf("FieldByName says present field is absent")
   419  	}
   420  	testType(t, 6, f.Type, "float32")
   421  
   422  	f, present = styp.FieldByName("absent")
   423  	if present {
   424  		t.Errorf("FieldByName says absent field is present")
   425  	}
   426  
   427  	typ = TypeOf([32]int32{})
   428  	testType(t, 7, typ, "[32]int32")
   429  	testType(t, 8, typ.Elem(), "int32")
   430  
   431  	typ = TypeOf((map[string]*int32)(nil))
   432  	testType(t, 9, typ, "map[string]*int32")
   433  	mtyp := typ
   434  	testType(t, 10, mtyp.Key(), "string")
   435  	testType(t, 11, mtyp.Elem(), "*int32")
   436  
   437  	typ = TypeOf((chan<- string)(nil))
   438  	testType(t, 12, typ, "chan<- string")
   439  	testType(t, 13, typ.Elem(), "string")
   440  
   441  	// make sure tag strings are not part of element type
   442  	typ = TypeOf(struct {
   443  		d []uint32 `reflect:"TAG"`
   444  	}{}).Field(0).Type
   445  	testType(t, 14, typ, "[]uint32")
   446  }
   447  
   448  func TestInterfaceGet(t *testing.T) {
   449  	var inter struct {
   450  		E interface{}
   451  	}
   452  	inter.E = 123.456
   453  	v1 := ValueOf(&inter)
   454  	v2 := v1.Elem().Field(0)
   455  	assert(t, v2.Type().String(), "interface {}")
   456  	i2 := v2.Interface()
   457  	v3 := ValueOf(i2)
   458  	assert(t, v3.Type().String(), "float64")
   459  }
   460  
   461  func TestInterfaceValue(t *testing.T) {
   462  	var inter struct {
   463  		E interface{}
   464  	}
   465  	inter.E = 123.456
   466  	v1 := ValueOf(&inter)
   467  	v2 := v1.Elem().Field(0)
   468  	assert(t, v2.Type().String(), "interface {}")
   469  	v3 := v2.Elem()
   470  	assert(t, v3.Type().String(), "float64")
   471  
   472  	i3 := v2.Interface()
   473  	if _, ok := i3.(float64); !ok {
   474  		t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
   475  	}
   476  }
   477  
   478  func TestFunctionValue(t *testing.T) {
   479  	var x interface{} = func() {}
   480  	v := ValueOf(x)
   481  	if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
   482  		t.Fatalf("TestFunction returned wrong pointer")
   483  	}
   484  	assert(t, v.Type().String(), "func()")
   485  }
   486  
   487  var appendTests = []struct {
   488  	orig, extra []int
   489  }{
   490  	{make([]int, 2, 4), []int{22}},
   491  	{make([]int, 2, 4), []int{22, 33, 44}},
   492  }
   493  
   494  func sameInts(x, y []int) bool {
   495  	if len(x) != len(y) {
   496  		return false
   497  	}
   498  	for i, xx := range x {
   499  		if xx != y[i] {
   500  			return false
   501  		}
   502  	}
   503  	return true
   504  }
   505  
   506  func TestAppend(t *testing.T) {
   507  	for i, test := range appendTests {
   508  		origLen, extraLen := len(test.orig), len(test.extra)
   509  		want := append(test.orig, test.extra...)
   510  		// Convert extra from []int to []Value.
   511  		e0 := make([]Value, len(test.extra))
   512  		for j, e := range test.extra {
   513  			e0[j] = ValueOf(e)
   514  		}
   515  		// Convert extra from []int to *SliceValue.
   516  		e1 := ValueOf(test.extra)
   517  		// Test Append.
   518  		a0 := ValueOf(test.orig)
   519  		have0 := Append(a0, e0...).Interface().([]int)
   520  		if !sameInts(have0, want) {
   521  			t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
   522  		}
   523  		// Check that the orig and extra slices were not modified.
   524  		if len(test.orig) != origLen {
   525  			t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
   526  		}
   527  		if len(test.extra) != extraLen {
   528  			t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
   529  		}
   530  		// Test AppendSlice.
   531  		a1 := ValueOf(test.orig)
   532  		have1 := AppendSlice(a1, e1).Interface().([]int)
   533  		if !sameInts(have1, want) {
   534  			t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
   535  		}
   536  		// Check that the orig and extra slices were not modified.
   537  		if len(test.orig) != origLen {
   538  			t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
   539  		}
   540  		if len(test.extra) != extraLen {
   541  			t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
   542  		}
   543  	}
   544  }
   545  
   546  func TestCopy(t *testing.T) {
   547  	a := []int{1, 2, 3, 4, 10, 9, 8, 7}
   548  	b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   549  	c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   550  	for i := 0; i < len(b); i++ {
   551  		if b[i] != c[i] {
   552  			t.Fatalf("b != c before test")
   553  		}
   554  	}
   555  	a1 := a
   556  	b1 := b
   557  	aa := ValueOf(&a1).Elem()
   558  	ab := ValueOf(&b1).Elem()
   559  	for tocopy := 1; tocopy <= 7; tocopy++ {
   560  		aa.SetLen(tocopy)
   561  		Copy(ab, aa)
   562  		aa.SetLen(8)
   563  		for i := 0; i < tocopy; i++ {
   564  			if a[i] != b[i] {
   565  				t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
   566  					tocopy, i, a[i], i, b[i])
   567  			}
   568  		}
   569  		for i := tocopy; i < len(b); i++ {
   570  			if b[i] != c[i] {
   571  				if i < len(a) {
   572  					t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
   573  						tocopy, i, a[i], i, b[i], i, c[i])
   574  				} else {
   575  					t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
   576  						tocopy, i, b[i], i, c[i])
   577  				}
   578  			} else {
   579  				t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
   580  			}
   581  		}
   582  	}
   583  }
   584  
   585  func TestCopyArray(t *testing.T) {
   586  	a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
   587  	b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   588  	c := b
   589  	aa := ValueOf(&a).Elem()
   590  	ab := ValueOf(&b).Elem()
   591  	Copy(ab, aa)
   592  	for i := 0; i < len(a); i++ {
   593  		if a[i] != b[i] {
   594  			t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
   595  		}
   596  	}
   597  	for i := len(a); i < len(b); i++ {
   598  		if b[i] != c[i] {
   599  			t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
   600  		} else {
   601  			t.Logf("elem %d is okay\n", i)
   602  		}
   603  	}
   604  }
   605  
   606  func TestBigUnnamedStruct(t *testing.T) {
   607  	b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
   608  	v := ValueOf(b)
   609  	b1 := v.Interface().(struct {
   610  		a, b, c, d int64
   611  	})
   612  	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
   613  		t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
   614  	}
   615  }
   616  
   617  type big struct {
   618  	a, b, c, d, e int64
   619  }
   620  
   621  func TestBigStruct(t *testing.T) {
   622  	b := big{1, 2, 3, 4, 5}
   623  	v := ValueOf(b)
   624  	b1 := v.Interface().(big)
   625  	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
   626  		t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
   627  	}
   628  }
   629  
   630  type Basic struct {
   631  	x int
   632  	y float32
   633  }
   634  
   635  type NotBasic Basic
   636  
   637  type DeepEqualTest struct {
   638  	a, b interface{}
   639  	eq   bool
   640  }
   641  
   642  // Simple functions for DeepEqual tests.
   643  var (
   644  	fn1 func()             // nil.
   645  	fn2 func()             // nil.
   646  	fn3 = func() { fn1() } // Not nil.
   647  )
   648  
   649  var deepEqualTests = []DeepEqualTest{
   650  	// Equalities
   651  	{nil, nil, true},
   652  	{1, 1, true},
   653  	{int32(1), int32(1), true},
   654  	{0.5, 0.5, true},
   655  	{float32(0.5), float32(0.5), true},
   656  	{"hello", "hello", true},
   657  	{make([]int, 10), make([]int, 10), true},
   658  	{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
   659  	{Basic{1, 0.5}, Basic{1, 0.5}, true},
   660  	{error(nil), error(nil), true},
   661  	{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
   662  	{fn1, fn2, true},
   663  
   664  	// Inequalities
   665  	{1, 2, false},
   666  	{int32(1), int32(2), false},
   667  	{0.5, 0.6, false},
   668  	{float32(0.5), float32(0.6), false},
   669  	{"hello", "hey", false},
   670  	{make([]int, 10), make([]int, 11), false},
   671  	{&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
   672  	{Basic{1, 0.5}, Basic{1, 0.6}, false},
   673  	{Basic{1, 0}, Basic{2, 0}, false},
   674  	{map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
   675  	{map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
   676  	{map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
   677  	{map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
   678  	{nil, 1, false},
   679  	{1, nil, false},
   680  	{fn1, fn3, false},
   681  	{fn3, fn3, false},
   682  	{[][]int{{1}}, [][]int{{2}}, false},
   683  
   684  	// Nil vs empty: not the same.
   685  	{[]int{}, []int(nil), false},
   686  	{[]int{}, []int{}, true},
   687  	{[]int(nil), []int(nil), true},
   688  	{map[int]int{}, map[int]int(nil), false},
   689  	{map[int]int{}, map[int]int{}, true},
   690  	{map[int]int(nil), map[int]int(nil), true},
   691  
   692  	// Mismatched types
   693  	{1, 1.0, false},
   694  	{int32(1), int64(1), false},
   695  	{0.5, "hello", false},
   696  	{[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
   697  	{&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
   698  	{Basic{1, 0.5}, NotBasic{1, 0.5}, false},
   699  	{map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
   700  }
   701  
   702  func TestDeepEqual(t *testing.T) {
   703  	for _, test := range deepEqualTests {
   704  		if r := DeepEqual(test.a, test.b); r != test.eq {
   705  			t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
   706  		}
   707  	}
   708  }
   709  
   710  func TestTypeOf(t *testing.T) {
   711  	// Special case for nil
   712  	if typ := TypeOf(nil); typ != nil {
   713  		t.Errorf("expected nil type for nil value; got %v", typ)
   714  	}
   715  	for _, test := range deepEqualTests {
   716  		v := ValueOf(test.a)
   717  		if !v.IsValid() {
   718  			continue
   719  		}
   720  		typ := TypeOf(test.a)
   721  		if typ != v.Type() {
   722  			t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
   723  		}
   724  	}
   725  }
   726  
   727  type Recursive struct {
   728  	x int
   729  	r *Recursive
   730  }
   731  
   732  func TestDeepEqualRecursiveStruct(t *testing.T) {
   733  	a, b := new(Recursive), new(Recursive)
   734  	*a = Recursive{12, a}
   735  	*b = Recursive{12, b}
   736  	if !DeepEqual(a, b) {
   737  		t.Error("DeepEqual(recursive same) = false, want true")
   738  	}
   739  }
   740  
   741  type _Complex struct {
   742  	a int
   743  	b [3]*_Complex
   744  	c *string
   745  	d map[float64]float64
   746  }
   747  
   748  func TestDeepEqualComplexStruct(t *testing.T) {
   749  	m := make(map[float64]float64)
   750  	stra, strb := "hello", "hello"
   751  	a, b := new(_Complex), new(_Complex)
   752  	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
   753  	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
   754  	if !DeepEqual(a, b) {
   755  		t.Error("DeepEqual(complex same) = false, want true")
   756  	}
   757  }
   758  
   759  func TestDeepEqualComplexStructInequality(t *testing.T) {
   760  	m := make(map[float64]float64)
   761  	stra, strb := "hello", "helloo" // Difference is here
   762  	a, b := new(_Complex), new(_Complex)
   763  	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
   764  	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
   765  	if DeepEqual(a, b) {
   766  		t.Error("DeepEqual(complex different) = true, want false")
   767  	}
   768  }
   769  
   770  type UnexpT struct {
   771  	m map[int]int
   772  }
   773  
   774  func TestDeepEqualUnexportedMap(t *testing.T) {
   775  	// Check that DeepEqual can look at unexported fields.
   776  	x1 := UnexpT{map[int]int{1: 2}}
   777  	x2 := UnexpT{map[int]int{1: 2}}
   778  	if !DeepEqual(&x1, &x2) {
   779  		t.Error("DeepEqual(x1, x2) = false, want true")
   780  	}
   781  
   782  	y1 := UnexpT{map[int]int{2: 3}}
   783  	if DeepEqual(&x1, &y1) {
   784  		t.Error("DeepEqual(x1, y1) = true, want false")
   785  	}
   786  }
   787  
   788  func check2ndField(x interface{}, offs uintptr, t *testing.T) {
   789  	s := ValueOf(x)
   790  	f := s.Type().Field(1)
   791  	if f.Offset != offs {
   792  		t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
   793  	}
   794  }
   795  
   796  // Check that structure alignment & offsets viewed through reflect agree with those
   797  // from the compiler itself.
   798  func TestAlignment(t *testing.T) {
   799  	type T1inner struct {
   800  		a int
   801  	}
   802  	type T1 struct {
   803  		T1inner
   804  		f int
   805  	}
   806  	type T2inner struct {
   807  		a, b int
   808  	}
   809  	type T2 struct {
   810  		T2inner
   811  		f int
   812  	}
   813  
   814  	x := T1{T1inner{2}, 17}
   815  	check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
   816  
   817  	x1 := T2{T2inner{2, 3}, 17}
   818  	check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
   819  }
   820  
   821  func Nil(a interface{}, t *testing.T) {
   822  	n := ValueOf(a).Field(0)
   823  	if !n.IsNil() {
   824  		t.Errorf("%v should be nil", a)
   825  	}
   826  }
   827  
   828  func NotNil(a interface{}, t *testing.T) {
   829  	n := ValueOf(a).Field(0)
   830  	if n.IsNil() {
   831  		t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
   832  	}
   833  }
   834  
   835  func TestIsNil(t *testing.T) {
   836  	// These implement IsNil.
   837  	// Wrap in extra struct to hide interface type.
   838  	doNil := []interface{}{
   839  		struct{ x *int }{},
   840  		struct{ x interface{} }{},
   841  		struct{ x map[string]int }{},
   842  		struct{ x func() bool }{},
   843  		struct{ x chan int }{},
   844  		struct{ x []string }{},
   845  	}
   846  	for _, ts := range doNil {
   847  		ty := TypeOf(ts).Field(0).Type
   848  		v := Zero(ty)
   849  		v.IsNil() // panics if not okay to call
   850  	}
   851  
   852  	// Check the implementations
   853  	var pi struct {
   854  		x *int
   855  	}
   856  	Nil(pi, t)
   857  	pi.x = new(int)
   858  	NotNil(pi, t)
   859  
   860  	var si struct {
   861  		x []int
   862  	}
   863  	Nil(si, t)
   864  	si.x = make([]int, 10)
   865  	NotNil(si, t)
   866  
   867  	var ci struct {
   868  		x chan int
   869  	}
   870  	Nil(ci, t)
   871  	ci.x = make(chan int)
   872  	NotNil(ci, t)
   873  
   874  	var mi struct {
   875  		x map[int]int
   876  	}
   877  	Nil(mi, t)
   878  	mi.x = make(map[int]int)
   879  	NotNil(mi, t)
   880  
   881  	var ii struct {
   882  		x interface{}
   883  	}
   884  	Nil(ii, t)
   885  	ii.x = 2
   886  	NotNil(ii, t)
   887  
   888  	var fi struct {
   889  		x func(t *testing.T)
   890  	}
   891  	Nil(fi, t)
   892  	fi.x = TestIsNil
   893  	NotNil(fi, t)
   894  }
   895  
   896  func TestInterfaceExtraction(t *testing.T) {
   897  	var s struct {
   898  		W io.Writer
   899  	}
   900  
   901  	s.W = os.Stdout
   902  	v := Indirect(ValueOf(&s)).Field(0).Interface()
   903  	if v != s.W.(interface{}) {
   904  		t.Error("Interface() on interface: ", v, s.W)
   905  	}
   906  }
   907  
   908  func TestNilPtrValueSub(t *testing.T) {
   909  	var pi *int
   910  	if pv := ValueOf(pi); pv.Elem().IsValid() {
   911  		t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
   912  	}
   913  }
   914  
   915  func TestMap(t *testing.T) {
   916  	m := map[string]int{"a": 1, "b": 2}
   917  	mv := ValueOf(m)
   918  	if n := mv.Len(); n != len(m) {
   919  		t.Errorf("Len = %d, want %d", n, len(m))
   920  	}
   921  	keys := mv.MapKeys()
   922  	newmap := MakeMap(mv.Type())
   923  	for k, v := range m {
   924  		// Check that returned Keys match keys in range.
   925  		// These aren't required to be in the same order.
   926  		seen := false
   927  		for _, kv := range keys {
   928  			if kv.String() == k {
   929  				seen = true
   930  				break
   931  			}
   932  		}
   933  		if !seen {
   934  			t.Errorf("Missing key %q", k)
   935  		}
   936  
   937  		// Check that value lookup is correct.
   938  		vv := mv.MapIndex(ValueOf(k))
   939  		if vi := vv.Int(); vi != int64(v) {
   940  			t.Errorf("Key %q: have value %d, want %d", k, vi, v)
   941  		}
   942  
   943  		// Copy into new map.
   944  		newmap.SetMapIndex(ValueOf(k), ValueOf(v))
   945  	}
   946  	vv := mv.MapIndex(ValueOf("not-present"))
   947  	if vv.IsValid() {
   948  		t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
   949  	}
   950  
   951  	newm := newmap.Interface().(map[string]int)
   952  	if len(newm) != len(m) {
   953  		t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
   954  	}
   955  
   956  	for k, v := range newm {
   957  		mv, ok := m[k]
   958  		if mv != v {
   959  			t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
   960  		}
   961  	}
   962  
   963  	newmap.SetMapIndex(ValueOf("a"), Value{})
   964  	v, ok := newm["a"]
   965  	if ok {
   966  		t.Errorf("newm[\"a\"] = %d after delete", v)
   967  	}
   968  
   969  	mv = ValueOf(&m).Elem()
   970  	mv.Set(Zero(mv.Type()))
   971  	if m != nil {
   972  		t.Errorf("mv.Set(nil) failed")
   973  	}
   974  }
   975  
   976  func TestNilMap(t *testing.T) {
   977  	var m map[string]int
   978  	mv := ValueOf(m)
   979  	keys := mv.MapKeys()
   980  	if len(keys) != 0 {
   981  		t.Errorf(">0 keys for nil map: %v", keys)
   982  	}
   983  
   984  	// Check that value for missing key is zero.
   985  	x := mv.MapIndex(ValueOf("hello"))
   986  	if x.Kind() != Invalid {
   987  		t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
   988  	}
   989  
   990  	// Check big value too.
   991  	var mbig map[string][10 << 20]byte
   992  	x = ValueOf(mbig).MapIndex(ValueOf("hello"))
   993  	if x.Kind() != Invalid {
   994  		t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
   995  	}
   996  
   997  	// Test that deletes from a nil map succeed.
   998  	mv.SetMapIndex(ValueOf("hi"), Value{})
   999  }
  1000  
  1001  func TestChan(t *testing.T) {
  1002  	for loop := 0; loop < 2; loop++ {
  1003  		var c chan int
  1004  		var cv Value
  1005  
  1006  		// check both ways to allocate channels
  1007  		switch loop {
  1008  		case 1:
  1009  			c = make(chan int, 1)
  1010  			cv = ValueOf(c)
  1011  		case 0:
  1012  			cv = MakeChan(TypeOf(c), 1)
  1013  			c = cv.Interface().(chan int)
  1014  		}
  1015  
  1016  		// Send
  1017  		cv.Send(ValueOf(2))
  1018  		if i := <-c; i != 2 {
  1019  			t.Errorf("reflect Send 2, native recv %d", i)
  1020  		}
  1021  
  1022  		// Recv
  1023  		c <- 3
  1024  		if i, ok := cv.Recv(); i.Int() != 3 || !ok {
  1025  			t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
  1026  		}
  1027  
  1028  		// TryRecv fail
  1029  		val, ok := cv.TryRecv()
  1030  		if val.IsValid() || ok {
  1031  			t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
  1032  		}
  1033  
  1034  		// TryRecv success
  1035  		c <- 4
  1036  		val, ok = cv.TryRecv()
  1037  		if !val.IsValid() {
  1038  			t.Errorf("TryRecv on ready chan got nil")
  1039  		} else if i := val.Int(); i != 4 || !ok {
  1040  			t.Errorf("native send 4, TryRecv %d, %t", i, ok)
  1041  		}
  1042  
  1043  		// TrySend fail
  1044  		c <- 100
  1045  		ok = cv.TrySend(ValueOf(5))
  1046  		i := <-c
  1047  		if ok {
  1048  			t.Errorf("TrySend on full chan succeeded: value %d", i)
  1049  		}
  1050  
  1051  		// TrySend success
  1052  		ok = cv.TrySend(ValueOf(6))
  1053  		if !ok {
  1054  			t.Errorf("TrySend on empty chan failed")
  1055  		} else {
  1056  			if i = <-c; i != 6 {
  1057  				t.Errorf("TrySend 6, recv %d", i)
  1058  			}
  1059  		}
  1060  
  1061  		// Close
  1062  		c <- 123
  1063  		cv.Close()
  1064  		if i, ok := cv.Recv(); i.Int() != 123 || !ok {
  1065  			t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
  1066  		}
  1067  		if i, ok := cv.Recv(); i.Int() != 0 || ok {
  1068  			t.Errorf("after close Recv %d, %t", i.Int(), ok)
  1069  		}
  1070  	}
  1071  
  1072  	// check creation of unbuffered channel
  1073  	var c chan int
  1074  	cv := MakeChan(TypeOf(c), 0)
  1075  	c = cv.Interface().(chan int)
  1076  	if cv.TrySend(ValueOf(7)) {
  1077  		t.Errorf("TrySend on sync chan succeeded")
  1078  	}
  1079  	if v, ok := cv.TryRecv(); v.IsValid() || ok {
  1080  		t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
  1081  	}
  1082  
  1083  	// len/cap
  1084  	cv = MakeChan(TypeOf(c), 10)
  1085  	c = cv.Interface().(chan int)
  1086  	for i := 0; i < 3; i++ {
  1087  		c <- i
  1088  	}
  1089  	if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
  1090  		t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
  1091  	}
  1092  }
  1093  
  1094  // caseInfo describes a single case in a select test.
  1095  type caseInfo struct {
  1096  	desc      string
  1097  	canSelect bool
  1098  	recv      Value
  1099  	closed    bool
  1100  	helper    func()
  1101  	panic     bool
  1102  }
  1103  
  1104  var allselect = flag.Bool("allselect", false, "exhaustive select test")
  1105  
  1106  func TestSelect(t *testing.T) {
  1107  	selectWatch.once.Do(func() { go selectWatcher() })
  1108  
  1109  	var x exhaustive
  1110  	nch := 0
  1111  	newop := func(n int, cap int) (ch, val Value) {
  1112  		nch++
  1113  		if nch%101%2 == 1 {
  1114  			c := make(chan int, cap)
  1115  			ch = ValueOf(c)
  1116  			val = ValueOf(n)
  1117  		} else {
  1118  			c := make(chan string, cap)
  1119  			ch = ValueOf(c)
  1120  			val = ValueOf(fmt.Sprint(n))
  1121  		}
  1122  		return
  1123  	}
  1124  
  1125  	for n := 0; x.Next(); n++ {
  1126  		if testing.Short() && n >= 1000 {
  1127  			break
  1128  		}
  1129  		if n >= 100000 && !*allselect {
  1130  			break
  1131  		}
  1132  		if n%100000 == 0 && testing.Verbose() {
  1133  			println("TestSelect", n)
  1134  		}
  1135  		var cases []SelectCase
  1136  		var info []caseInfo
  1137  
  1138  		// Ready send.
  1139  		if x.Maybe() {
  1140  			ch, val := newop(len(cases), 1)
  1141  			cases = append(cases, SelectCase{
  1142  				Dir:  SelectSend,
  1143  				Chan: ch,
  1144  				Send: val,
  1145  			})
  1146  			info = append(info, caseInfo{desc: "ready send", canSelect: true})
  1147  		}
  1148  
  1149  		// Ready recv.
  1150  		if x.Maybe() {
  1151  			ch, val := newop(len(cases), 1)
  1152  			ch.Send(val)
  1153  			cases = append(cases, SelectCase{
  1154  				Dir:  SelectRecv,
  1155  				Chan: ch,
  1156  			})
  1157  			info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
  1158  		}
  1159  
  1160  		// Blocking send.
  1161  		if x.Maybe() {
  1162  			ch, val := newop(len(cases), 0)
  1163  			cases = append(cases, SelectCase{
  1164  				Dir:  SelectSend,
  1165  				Chan: ch,
  1166  				Send: val,
  1167  			})
  1168  			// Let it execute?
  1169  			if x.Maybe() {
  1170  				f := func() { ch.Recv() }
  1171  				info = append(info, caseInfo{desc: "blocking send", helper: f})
  1172  			} else {
  1173  				info = append(info, caseInfo{desc: "blocking send"})
  1174  			}
  1175  		}
  1176  
  1177  		// Blocking recv.
  1178  		if x.Maybe() {
  1179  			ch, val := newop(len(cases), 0)
  1180  			cases = append(cases, SelectCase{
  1181  				Dir:  SelectRecv,
  1182  				Chan: ch,
  1183  			})
  1184  			// Let it execute?
  1185  			if x.Maybe() {
  1186  				f := func() { ch.Send(val) }
  1187  				info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
  1188  			} else {
  1189  				info = append(info, caseInfo{desc: "blocking recv"})
  1190  			}
  1191  		}
  1192  
  1193  		// Zero Chan send.
  1194  		if x.Maybe() {
  1195  			// Maybe include value to send.
  1196  			var val Value
  1197  			if x.Maybe() {
  1198  				val = ValueOf(100)
  1199  			}
  1200  			cases = append(cases, SelectCase{
  1201  				Dir:  SelectSend,
  1202  				Send: val,
  1203  			})
  1204  			info = append(info, caseInfo{desc: "zero Chan send"})
  1205  		}
  1206  
  1207  		// Zero Chan receive.
  1208  		if x.Maybe() {
  1209  			cases = append(cases, SelectCase{
  1210  				Dir: SelectRecv,
  1211  			})
  1212  			info = append(info, caseInfo{desc: "zero Chan recv"})
  1213  		}
  1214  
  1215  		// nil Chan send.
  1216  		if x.Maybe() {
  1217  			cases = append(cases, SelectCase{
  1218  				Dir:  SelectSend,
  1219  				Chan: ValueOf((chan int)(nil)),
  1220  				Send: ValueOf(101),
  1221  			})
  1222  			info = append(info, caseInfo{desc: "nil Chan send"})
  1223  		}
  1224  
  1225  		// nil Chan recv.
  1226  		if x.Maybe() {
  1227  			cases = append(cases, SelectCase{
  1228  				Dir:  SelectRecv,
  1229  				Chan: ValueOf((chan int)(nil)),
  1230  			})
  1231  			info = append(info, caseInfo{desc: "nil Chan recv"})
  1232  		}
  1233  
  1234  		// closed Chan send.
  1235  		if x.Maybe() {
  1236  			ch := make(chan int)
  1237  			close(ch)
  1238  			cases = append(cases, SelectCase{
  1239  				Dir:  SelectSend,
  1240  				Chan: ValueOf(ch),
  1241  				Send: ValueOf(101),
  1242  			})
  1243  			info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
  1244  		}
  1245  
  1246  		// closed Chan recv.
  1247  		if x.Maybe() {
  1248  			ch, val := newop(len(cases), 0)
  1249  			ch.Close()
  1250  			val = Zero(val.Type())
  1251  			cases = append(cases, SelectCase{
  1252  				Dir:  SelectRecv,
  1253  				Chan: ch,
  1254  			})
  1255  			info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
  1256  		}
  1257  
  1258  		var helper func() // goroutine to help the select complete
  1259  
  1260  		// Add default? Must be last case here, but will permute.
  1261  		// Add the default if the select would otherwise
  1262  		// block forever, and maybe add it anyway.
  1263  		numCanSelect := 0
  1264  		canProceed := false
  1265  		canBlock := true
  1266  		canPanic := false
  1267  		helpers := []int{}
  1268  		for i, c := range info {
  1269  			if c.canSelect {
  1270  				canProceed = true
  1271  				canBlock = false
  1272  				numCanSelect++
  1273  				if c.panic {
  1274  					canPanic = true
  1275  				}
  1276  			} else if c.helper != nil {
  1277  				canProceed = true
  1278  				helpers = append(helpers, i)
  1279  			}
  1280  		}
  1281  		if !canProceed || x.Maybe() {
  1282  			cases = append(cases, SelectCase{
  1283  				Dir: SelectDefault,
  1284  			})
  1285  			info = append(info, caseInfo{desc: "default", canSelect: canBlock})
  1286  			numCanSelect++
  1287  		} else if canBlock {
  1288  			// Select needs to communicate with another goroutine.
  1289  			cas := &info[helpers[x.Choose(len(helpers))]]
  1290  			helper = cas.helper
  1291  			cas.canSelect = true
  1292  			numCanSelect++
  1293  		}
  1294  
  1295  		// Permute cases and case info.
  1296  		// Doing too much here makes the exhaustive loop
  1297  		// too exhausting, so just do two swaps.
  1298  		for loop := 0; loop < 2; loop++ {
  1299  			i := x.Choose(len(cases))
  1300  			j := x.Choose(len(cases))
  1301  			cases[i], cases[j] = cases[j], cases[i]
  1302  			info[i], info[j] = info[j], info[i]
  1303  		}
  1304  
  1305  		if helper != nil {
  1306  			// We wait before kicking off a goroutine to satisfy a blocked select.
  1307  			// The pause needs to be big enough to let the select block before
  1308  			// we run the helper, but if we lose that race once in a while it's okay: the
  1309  			// select will just proceed immediately. Not a big deal.
  1310  			// For short tests we can grow [sic] the timeout a bit without fear of taking too long
  1311  			pause := 10 * time.Microsecond
  1312  			if testing.Short() {
  1313  				pause = 100 * time.Microsecond
  1314  			}
  1315  			time.AfterFunc(pause, helper)
  1316  		}
  1317  
  1318  		// Run select.
  1319  		i, recv, recvOK, panicErr := runSelect(cases, info)
  1320  		if panicErr != nil && !canPanic {
  1321  			t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
  1322  		}
  1323  		if panicErr == nil && canPanic && numCanSelect == 1 {
  1324  			t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
  1325  		}
  1326  		if panicErr != nil {
  1327  			continue
  1328  		}
  1329  
  1330  		cas := info[i]
  1331  		if !cas.canSelect {
  1332  			recvStr := ""
  1333  			if recv.IsValid() {
  1334  				recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
  1335  			}
  1336  			t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
  1337  			continue
  1338  		}
  1339  		if cas.panic {
  1340  			t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
  1341  			continue
  1342  		}
  1343  
  1344  		if cases[i].Dir == SelectRecv {
  1345  			if !recv.IsValid() {
  1346  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
  1347  			}
  1348  			if !cas.recv.IsValid() {
  1349  				t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
  1350  			}
  1351  			if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
  1352  				if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
  1353  					t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
  1354  				}
  1355  				t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
  1356  			}
  1357  		} else {
  1358  			if recv.IsValid() || recvOK {
  1359  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
  1360  			}
  1361  		}
  1362  	}
  1363  }
  1364  
  1365  // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
  1366  // If the selectWatcher notices that the select has been blocked for >1 second, it prints
  1367  // an error describing the select and panics the entire test binary.
  1368  var selectWatch struct {
  1369  	sync.Mutex
  1370  	once sync.Once
  1371  	now  time.Time
  1372  	info []caseInfo
  1373  }
  1374  
  1375  func selectWatcher() {
  1376  	for {
  1377  		time.Sleep(1 * time.Second)
  1378  		selectWatch.Lock()
  1379  		if selectWatch.info != nil && time.Since(selectWatch.now) > 1*time.Second {
  1380  			fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
  1381  			panic("select stuck")
  1382  		}
  1383  		selectWatch.Unlock()
  1384  	}
  1385  }
  1386  
  1387  // runSelect runs a single select test.
  1388  // It returns the values returned by Select but also returns
  1389  // a panic value if the Select panics.
  1390  func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
  1391  	defer func() {
  1392  		panicErr = recover()
  1393  
  1394  		selectWatch.Lock()
  1395  		selectWatch.info = nil
  1396  		selectWatch.Unlock()
  1397  	}()
  1398  
  1399  	selectWatch.Lock()
  1400  	selectWatch.now = time.Now()
  1401  	selectWatch.info = info
  1402  	selectWatch.Unlock()
  1403  
  1404  	chosen, recv, recvOK = Select(cases)
  1405  	return
  1406  }
  1407  
  1408  // fmtSelect formats the information about a single select test.
  1409  func fmtSelect(info []caseInfo) string {
  1410  	var buf bytes.Buffer
  1411  	fmt.Fprintf(&buf, "\nselect {\n")
  1412  	for i, cas := range info {
  1413  		fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
  1414  		if cas.recv.IsValid() {
  1415  			fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
  1416  		}
  1417  		if cas.canSelect {
  1418  			fmt.Fprintf(&buf, " canselect")
  1419  		}
  1420  		if cas.panic {
  1421  			fmt.Fprintf(&buf, " panic")
  1422  		}
  1423  		fmt.Fprintf(&buf, "\n")
  1424  	}
  1425  	fmt.Fprintf(&buf, "}")
  1426  	return buf.String()
  1427  }
  1428  
  1429  type two [2]uintptr
  1430  
  1431  // Difficult test for function call because of
  1432  // implicit padding between arguments.
  1433  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) {
  1434  	return b, c, d, e, f, g, h
  1435  }
  1436  
  1437  func TestFunc(t *testing.T) {
  1438  	ret := ValueOf(dummy).Call([]Value{
  1439  		ValueOf(byte(10)),
  1440  		ValueOf(20),
  1441  		ValueOf(byte(30)),
  1442  		ValueOf(two{40, 50}),
  1443  		ValueOf(byte(60)),
  1444  		ValueOf(float32(70)),
  1445  		ValueOf(byte(80)),
  1446  	})
  1447  	if len(ret) != 7 {
  1448  		t.Fatalf("Call returned %d values, want 7", len(ret))
  1449  	}
  1450  
  1451  	i := byte(ret[0].Uint())
  1452  	j := int(ret[1].Int())
  1453  	k := byte(ret[2].Uint())
  1454  	l := ret[3].Interface().(two)
  1455  	m := byte(ret[4].Uint())
  1456  	n := float32(ret[5].Float())
  1457  	o := byte(ret[6].Uint())
  1458  
  1459  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1460  		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)
  1461  	}
  1462  }
  1463  
  1464  type emptyStruct struct{}
  1465  
  1466  type nonEmptyStruct struct {
  1467  	member int
  1468  }
  1469  
  1470  func returnEmpty() emptyStruct {
  1471  	return emptyStruct{}
  1472  }
  1473  
  1474  func takesEmpty(e emptyStruct) {
  1475  }
  1476  
  1477  func returnNonEmpty(i int) nonEmptyStruct {
  1478  	return nonEmptyStruct{member: i}
  1479  }
  1480  
  1481  func takesNonEmpty(n nonEmptyStruct) int {
  1482  	return n.member
  1483  }
  1484  
  1485  func TestCallWithStruct(t *testing.T) {
  1486  	r := ValueOf(returnEmpty).Call(nil)
  1487  	if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
  1488  		t.Errorf("returning empty struct returned %#v instead", r)
  1489  	}
  1490  	r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
  1491  	if len(r) != 0 {
  1492  		t.Errorf("takesEmpty returned values: %#v", r)
  1493  	}
  1494  	r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
  1495  	if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
  1496  		t.Errorf("returnNonEmpty returned %#v", r)
  1497  	}
  1498  	r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
  1499  	if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
  1500  		t.Errorf("takesNonEmpty returned %#v", r)
  1501  	}
  1502  }
  1503  
  1504  func TestMakeFunc(t *testing.T) {
  1505  	f := dummy
  1506  	fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
  1507  	ValueOf(&f).Elem().Set(fv)
  1508  
  1509  	// Call g with small arguments so that there is
  1510  	// something predictable (and different from the
  1511  	// correct results) in those positions on the stack.
  1512  	g := dummy
  1513  	g(1, 2, 3, two{4, 5}, 6, 7, 8)
  1514  
  1515  	// Call constructed function f.
  1516  	i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
  1517  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1518  		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)
  1519  	}
  1520  }
  1521  
  1522  func TestMakeFuncInterface(t *testing.T) {
  1523  	fn := func(i int) int { return i }
  1524  	incr := func(in []Value) []Value {
  1525  		return []Value{ValueOf(int(in[0].Int() + 1))}
  1526  	}
  1527  	fv := MakeFunc(TypeOf(fn), incr)
  1528  	ValueOf(&fn).Elem().Set(fv)
  1529  	if r := fn(2); r != 3 {
  1530  		t.Errorf("Call returned %d, want 3", r)
  1531  	}
  1532  	if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
  1533  		t.Errorf("Call returned %d, want 15", r)
  1534  	}
  1535  	if r := fv.Interface().(func(int) int)(26); r != 27 {
  1536  		t.Errorf("Call returned %d, want 27", r)
  1537  	}
  1538  }
  1539  
  1540  func TestMakeFuncVariadic(t *testing.T) {
  1541  	// Test that variadic arguments are packed into a slice and passed as last arg
  1542  	fn := func(_ int, is ...int) []int { return nil }
  1543  	fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
  1544  	ValueOf(&fn).Elem().Set(fv)
  1545  
  1546  	r := fn(1, 2, 3)
  1547  	if r[0] != 2 || r[1] != 3 {
  1548  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1549  	}
  1550  
  1551  	r = fn(1, []int{2, 3}...)
  1552  	if r[0] != 2 || r[1] != 3 {
  1553  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1554  	}
  1555  
  1556  	r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
  1557  	if r[0] != 2 || r[1] != 3 {
  1558  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1559  	}
  1560  
  1561  	r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
  1562  	if r[0] != 2 || r[1] != 3 {
  1563  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1564  	}
  1565  
  1566  	f := fv.Interface().(func(int, ...int) []int)
  1567  
  1568  	r = f(1, 2, 3)
  1569  	if r[0] != 2 || r[1] != 3 {
  1570  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1571  	}
  1572  	r = f(1, []int{2, 3}...)
  1573  	if r[0] != 2 || r[1] != 3 {
  1574  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1575  	}
  1576  }
  1577  
  1578  type Point struct {
  1579  	x, y int
  1580  }
  1581  
  1582  // This will be index 0.
  1583  func (p Point) AnotherMethod(scale int) int {
  1584  	return -1
  1585  }
  1586  
  1587  // This will be index 1.
  1588  func (p Point) Dist(scale int) int {
  1589  	//println("Point.Dist", p.x, p.y, scale)
  1590  	return p.x*p.x*scale + p.y*p.y*scale
  1591  }
  1592  
  1593  // This will be index 2.
  1594  func (p Point) GCMethod(k int) int {
  1595  	runtime.GC()
  1596  	return k + p.x
  1597  }
  1598  
  1599  // This will be index 3.
  1600  func (p Point) TotalDist(points ...Point) int {
  1601  	tot := 0
  1602  	for _, q := range points {
  1603  		dx := q.x - p.x
  1604  		dy := q.y - p.y
  1605  		tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
  1606  
  1607  	}
  1608  	return tot
  1609  }
  1610  
  1611  func TestMethod(t *testing.T) {
  1612  	// Non-curried method of type.
  1613  	p := Point{3, 4}
  1614  	i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
  1615  	if i != 250 {
  1616  		t.Errorf("Type Method returned %d; want 250", i)
  1617  	}
  1618  
  1619  	m, ok := TypeOf(p).MethodByName("Dist")
  1620  	if !ok {
  1621  		t.Fatalf("method by name failed")
  1622  	}
  1623  	i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
  1624  	if i != 275 {
  1625  		t.Errorf("Type MethodByName returned %d; want 275", i)
  1626  	}
  1627  
  1628  	i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
  1629  	if i != 300 {
  1630  		t.Errorf("Pointer Type Method returned %d; want 300", i)
  1631  	}
  1632  
  1633  	m, ok = TypeOf(&p).MethodByName("Dist")
  1634  	if !ok {
  1635  		t.Fatalf("ptr method by name failed")
  1636  	}
  1637  	i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
  1638  	if i != 325 {
  1639  		t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
  1640  	}
  1641  
  1642  	// Curried method of value.
  1643  	tfunc := TypeOf((func(int) int)(nil))
  1644  	v := ValueOf(p).Method(1)
  1645  	if tt := v.Type(); tt != tfunc {
  1646  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1647  	}
  1648  	i = v.Call([]Value{ValueOf(14)})[0].Int()
  1649  	if i != 350 {
  1650  		t.Errorf("Value Method returned %d; want 350", i)
  1651  	}
  1652  	v = ValueOf(p).MethodByName("Dist")
  1653  	if tt := v.Type(); tt != tfunc {
  1654  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  1655  	}
  1656  	i = v.Call([]Value{ValueOf(15)})[0].Int()
  1657  	if i != 375 {
  1658  		t.Errorf("Value MethodByName returned %d; want 375", i)
  1659  	}
  1660  
  1661  	// Curried method of pointer.
  1662  	v = ValueOf(&p).Method(1)
  1663  	if tt := v.Type(); tt != tfunc {
  1664  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  1665  	}
  1666  	i = v.Call([]Value{ValueOf(16)})[0].Int()
  1667  	if i != 400 {
  1668  		t.Errorf("Pointer Value Method returned %d; want 400", i)
  1669  	}
  1670  	v = ValueOf(&p).MethodByName("Dist")
  1671  	if tt := v.Type(); tt != tfunc {
  1672  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1673  	}
  1674  	i = v.Call([]Value{ValueOf(17)})[0].Int()
  1675  	if i != 425 {
  1676  		t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
  1677  	}
  1678  
  1679  	// Curried method of interface value.
  1680  	// Have to wrap interface value in a struct to get at it.
  1681  	// Passing it to ValueOf directly would
  1682  	// access the underlying Point, not the interface.
  1683  	var x interface {
  1684  		Dist(int) int
  1685  	} = p
  1686  	pv := ValueOf(&x).Elem()
  1687  	v = pv.Method(0)
  1688  	if tt := v.Type(); tt != tfunc {
  1689  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  1690  	}
  1691  	i = v.Call([]Value{ValueOf(18)})[0].Int()
  1692  	if i != 450 {
  1693  		t.Errorf("Interface Method returned %d; want 450", i)
  1694  	}
  1695  	v = pv.MethodByName("Dist")
  1696  	if tt := v.Type(); tt != tfunc {
  1697  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  1698  	}
  1699  	i = v.Call([]Value{ValueOf(19)})[0].Int()
  1700  	if i != 475 {
  1701  		t.Errorf("Interface MethodByName returned %d; want 475", i)
  1702  	}
  1703  }
  1704  
  1705  func TestMethodValue(t *testing.T) {
  1706  	p := Point{3, 4}
  1707  	var i int64
  1708  
  1709  	// Curried method of value.
  1710  	tfunc := TypeOf((func(int) int)(nil))
  1711  	v := ValueOf(p).Method(1)
  1712  	if tt := v.Type(); tt != tfunc {
  1713  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1714  	}
  1715  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
  1716  	if i != 250 {
  1717  		t.Errorf("Value Method returned %d; want 250", i)
  1718  	}
  1719  	v = ValueOf(p).MethodByName("Dist")
  1720  	if tt := v.Type(); tt != tfunc {
  1721  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  1722  	}
  1723  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
  1724  	if i != 275 {
  1725  		t.Errorf("Value MethodByName returned %d; want 275", i)
  1726  	}
  1727  
  1728  	// Curried method of pointer.
  1729  	v = ValueOf(&p).Method(1)
  1730  	if tt := v.Type(); tt != tfunc {
  1731  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  1732  	}
  1733  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
  1734  	if i != 300 {
  1735  		t.Errorf("Pointer Value Method returned %d; want 300", i)
  1736  	}
  1737  	v = ValueOf(&p).MethodByName("Dist")
  1738  	if tt := v.Type(); tt != tfunc {
  1739  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1740  	}
  1741  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
  1742  	if i != 325 {
  1743  		t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
  1744  	}
  1745  
  1746  	// Curried method of pointer to pointer.
  1747  	pp := &p
  1748  	v = ValueOf(&pp).Elem().Method(1)
  1749  	if tt := v.Type(); tt != tfunc {
  1750  		t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
  1751  	}
  1752  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
  1753  	if i != 350 {
  1754  		t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
  1755  	}
  1756  	v = ValueOf(&pp).Elem().MethodByName("Dist")
  1757  	if tt := v.Type(); tt != tfunc {
  1758  		t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1759  	}
  1760  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
  1761  	if i != 375 {
  1762  		t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
  1763  	}
  1764  
  1765  	// Curried method of interface value.
  1766  	// Have to wrap interface value in a struct to get at it.
  1767  	// Passing it to ValueOf directly would
  1768  	// access the underlying Point, not the interface.
  1769  	var s = struct {
  1770  		X interface {
  1771  			Dist(int) int
  1772  		}
  1773  	}{p}
  1774  	pv := ValueOf(s).Field(0)
  1775  	v = pv.Method(0)
  1776  	if tt := v.Type(); tt != tfunc {
  1777  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  1778  	}
  1779  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
  1780  	if i != 400 {
  1781  		t.Errorf("Interface Method returned %d; want 400", i)
  1782  	}
  1783  	v = pv.MethodByName("Dist")
  1784  	if tt := v.Type(); tt != tfunc {
  1785  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  1786  	}
  1787  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
  1788  	if i != 425 {
  1789  		t.Errorf("Interface MethodByName returned %d; want 425", i)
  1790  	}
  1791  }
  1792  
  1793  func TestVariadicMethodValue(t *testing.T) {
  1794  	p := Point{3, 4}
  1795  	points := []Point{{20, 21}, {22, 23}, {24, 25}}
  1796  	want := int64(p.TotalDist(points[0], points[1], points[2]))
  1797  
  1798  	// Curried method of value.
  1799  	tfunc := TypeOf((func(...Point) int)(nil))
  1800  	v := ValueOf(p).Method(3)
  1801  	if tt := v.Type(); tt != tfunc {
  1802  		t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
  1803  	}
  1804  	i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
  1805  	if i != want {
  1806  		t.Errorf("Variadic Method returned %d; want %d", i, want)
  1807  	}
  1808  	i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
  1809  	if i != want {
  1810  		t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
  1811  	}
  1812  
  1813  	f := v.Interface().(func(...Point) int)
  1814  	i = int64(f(points[0], points[1], points[2]))
  1815  	if i != want {
  1816  		t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
  1817  	}
  1818  	i = int64(f(points...))
  1819  	if i != want {
  1820  		t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
  1821  	}
  1822  }
  1823  
  1824  // Reflect version of $GOROOT/test/method5.go
  1825  
  1826  // Concrete types implementing M method.
  1827  // Smaller than a word, word-sized, larger than a word.
  1828  // Value and pointer receivers.
  1829  
  1830  type Tinter interface {
  1831  	M(int, byte) (byte, int)
  1832  }
  1833  
  1834  type Tsmallv byte
  1835  
  1836  func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  1837  
  1838  type Tsmallp byte
  1839  
  1840  func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  1841  
  1842  type Twordv uintptr
  1843  
  1844  func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  1845  
  1846  type Twordp uintptr
  1847  
  1848  func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  1849  
  1850  type Tbigv [2]uintptr
  1851  
  1852  func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  1853  
  1854  type Tbigp [2]uintptr
  1855  
  1856  func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  1857  
  1858  // Again, with an unexported method.
  1859  
  1860  type tsmallv byte
  1861  
  1862  func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
  1863  
  1864  type tsmallp byte
  1865  
  1866  func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
  1867  
  1868  type twordv uintptr
  1869  
  1870  func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
  1871  
  1872  type twordp uintptr
  1873  
  1874  func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
  1875  
  1876  type tbigv [2]uintptr
  1877  
  1878  func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  1879  
  1880  type tbigp [2]uintptr
  1881  
  1882  func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  1883  
  1884  type tinter interface {
  1885  	m(int, byte) (byte, int)
  1886  }
  1887  
  1888  // Embedding via pointer.
  1889  
  1890  type Tm1 struct {
  1891  	Tm2
  1892  }
  1893  
  1894  type Tm2 struct {
  1895  	*Tm3
  1896  }
  1897  
  1898  type Tm3 struct {
  1899  	*Tm4
  1900  }
  1901  
  1902  type Tm4 struct {
  1903  }
  1904  
  1905  func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
  1906  
  1907  func TestMethod5(t *testing.T) {
  1908  	CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
  1909  		b, x := f(1000, 99)
  1910  		if b != 99 || x != 1000+inc {
  1911  			t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  1912  		}
  1913  	}
  1914  
  1915  	CheckV := func(name string, i Value, inc int) {
  1916  		bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
  1917  		b := bx[0].Interface()
  1918  		x := bx[1].Interface()
  1919  		if b != byte(99) || x != 1000+inc {
  1920  			t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  1921  		}
  1922  
  1923  		CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
  1924  	}
  1925  
  1926  	var TinterType = TypeOf(new(Tinter)).Elem()
  1927  	var tinterType = TypeOf(new(tinter)).Elem()
  1928  
  1929  	CheckI := func(name string, i interface{}, inc int) {
  1930  		v := ValueOf(i)
  1931  		CheckV(name, v, inc)
  1932  		CheckV("(i="+name+")", v.Convert(TinterType), inc)
  1933  	}
  1934  
  1935  	sv := Tsmallv(1)
  1936  	CheckI("sv", sv, 1)
  1937  	CheckI("&sv", &sv, 1)
  1938  
  1939  	sp := Tsmallp(2)
  1940  	CheckI("&sp", &sp, 2)
  1941  
  1942  	wv := Twordv(3)
  1943  	CheckI("wv", wv, 3)
  1944  	CheckI("&wv", &wv, 3)
  1945  
  1946  	wp := Twordp(4)
  1947  	CheckI("&wp", &wp, 4)
  1948  
  1949  	bv := Tbigv([2]uintptr{5, 6})
  1950  	CheckI("bv", bv, 11)
  1951  	CheckI("&bv", &bv, 11)
  1952  
  1953  	bp := Tbigp([2]uintptr{7, 8})
  1954  	CheckI("&bp", &bp, 15)
  1955  
  1956  	t4 := Tm4{}
  1957  	t3 := Tm3{&t4}
  1958  	t2 := Tm2{&t3}
  1959  	t1 := Tm1{t2}
  1960  	CheckI("t4", t4, 40)
  1961  	CheckI("&t4", &t4, 40)
  1962  	CheckI("t3", t3, 40)
  1963  	CheckI("&t3", &t3, 40)
  1964  	CheckI("t2", t2, 40)
  1965  	CheckI("&t2", &t2, 40)
  1966  	CheckI("t1", t1, 40)
  1967  	CheckI("&t1", &t1, 40)
  1968  
  1969  	methodShouldPanic := func(name string, i interface{}) {
  1970  		v := ValueOf(i)
  1971  		m := v.Method(0)
  1972  		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
  1973  		shouldPanic(func() { m.Interface() })
  1974  
  1975  		v = v.Convert(tinterType)
  1976  		m = v.Method(0)
  1977  		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
  1978  		shouldPanic(func() { m.Interface() })
  1979  	}
  1980  
  1981  	_sv := tsmallv(1)
  1982  	methodShouldPanic("_sv", _sv)
  1983  	methodShouldPanic("&_sv", &_sv)
  1984  
  1985  	_sp := tsmallp(2)
  1986  	methodShouldPanic("&_sp", &_sp)
  1987  
  1988  	_wv := twordv(3)
  1989  	methodShouldPanic("_wv", _wv)
  1990  	methodShouldPanic("&_wv", &_wv)
  1991  
  1992  	_wp := twordp(4)
  1993  	methodShouldPanic("&_wp", &_wp)
  1994  
  1995  	_bv := tbigv([2]uintptr{5, 6})
  1996  	methodShouldPanic("_bv", _bv)
  1997  	methodShouldPanic("&_bv", &_bv)
  1998  
  1999  	_bp := tbigp([2]uintptr{7, 8})
  2000  	methodShouldPanic("&_bp", &_bp)
  2001  
  2002  	var tnil Tinter
  2003  	vnil := ValueOf(&tnil).Elem()
  2004  	shouldPanic(func() { vnil.Method(0) })
  2005  }
  2006  
  2007  func TestInterfaceSet(t *testing.T) {
  2008  	p := &Point{3, 4}
  2009  
  2010  	var s struct {
  2011  		I interface{}
  2012  		P interface {
  2013  			Dist(int) int
  2014  		}
  2015  	}
  2016  	sv := ValueOf(&s).Elem()
  2017  	sv.Field(0).Set(ValueOf(p))
  2018  	if q := s.I.(*Point); q != p {
  2019  		t.Errorf("i: have %p want %p", q, p)
  2020  	}
  2021  
  2022  	pv := sv.Field(1)
  2023  	pv.Set(ValueOf(p))
  2024  	if q := s.P.(*Point); q != p {
  2025  		t.Errorf("i: have %p want %p", q, p)
  2026  	}
  2027  
  2028  	i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
  2029  	if i != 250 {
  2030  		t.Errorf("Interface Method returned %d; want 250", i)
  2031  	}
  2032  }
  2033  
  2034  type T1 struct {
  2035  	a string
  2036  	int
  2037  }
  2038  
  2039  func TestAnonymousFields(t *testing.T) {
  2040  	var field StructField
  2041  	var ok bool
  2042  	var t1 T1
  2043  	type1 := TypeOf(t1)
  2044  	if field, ok = type1.FieldByName("int"); !ok {
  2045  		t.Fatal("no field 'int'")
  2046  	}
  2047  	if field.Index[0] != 1 {
  2048  		t.Error("field index should be 1; is", field.Index)
  2049  	}
  2050  }
  2051  
  2052  type FTest struct {
  2053  	s     interface{}
  2054  	name  string
  2055  	index []int
  2056  	value int
  2057  }
  2058  
  2059  type D1 struct {
  2060  	d int
  2061  }
  2062  type D2 struct {
  2063  	d int
  2064  }
  2065  
  2066  type S0 struct {
  2067  	A, B, C int
  2068  	D1
  2069  	D2
  2070  }
  2071  
  2072  type S1 struct {
  2073  	B int
  2074  	S0
  2075  }
  2076  
  2077  type S2 struct {
  2078  	A int
  2079  	*S1
  2080  }
  2081  
  2082  type S1x struct {
  2083  	S1
  2084  }
  2085  
  2086  type S1y struct {
  2087  	S1
  2088  }
  2089  
  2090  type S3 struct {
  2091  	S1x
  2092  	S2
  2093  	D, E int
  2094  	*S1y
  2095  }
  2096  
  2097  type S4 struct {
  2098  	*S4
  2099  	A int
  2100  }
  2101  
  2102  // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
  2103  type S5 struct {
  2104  	S6
  2105  	S7
  2106  	S8
  2107  }
  2108  
  2109  type S6 struct {
  2110  	X int
  2111  }
  2112  
  2113  type S7 S6
  2114  
  2115  type S8 struct {
  2116  	S9
  2117  }
  2118  
  2119  type S9 struct {
  2120  	X int
  2121  	Y int
  2122  }
  2123  
  2124  // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
  2125  type S10 struct {
  2126  	S11
  2127  	S12
  2128  	S13
  2129  }
  2130  
  2131  type S11 struct {
  2132  	S6
  2133  }
  2134  
  2135  type S12 struct {
  2136  	S6
  2137  }
  2138  
  2139  type S13 struct {
  2140  	S8
  2141  }
  2142  
  2143  // The X in S15.S11.S1 and S16.S11.S1 annihilate.
  2144  type S14 struct {
  2145  	S15
  2146  	S16
  2147  }
  2148  
  2149  type S15 struct {
  2150  	S11
  2151  }
  2152  
  2153  type S16 struct {
  2154  	S11
  2155  }
  2156  
  2157  var fieldTests = []FTest{
  2158  	{struct{}{}, "", nil, 0},
  2159  	{struct{}{}, "Foo", nil, 0},
  2160  	{S0{A: 'a'}, "A", []int{0}, 'a'},
  2161  	{S0{}, "D", nil, 0},
  2162  	{S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
  2163  	{S1{B: 'b'}, "B", []int{0}, 'b'},
  2164  	{S1{}, "S0", []int{1}, 0},
  2165  	{S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
  2166  	{S2{A: 'a'}, "A", []int{0}, 'a'},
  2167  	{S2{}, "S1", []int{1}, 0},
  2168  	{S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
  2169  	{S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
  2170  	{S2{}, "D", nil, 0},
  2171  	{S3{}, "S1", nil, 0},
  2172  	{S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
  2173  	{S3{}, "B", nil, 0},
  2174  	{S3{D: 'd'}, "D", []int{2}, 0},
  2175  	{S3{E: 'e'}, "E", []int{3}, 'e'},
  2176  	{S4{A: 'a'}, "A", []int{1}, 'a'},
  2177  	{S4{}, "B", nil, 0},
  2178  	{S5{}, "X", nil, 0},
  2179  	{S5{}, "Y", []int{2, 0, 1}, 0},
  2180  	{S10{}, "X", nil, 0},
  2181  	{S10{}, "Y", []int{2, 0, 0, 1}, 0},
  2182  	{S14{}, "X", nil, 0},
  2183  }
  2184  
  2185  func TestFieldByIndex(t *testing.T) {
  2186  	for _, test := range fieldTests {
  2187  		s := TypeOf(test.s)
  2188  		f := s.FieldByIndex(test.index)
  2189  		if f.Name != "" {
  2190  			if test.index != nil {
  2191  				if f.Name != test.name {
  2192  					t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
  2193  				}
  2194  			} else {
  2195  				t.Errorf("%s.%s found", s.Name(), f.Name)
  2196  			}
  2197  		} else if len(test.index) > 0 {
  2198  			t.Errorf("%s.%s not found", s.Name(), test.name)
  2199  		}
  2200  
  2201  		if test.value != 0 {
  2202  			v := ValueOf(test.s).FieldByIndex(test.index)
  2203  			if v.IsValid() {
  2204  				if x, ok := v.Interface().(int); ok {
  2205  					if x != test.value {
  2206  						t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
  2207  					}
  2208  				} else {
  2209  					t.Errorf("%s%v value not an int", s.Name(), test.index)
  2210  				}
  2211  			} else {
  2212  				t.Errorf("%s%v value not found", s.Name(), test.index)
  2213  			}
  2214  		}
  2215  	}
  2216  }
  2217  
  2218  func TestFieldByName(t *testing.T) {
  2219  	for _, test := range fieldTests {
  2220  		s := TypeOf(test.s)
  2221  		f, found := s.FieldByName(test.name)
  2222  		if found {
  2223  			if test.index != nil {
  2224  				// Verify field depth and index.
  2225  				if len(f.Index) != len(test.index) {
  2226  					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)
  2227  				} else {
  2228  					for i, x := range f.Index {
  2229  						if x != test.index[i] {
  2230  							t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
  2231  						}
  2232  					}
  2233  				}
  2234  			} else {
  2235  				t.Errorf("%s.%s found", s.Name(), f.Name)
  2236  			}
  2237  		} else if len(test.index) > 0 {
  2238  			t.Errorf("%s.%s not found", s.Name(), test.name)
  2239  		}
  2240  
  2241  		if test.value != 0 {
  2242  			v := ValueOf(test.s).FieldByName(test.name)
  2243  			if v.IsValid() {
  2244  				if x, ok := v.Interface().(int); ok {
  2245  					if x != test.value {
  2246  						t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
  2247  					}
  2248  				} else {
  2249  					t.Errorf("%s.%s value not an int", s.Name(), test.name)
  2250  				}
  2251  			} else {
  2252  				t.Errorf("%s.%s value not found", s.Name(), test.name)
  2253  			}
  2254  		}
  2255  	}
  2256  }
  2257  
  2258  func TestImportPath(t *testing.T) {
  2259  	tests := []struct {
  2260  		t    Type
  2261  		path string
  2262  	}{
  2263  		{TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
  2264  		{TypeOf(int(0)), ""},
  2265  		{TypeOf(int8(0)), ""},
  2266  		{TypeOf(int16(0)), ""},
  2267  		{TypeOf(int32(0)), ""},
  2268  		{TypeOf(int64(0)), ""},
  2269  		{TypeOf(uint(0)), ""},
  2270  		{TypeOf(uint8(0)), ""},
  2271  		{TypeOf(uint16(0)), ""},
  2272  		{TypeOf(uint32(0)), ""},
  2273  		{TypeOf(uint64(0)), ""},
  2274  		{TypeOf(uintptr(0)), ""},
  2275  		{TypeOf(float32(0)), ""},
  2276  		{TypeOf(float64(0)), ""},
  2277  		{TypeOf(complex64(0)), ""},
  2278  		{TypeOf(complex128(0)), ""},
  2279  		{TypeOf(byte(0)), ""},
  2280  		{TypeOf(rune(0)), ""},
  2281  		{TypeOf([]byte(nil)), ""},
  2282  		{TypeOf([]rune(nil)), ""},
  2283  		{TypeOf(string("")), ""},
  2284  		{TypeOf((*interface{})(nil)).Elem(), ""},
  2285  		{TypeOf((*byte)(nil)), ""},
  2286  		{TypeOf((*rune)(nil)), ""},
  2287  		{TypeOf((*int64)(nil)), ""},
  2288  		{TypeOf(map[string]int{}), ""},
  2289  		{TypeOf((*error)(nil)).Elem(), ""},
  2290  	}
  2291  	for _, test := range tests {
  2292  		if path := test.t.PkgPath(); path != test.path {
  2293  			t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
  2294  		}
  2295  	}
  2296  }
  2297  
  2298  func TestVariadicType(t *testing.T) {
  2299  	// Test example from Type documentation.
  2300  	var f func(x int, y ...float64)
  2301  	typ := TypeOf(f)
  2302  	if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
  2303  		sl := typ.In(1)
  2304  		if sl.Kind() == Slice {
  2305  			if sl.Elem() == TypeOf(0.0) {
  2306  				// ok
  2307  				return
  2308  			}
  2309  		}
  2310  	}
  2311  
  2312  	// Failed
  2313  	t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
  2314  	s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
  2315  	for i := 0; i < typ.NumIn(); i++ {
  2316  		s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
  2317  	}
  2318  	t.Error(s)
  2319  }
  2320  
  2321  type inner struct {
  2322  	x int
  2323  }
  2324  
  2325  type outer struct {
  2326  	y int
  2327  	inner
  2328  }
  2329  
  2330  func (*inner) m() {}
  2331  func (*outer) m() {}
  2332  
  2333  func TestNestedMethods(t *testing.T) {
  2334  	typ := TypeOf((*outer)(nil))
  2335  	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
  2336  		t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
  2337  		for i := 0; i < typ.NumMethod(); i++ {
  2338  			m := typ.Method(i)
  2339  			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2340  		}
  2341  	}
  2342  }
  2343  
  2344  type InnerInt struct {
  2345  	X int
  2346  }
  2347  
  2348  type OuterInt struct {
  2349  	Y int
  2350  	InnerInt
  2351  }
  2352  
  2353  func (i *InnerInt) M() int {
  2354  	return i.X
  2355  }
  2356  
  2357  func TestEmbeddedMethods(t *testing.T) {
  2358  	typ := TypeOf((*OuterInt)(nil))
  2359  	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
  2360  		t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
  2361  		for i := 0; i < typ.NumMethod(); i++ {
  2362  			m := typ.Method(i)
  2363  			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2364  		}
  2365  	}
  2366  
  2367  	i := &InnerInt{3}
  2368  	if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
  2369  		t.Errorf("i.M() = %d, want 3", v)
  2370  	}
  2371  
  2372  	o := &OuterInt{1, InnerInt{2}}
  2373  	if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
  2374  		t.Errorf("i.M() = %d, want 2", v)
  2375  	}
  2376  
  2377  	f := (*OuterInt).M
  2378  	if v := f(o); v != 2 {
  2379  		t.Errorf("f(o) = %d, want 2", v)
  2380  	}
  2381  }
  2382  
  2383  func TestPtrTo(t *testing.T) {
  2384  	var i int
  2385  
  2386  	typ := TypeOf(i)
  2387  	for i = 0; i < 100; i++ {
  2388  		typ = PtrTo(typ)
  2389  	}
  2390  	for i = 0; i < 100; i++ {
  2391  		typ = typ.Elem()
  2392  	}
  2393  	if typ != TypeOf(i) {
  2394  		t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
  2395  	}
  2396  }
  2397  
  2398  func TestPtrToGC(t *testing.T) {
  2399  	type T *uintptr
  2400  	tt := TypeOf(T(nil))
  2401  	pt := PtrTo(tt)
  2402  	const n = 100
  2403  	var x []interface{}
  2404  	for i := 0; i < n; i++ {
  2405  		v := New(pt)
  2406  		p := new(*uintptr)
  2407  		*p = new(uintptr)
  2408  		**p = uintptr(i)
  2409  		v.Elem().Set(ValueOf(p).Convert(pt))
  2410  		x = append(x, v.Interface())
  2411  	}
  2412  	runtime.GC()
  2413  
  2414  	for i, xi := range x {
  2415  		k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
  2416  		if k != uintptr(i) {
  2417  			t.Errorf("lost x[%d] = %d, want %d", i, k, i)
  2418  		}
  2419  	}
  2420  }
  2421  
  2422  func TestAddr(t *testing.T) {
  2423  	var p struct {
  2424  		X, Y int
  2425  	}
  2426  
  2427  	v := ValueOf(&p)
  2428  	v = v.Elem()
  2429  	v = v.Addr()
  2430  	v = v.Elem()
  2431  	v = v.Field(0)
  2432  	v.SetInt(2)
  2433  	if p.X != 2 {
  2434  		t.Errorf("Addr.Elem.Set failed to set value")
  2435  	}
  2436  
  2437  	// Again but take address of the ValueOf value.
  2438  	// Exercises generation of PtrTypes not present in the binary.
  2439  	q := &p
  2440  	v = ValueOf(&q).Elem()
  2441  	v = v.Addr()
  2442  	v = v.Elem()
  2443  	v = v.Elem()
  2444  	v = v.Addr()
  2445  	v = v.Elem()
  2446  	v = v.Field(0)
  2447  	v.SetInt(3)
  2448  	if p.X != 3 {
  2449  		t.Errorf("Addr.Elem.Set failed to set value")
  2450  	}
  2451  
  2452  	// Starting without pointer we should get changed value
  2453  	// in interface.
  2454  	qq := p
  2455  	v = ValueOf(&qq).Elem()
  2456  	v0 := v
  2457  	v = v.Addr()
  2458  	v = v.Elem()
  2459  	v = v.Field(0)
  2460  	v.SetInt(4)
  2461  	if p.X != 3 { // should be unchanged from last time
  2462  		t.Errorf("somehow value Set changed original p")
  2463  	}
  2464  	p = v0.Interface().(struct {
  2465  		X, Y int
  2466  	})
  2467  	if p.X != 4 {
  2468  		t.Errorf("Addr.Elem.Set valued to set value in top value")
  2469  	}
  2470  
  2471  	// Verify that taking the address of a type gives us a pointer
  2472  	// which we can convert back using the usual interface
  2473  	// notation.
  2474  	var s struct {
  2475  		B *bool
  2476  	}
  2477  	ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
  2478  	*(ps.(**bool)) = new(bool)
  2479  	if s.B == nil {
  2480  		t.Errorf("Addr.Interface direct assignment failed")
  2481  	}
  2482  }
  2483  
  2484  func noAlloc(t *testing.T, n int, f func(int)) {
  2485  	if testing.Short() {
  2486  		t.Skip("skipping malloc count in short mode")
  2487  	}
  2488  	if runtime.GOMAXPROCS(0) > 1 {
  2489  		t.Skip("skipping; GOMAXPROCS>1")
  2490  	}
  2491  	i := -1
  2492  	allocs := testing.AllocsPerRun(n, func() {
  2493  		f(i)
  2494  		i++
  2495  	})
  2496  	if allocs > 0 {
  2497  		t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
  2498  	}
  2499  }
  2500  
  2501  func TestAllocations(t *testing.T) {
  2502  	noAlloc(t, 100, func(j int) {
  2503  		var i interface{}
  2504  		var v Value
  2505  
  2506  		// We can uncomment this when compiler escape analysis
  2507  		// is good enough to see that the integer assigned to i
  2508  		// does not escape and therefore need not be allocated.
  2509  		//
  2510  		// i = 42 + j
  2511  		// v = ValueOf(i)
  2512  		// if int(v.Int()) != 42+j {
  2513  		// 	panic("wrong int")
  2514  		// }
  2515  
  2516  		i = func(j int) int { return j }
  2517  		v = ValueOf(i)
  2518  		if v.Interface().(func(int) int)(j) != j {
  2519  			panic("wrong result")
  2520  		}
  2521  	})
  2522  }
  2523  
  2524  func TestSmallNegativeInt(t *testing.T) {
  2525  	i := int16(-1)
  2526  	v := ValueOf(i)
  2527  	if v.Int() != -1 {
  2528  		t.Errorf("int16(-1).Int() returned %v", v.Int())
  2529  	}
  2530  }
  2531  
  2532  func TestIndex(t *testing.T) {
  2533  	xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
  2534  	v := ValueOf(xs).Index(3).Interface().(byte)
  2535  	if v != xs[3] {
  2536  		t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
  2537  	}
  2538  	xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
  2539  	v = ValueOf(xa).Index(2).Interface().(byte)
  2540  	if v != xa[2] {
  2541  		t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
  2542  	}
  2543  	s := "0123456789"
  2544  	v = ValueOf(s).Index(3).Interface().(byte)
  2545  	if v != s[3] {
  2546  		t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
  2547  	}
  2548  }
  2549  
  2550  func TestSlice(t *testing.T) {
  2551  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2552  	v := ValueOf(xs).Slice(3, 5).Interface().([]int)
  2553  	if len(v) != 2 {
  2554  		t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
  2555  	}
  2556  	if cap(v) != 5 {
  2557  		t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
  2558  	}
  2559  	if !DeepEqual(v[0:5], xs[3:]) {
  2560  		t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
  2561  	}
  2562  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2563  	v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
  2564  	if len(v) != 3 {
  2565  		t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
  2566  	}
  2567  	if cap(v) != 6 {
  2568  		t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
  2569  	}
  2570  	if !DeepEqual(v[0:6], xa[2:]) {
  2571  		t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
  2572  	}
  2573  	s := "0123456789"
  2574  	vs := ValueOf(s).Slice(3, 5).Interface().(string)
  2575  	if vs != s[3:5] {
  2576  		t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
  2577  	}
  2578  
  2579  	rv := ValueOf(&xs).Elem()
  2580  	rv = rv.Slice(3, 4)
  2581  	ptr2 := rv.Pointer()
  2582  	rv = rv.Slice(5, 5)
  2583  	ptr3 := rv.Pointer()
  2584  	if ptr3 != ptr2 {
  2585  		t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
  2586  	}
  2587  }
  2588  
  2589  func TestSlice3(t *testing.T) {
  2590  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2591  	v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
  2592  	if len(v) != 2 {
  2593  		t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
  2594  	}
  2595  	if cap(v) != 4 {
  2596  		t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
  2597  	}
  2598  	if !DeepEqual(v[0:4], xs[3:7:7]) {
  2599  		t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
  2600  	}
  2601  	rv := ValueOf(&xs).Elem()
  2602  	shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2603  	shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2604  	shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2605  
  2606  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2607  	v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
  2608  	if len(v) != 3 {
  2609  		t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
  2610  	}
  2611  	if cap(v) != 4 {
  2612  		t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
  2613  	}
  2614  	if !DeepEqual(v[0:4], xa[2:6:6]) {
  2615  		t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
  2616  	}
  2617  	rv = ValueOf(&xa).Elem()
  2618  	shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2619  	shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2620  	shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2621  
  2622  	s := "hello world"
  2623  	rv = ValueOf(&s).Elem()
  2624  	shouldPanic(func() { rv.Slice3(1, 2, 3) })
  2625  
  2626  	rv = ValueOf(&xs).Elem()
  2627  	rv = rv.Slice3(3, 5, 7)
  2628  	ptr2 := rv.Pointer()
  2629  	rv = rv.Slice3(4, 4, 4)
  2630  	ptr3 := rv.Pointer()
  2631  	if ptr3 != ptr2 {
  2632  		t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
  2633  	}
  2634  }
  2635  
  2636  func TestSetLenCap(t *testing.T) {
  2637  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2638  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2639  
  2640  	vs := ValueOf(&xs).Elem()
  2641  	shouldPanic(func() { vs.SetLen(10) })
  2642  	shouldPanic(func() { vs.SetCap(10) })
  2643  	shouldPanic(func() { vs.SetLen(-1) })
  2644  	shouldPanic(func() { vs.SetCap(-1) })
  2645  	shouldPanic(func() { vs.SetCap(6) }) // smaller than len
  2646  	vs.SetLen(5)
  2647  	if len(xs) != 5 || cap(xs) != 8 {
  2648  		t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
  2649  	}
  2650  	vs.SetCap(6)
  2651  	if len(xs) != 5 || cap(xs) != 6 {
  2652  		t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
  2653  	}
  2654  	vs.SetCap(5)
  2655  	if len(xs) != 5 || cap(xs) != 5 {
  2656  		t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
  2657  	}
  2658  	shouldPanic(func() { vs.SetCap(4) }) // smaller than len
  2659  	shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
  2660  
  2661  	va := ValueOf(&xa).Elem()
  2662  	shouldPanic(func() { va.SetLen(8) })
  2663  	shouldPanic(func() { va.SetCap(8) })
  2664  }
  2665  
  2666  func TestVariadic(t *testing.T) {
  2667  	var b bytes.Buffer
  2668  	V := ValueOf
  2669  
  2670  	b.Reset()
  2671  	V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
  2672  	if b.String() != "hello, 42 world" {
  2673  		t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
  2674  	}
  2675  
  2676  	b.Reset()
  2677  	V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
  2678  	if b.String() != "hello, 42 world" {
  2679  		t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
  2680  	}
  2681  }
  2682  
  2683  func TestFuncArg(t *testing.T) {
  2684  	f1 := func(i int, f func(int) int) int { return f(i) }
  2685  	f2 := func(i int) int { return i + 1 }
  2686  	r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
  2687  	if r[0].Int() != 101 {
  2688  		t.Errorf("function returned %d, want 101", r[0].Int())
  2689  	}
  2690  }
  2691  
  2692  func TestStructArg(t *testing.T) {
  2693  	type padded struct {
  2694  		B string
  2695  		C int32
  2696  	}
  2697  	var (
  2698  		gotA  padded
  2699  		gotB  uint32
  2700  		wantA = padded{"3", 4}
  2701  		wantB = uint32(5)
  2702  	)
  2703  	f := func(a padded, b uint32) {
  2704  		gotA, gotB = a, b
  2705  	}
  2706  	ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
  2707  	if gotA != wantA || gotB != wantB {
  2708  		t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
  2709  	}
  2710  }
  2711  
  2712  var tagGetTests = []struct {
  2713  	Tag   StructTag
  2714  	Key   string
  2715  	Value string
  2716  }{
  2717  	{`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
  2718  	{`protobuf:"PB(1,2)"`, `foo`, ``},
  2719  	{`protobuf:"PB(1,2)"`, `rotobuf`, ``},
  2720  	{`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
  2721  	{`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
  2722  }
  2723  
  2724  func TestTagGet(t *testing.T) {
  2725  	for _, tt := range tagGetTests {
  2726  		if v := tt.Tag.Get(tt.Key); v != tt.Value {
  2727  			t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
  2728  		}
  2729  	}
  2730  }
  2731  
  2732  func TestBytes(t *testing.T) {
  2733  	type B []byte
  2734  	x := B{1, 2, 3, 4}
  2735  	y := ValueOf(x).Bytes()
  2736  	if !bytes.Equal(x, y) {
  2737  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  2738  	}
  2739  	if &x[0] != &y[0] {
  2740  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  2741  	}
  2742  }
  2743  
  2744  func TestSetBytes(t *testing.T) {
  2745  	type B []byte
  2746  	var x B
  2747  	y := []byte{1, 2, 3, 4}
  2748  	ValueOf(&x).Elem().SetBytes(y)
  2749  	if !bytes.Equal(x, y) {
  2750  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  2751  	}
  2752  	if &x[0] != &y[0] {
  2753  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  2754  	}
  2755  }
  2756  
  2757  type Private struct {
  2758  	x int
  2759  	y **int
  2760  }
  2761  
  2762  func (p *Private) m() {
  2763  }
  2764  
  2765  type Public struct {
  2766  	X int
  2767  	Y **int
  2768  }
  2769  
  2770  func (p *Public) M() {
  2771  }
  2772  
  2773  func TestUnexported(t *testing.T) {
  2774  	var pub Public
  2775  	v := ValueOf(&pub)
  2776  	isValid(v.Elem().Field(0))
  2777  	isValid(v.Elem().Field(1))
  2778  	isValid(v.Elem().FieldByName("X"))
  2779  	isValid(v.Elem().FieldByName("Y"))
  2780  	isValid(v.Type().Method(0).Func)
  2781  	isNonNil(v.Elem().Field(0).Interface())
  2782  	isNonNil(v.Elem().Field(1).Interface())
  2783  	isNonNil(v.Elem().FieldByName("X").Interface())
  2784  	isNonNil(v.Elem().FieldByName("Y").Interface())
  2785  	isNonNil(v.Type().Method(0).Func.Interface())
  2786  
  2787  	var priv Private
  2788  	v = ValueOf(&priv)
  2789  	isValid(v.Elem().Field(0))
  2790  	isValid(v.Elem().Field(1))
  2791  	isValid(v.Elem().FieldByName("x"))
  2792  	isValid(v.Elem().FieldByName("y"))
  2793  	isValid(v.Type().Method(0).Func)
  2794  	shouldPanic(func() { v.Elem().Field(0).Interface() })
  2795  	shouldPanic(func() { v.Elem().Field(1).Interface() })
  2796  	shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
  2797  	shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
  2798  	shouldPanic(func() { v.Type().Method(0).Func.Interface() })
  2799  }
  2800  
  2801  func shouldPanic(f func()) {
  2802  	defer func() {
  2803  		if recover() == nil {
  2804  			panic("did not panic")
  2805  		}
  2806  	}()
  2807  	f()
  2808  }
  2809  
  2810  func isNonNil(x interface{}) {
  2811  	if x == nil {
  2812  		panic("nil interface")
  2813  	}
  2814  }
  2815  
  2816  func isValid(v Value) {
  2817  	if !v.IsValid() {
  2818  		panic("zero Value")
  2819  	}
  2820  }
  2821  
  2822  func TestAlias(t *testing.T) {
  2823  	x := string("hello")
  2824  	v := ValueOf(&x).Elem()
  2825  	oldvalue := v.Interface()
  2826  	v.SetString("world")
  2827  	newvalue := v.Interface()
  2828  
  2829  	if oldvalue != "hello" || newvalue != "world" {
  2830  		t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
  2831  	}
  2832  }
  2833  
  2834  var V = ValueOf
  2835  
  2836  func EmptyInterfaceV(x interface{}) Value {
  2837  	return ValueOf(&x).Elem()
  2838  }
  2839  
  2840  func ReaderV(x io.Reader) Value {
  2841  	return ValueOf(&x).Elem()
  2842  }
  2843  
  2844  func ReadWriterV(x io.ReadWriter) Value {
  2845  	return ValueOf(&x).Elem()
  2846  }
  2847  
  2848  type Empty struct{}
  2849  type MyString string
  2850  type MyBytes []byte
  2851  type MyRunes []int32
  2852  type MyFunc func()
  2853  type MyByte byte
  2854  
  2855  var convertTests = []struct {
  2856  	in  Value
  2857  	out Value
  2858  }{
  2859  	// numbers
  2860  	/*
  2861  		Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
  2862  
  2863  		package main
  2864  
  2865  		import "fmt"
  2866  
  2867  		var numbers = []string{
  2868  			"int8", "uint8", "int16", "uint16",
  2869  			"int32", "uint32", "int64", "uint64",
  2870  			"int", "uint", "uintptr",
  2871  			"float32", "float64",
  2872  		}
  2873  
  2874  		func main() {
  2875  			// all pairs but in an unusual order,
  2876  			// to emit all the int8, uint8 cases
  2877  			// before n grows too big.
  2878  			n := 1
  2879  			for i, f := range numbers {
  2880  				for _, g := range numbers[i:] {
  2881  					fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
  2882  					n++
  2883  					if f != g {
  2884  						fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
  2885  						n++
  2886  					}
  2887  				}
  2888  			}
  2889  		}
  2890  	*/
  2891  	{V(int8(1)), V(int8(1))},
  2892  	{V(int8(2)), V(uint8(2))},
  2893  	{V(uint8(3)), V(int8(3))},
  2894  	{V(int8(4)), V(int16(4))},
  2895  	{V(int16(5)), V(int8(5))},
  2896  	{V(int8(6)), V(uint16(6))},
  2897  	{V(uint16(7)), V(int8(7))},
  2898  	{V(int8(8)), V(int32(8))},
  2899  	{V(int32(9)), V(int8(9))},
  2900  	{V(int8(10)), V(uint32(10))},
  2901  	{V(uint32(11)), V(int8(11))},
  2902  	{V(int8(12)), V(int64(12))},
  2903  	{V(int64(13)), V(int8(13))},
  2904  	{V(int8(14)), V(uint64(14))},
  2905  	{V(uint64(15)), V(int8(15))},
  2906  	{V(int8(16)), V(int(16))},
  2907  	{V(int(17)), V(int8(17))},
  2908  	{V(int8(18)), V(uint(18))},
  2909  	{V(uint(19)), V(int8(19))},
  2910  	{V(int8(20)), V(uintptr(20))},
  2911  	{V(uintptr(21)), V(int8(21))},
  2912  	{V(int8(22)), V(float32(22))},
  2913  	{V(float32(23)), V(int8(23))},
  2914  	{V(int8(24)), V(float64(24))},
  2915  	{V(float64(25)), V(int8(25))},
  2916  	{V(uint8(26)), V(uint8(26))},
  2917  	{V(uint8(27)), V(int16(27))},
  2918  	{V(int16(28)), V(uint8(28))},
  2919  	{V(uint8(29)), V(uint16(29))},
  2920  	{V(uint16(30)), V(uint8(30))},
  2921  	{V(uint8(31)), V(int32(31))},
  2922  	{V(int32(32)), V(uint8(32))},
  2923  	{V(uint8(33)), V(uint32(33))},
  2924  	{V(uint32(34)), V(uint8(34))},
  2925  	{V(uint8(35)), V(int64(35))},
  2926  	{V(int64(36)), V(uint8(36))},
  2927  	{V(uint8(37)), V(uint64(37))},
  2928  	{V(uint64(38)), V(uint8(38))},
  2929  	{V(uint8(39)), V(int(39))},
  2930  	{V(int(40)), V(uint8(40))},
  2931  	{V(uint8(41)), V(uint(41))},
  2932  	{V(uint(42)), V(uint8(42))},
  2933  	{V(uint8(43)), V(uintptr(43))},
  2934  	{V(uintptr(44)), V(uint8(44))},
  2935  	{V(uint8(45)), V(float32(45))},
  2936  	{V(float32(46)), V(uint8(46))},
  2937  	{V(uint8(47)), V(float64(47))},
  2938  	{V(float64(48)), V(uint8(48))},
  2939  	{V(int16(49)), V(int16(49))},
  2940  	{V(int16(50)), V(uint16(50))},
  2941  	{V(uint16(51)), V(int16(51))},
  2942  	{V(int16(52)), V(int32(52))},
  2943  	{V(int32(53)), V(int16(53))},
  2944  	{V(int16(54)), V(uint32(54))},
  2945  	{V(uint32(55)), V(int16(55))},
  2946  	{V(int16(56)), V(int64(56))},
  2947  	{V(int64(57)), V(int16(57))},
  2948  	{V(int16(58)), V(uint64(58))},
  2949  	{V(uint64(59)), V(int16(59))},
  2950  	{V(int16(60)), V(int(60))},
  2951  	{V(int(61)), V(int16(61))},
  2952  	{V(int16(62)), V(uint(62))},
  2953  	{V(uint(63)), V(int16(63))},
  2954  	{V(int16(64)), V(uintptr(64))},
  2955  	{V(uintptr(65)), V(int16(65))},
  2956  	{V(int16(66)), V(float32(66))},
  2957  	{V(float32(67)), V(int16(67))},
  2958  	{V(int16(68)), V(float64(68))},
  2959  	{V(float64(69)), V(int16(69))},
  2960  	{V(uint16(70)), V(uint16(70))},
  2961  	{V(uint16(71)), V(int32(71))},
  2962  	{V(int32(72)), V(uint16(72))},
  2963  	{V(uint16(73)), V(uint32(73))},
  2964  	{V(uint32(74)), V(uint16(74))},
  2965  	{V(uint16(75)), V(int64(75))},
  2966  	{V(int64(76)), V(uint16(76))},
  2967  	{V(uint16(77)), V(uint64(77))},
  2968  	{V(uint64(78)), V(uint16(78))},
  2969  	{V(uint16(79)), V(int(79))},
  2970  	{V(int(80)), V(uint16(80))},
  2971  	{V(uint16(81)), V(uint(81))},
  2972  	{V(uint(82)), V(uint16(82))},
  2973  	{V(uint16(83)), V(uintptr(83))},
  2974  	{V(uintptr(84)), V(uint16(84))},
  2975  	{V(uint16(85)), V(float32(85))},
  2976  	{V(float32(86)), V(uint16(86))},
  2977  	{V(uint16(87)), V(float64(87))},
  2978  	{V(float64(88)), V(uint16(88))},
  2979  	{V(int32(89)), V(int32(89))},
  2980  	{V(int32(90)), V(uint32(90))},
  2981  	{V(uint32(91)), V(int32(91))},
  2982  	{V(int32(92)), V(int64(92))},
  2983  	{V(int64(93)), V(int32(93))},
  2984  	{V(int32(94)), V(uint64(94))},
  2985  	{V(uint64(95)), V(int32(95))},
  2986  	{V(int32(96)), V(int(96))},
  2987  	{V(int(97)), V(int32(97))},
  2988  	{V(int32(98)), V(uint(98))},
  2989  	{V(uint(99)), V(int32(99))},
  2990  	{V(int32(100)), V(uintptr(100))},
  2991  	{V(uintptr(101)), V(int32(101))},
  2992  	{V(int32(102)), V(float32(102))},
  2993  	{V(float32(103)), V(int32(103))},
  2994  	{V(int32(104)), V(float64(104))},
  2995  	{V(float64(105)), V(int32(105))},
  2996  	{V(uint32(106)), V(uint32(106))},
  2997  	{V(uint32(107)), V(int64(107))},
  2998  	{V(int64(108)), V(uint32(108))},
  2999  	{V(uint32(109)), V(uint64(109))},
  3000  	{V(uint64(110)), V(uint32(110))},
  3001  	{V(uint32(111)), V(int(111))},
  3002  	{V(int(112)), V(uint32(112))},
  3003  	{V(uint32(113)), V(uint(113))},
  3004  	{V(uint(114)), V(uint32(114))},
  3005  	{V(uint32(115)), V(uintptr(115))},
  3006  	{V(uintptr(116)), V(uint32(116))},
  3007  	{V(uint32(117)), V(float32(117))},
  3008  	{V(float32(118)), V(uint32(118))},
  3009  	{V(uint32(119)), V(float64(119))},
  3010  	{V(float64(120)), V(uint32(120))},
  3011  	{V(int64(121)), V(int64(121))},
  3012  	{V(int64(122)), V(uint64(122))},
  3013  	{V(uint64(123)), V(int64(123))},
  3014  	{V(int64(124)), V(int(124))},
  3015  	{V(int(125)), V(int64(125))},
  3016  	{V(int64(126)), V(uint(126))},
  3017  	{V(uint(127)), V(int64(127))},
  3018  	{V(int64(128)), V(uintptr(128))},
  3019  	{V(uintptr(129)), V(int64(129))},
  3020  	{V(int64(130)), V(float32(130))},
  3021  	{V(float32(131)), V(int64(131))},
  3022  	{V(int64(132)), V(float64(132))},
  3023  	{V(float64(133)), V(int64(133))},
  3024  	{V(uint64(134)), V(uint64(134))},
  3025  	{V(uint64(135)), V(int(135))},
  3026  	{V(int(136)), V(uint64(136))},
  3027  	{V(uint64(137)), V(uint(137))},
  3028  	{V(uint(138)), V(uint64(138))},
  3029  	{V(uint64(139)), V(uintptr(139))},
  3030  	{V(uintptr(140)), V(uint64(140))},
  3031  	{V(uint64(141)), V(float32(141))},
  3032  	{V(float32(142)), V(uint64(142))},
  3033  	{V(uint64(143)), V(float64(143))},
  3034  	{V(float64(144)), V(uint64(144))},
  3035  	{V(int(145)), V(int(145))},
  3036  	{V(int(146)), V(uint(146))},
  3037  	{V(uint(147)), V(int(147))},
  3038  	{V(int(148)), V(uintptr(148))},
  3039  	{V(uintptr(149)), V(int(149))},
  3040  	{V(int(150)), V(float32(150))},
  3041  	{V(float32(151)), V(int(151))},
  3042  	{V(int(152)), V(float64(152))},
  3043  	{V(float64(153)), V(int(153))},
  3044  	{V(uint(154)), V(uint(154))},
  3045  	{V(uint(155)), V(uintptr(155))},
  3046  	{V(uintptr(156)), V(uint(156))},
  3047  	{V(uint(157)), V(float32(157))},
  3048  	{V(float32(158)), V(uint(158))},
  3049  	{V(uint(159)), V(float64(159))},
  3050  	{V(float64(160)), V(uint(160))},
  3051  	{V(uintptr(161)), V(uintptr(161))},
  3052  	{V(uintptr(162)), V(float32(162))},
  3053  	{V(float32(163)), V(uintptr(163))},
  3054  	{V(uintptr(164)), V(float64(164))},
  3055  	{V(float64(165)), V(uintptr(165))},
  3056  	{V(float32(166)), V(float32(166))},
  3057  	{V(float32(167)), V(float64(167))},
  3058  	{V(float64(168)), V(float32(168))},
  3059  	{V(float64(169)), V(float64(169))},
  3060  
  3061  	// truncation
  3062  	{V(float64(1.5)), V(int(1))},
  3063  
  3064  	// complex
  3065  	{V(complex64(1i)), V(complex64(1i))},
  3066  	{V(complex64(2i)), V(complex128(2i))},
  3067  	{V(complex128(3i)), V(complex64(3i))},
  3068  	{V(complex128(4i)), V(complex128(4i))},
  3069  
  3070  	// string
  3071  	{V(string("hello")), V(string("hello"))},
  3072  	{V(string("bytes1")), V([]byte("bytes1"))},
  3073  	{V([]byte("bytes2")), V(string("bytes2"))},
  3074  	{V([]byte("bytes3")), V([]byte("bytes3"))},
  3075  	{V(string("runes♝")), V([]rune("runes♝"))},
  3076  	{V([]rune("runes♕")), V(string("runes♕"))},
  3077  	{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  3078  	{V(int('a')), V(string("a"))},
  3079  	{V(int8('a')), V(string("a"))},
  3080  	{V(int16('a')), V(string("a"))},
  3081  	{V(int32('a')), V(string("a"))},
  3082  	{V(int64('a')), V(string("a"))},
  3083  	{V(uint('a')), V(string("a"))},
  3084  	{V(uint8('a')), V(string("a"))},
  3085  	{V(uint16('a')), V(string("a"))},
  3086  	{V(uint32('a')), V(string("a"))},
  3087  	{V(uint64('a')), V(string("a"))},
  3088  	{V(uintptr('a')), V(string("a"))},
  3089  	{V(int(-1)), V(string("\uFFFD"))},
  3090  	{V(int8(-2)), V(string("\uFFFD"))},
  3091  	{V(int16(-3)), V(string("\uFFFD"))},
  3092  	{V(int32(-4)), V(string("\uFFFD"))},
  3093  	{V(int64(-5)), V(string("\uFFFD"))},
  3094  	{V(uint(0x110001)), V(string("\uFFFD"))},
  3095  	{V(uint32(0x110002)), V(string("\uFFFD"))},
  3096  	{V(uint64(0x110003)), V(string("\uFFFD"))},
  3097  	{V(uintptr(0x110004)), V(string("\uFFFD"))},
  3098  
  3099  	// named string
  3100  	{V(MyString("hello")), V(string("hello"))},
  3101  	{V(string("hello")), V(MyString("hello"))},
  3102  	{V(string("hello")), V(string("hello"))},
  3103  	{V(MyString("hello")), V(MyString("hello"))},
  3104  	{V(MyString("bytes1")), V([]byte("bytes1"))},
  3105  	{V([]byte("bytes2")), V(MyString("bytes2"))},
  3106  	{V([]byte("bytes3")), V([]byte("bytes3"))},
  3107  	{V(MyString("runes♝")), V([]rune("runes♝"))},
  3108  	{V([]rune("runes♕")), V(MyString("runes♕"))},
  3109  	{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  3110  	{V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  3111  	{V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  3112  	{V(int('a')), V(MyString("a"))},
  3113  	{V(int8('a')), V(MyString("a"))},
  3114  	{V(int16('a')), V(MyString("a"))},
  3115  	{V(int32('a')), V(MyString("a"))},
  3116  	{V(int64('a')), V(MyString("a"))},
  3117  	{V(uint('a')), V(MyString("a"))},
  3118  	{V(uint8('a')), V(MyString("a"))},
  3119  	{V(uint16('a')), V(MyString("a"))},
  3120  	{V(uint32('a')), V(MyString("a"))},
  3121  	{V(uint64('a')), V(MyString("a"))},
  3122  	{V(uintptr('a')), V(MyString("a"))},
  3123  	{V(int(-1)), V(MyString("\uFFFD"))},
  3124  	{V(int8(-2)), V(MyString("\uFFFD"))},
  3125  	{V(int16(-3)), V(MyString("\uFFFD"))},
  3126  	{V(int32(-4)), V(MyString("\uFFFD"))},
  3127  	{V(int64(-5)), V(MyString("\uFFFD"))},
  3128  	{V(uint(0x110001)), V(MyString("\uFFFD"))},
  3129  	{V(uint32(0x110002)), V(MyString("\uFFFD"))},
  3130  	{V(uint64(0x110003)), V(MyString("\uFFFD"))},
  3131  	{V(uintptr(0x110004)), V(MyString("\uFFFD"))},
  3132  
  3133  	// named []byte
  3134  	{V(string("bytes1")), V(MyBytes("bytes1"))},
  3135  	{V(MyBytes("bytes2")), V(string("bytes2"))},
  3136  	{V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
  3137  	{V(MyString("bytes1")), V(MyBytes("bytes1"))},
  3138  	{V(MyBytes("bytes2")), V(MyString("bytes2"))},
  3139  
  3140  	// named []rune
  3141  	{V(string("runes♝")), V(MyRunes("runes♝"))},
  3142  	{V(MyRunes("runes♕")), V(string("runes♕"))},
  3143  	{V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  3144  	{V(MyString("runes♝")), V(MyRunes("runes♝"))},
  3145  	{V(MyRunes("runes♕")), V(MyString("runes♕"))},
  3146  
  3147  	// named types and equal underlying types
  3148  	{V(new(int)), V(new(integer))},
  3149  	{V(new(integer)), V(new(int))},
  3150  	{V(Empty{}), V(struct{}{})},
  3151  	{V(new(Empty)), V(new(struct{}))},
  3152  	{V(struct{}{}), V(Empty{})},
  3153  	{V(new(struct{})), V(new(Empty))},
  3154  	{V(Empty{}), V(Empty{})},
  3155  	{V(MyBytes{}), V([]byte{})},
  3156  	{V([]byte{}), V(MyBytes{})},
  3157  	{V((func())(nil)), V(MyFunc(nil))},
  3158  	{V((MyFunc)(nil)), V((func())(nil))},
  3159  
  3160  	// can convert *byte and *MyByte
  3161  	{V((*byte)(nil)), V((*MyByte)(nil))},
  3162  	{V((*MyByte)(nil)), V((*byte)(nil))},
  3163  
  3164  	// cannot convert mismatched array sizes
  3165  	{V([2]byte{}), V([2]byte{})},
  3166  	{V([3]byte{}), V([3]byte{})},
  3167  
  3168  	// cannot convert other instances
  3169  	{V((**byte)(nil)), V((**byte)(nil))},
  3170  	{V((**MyByte)(nil)), V((**MyByte)(nil))},
  3171  	{V((chan byte)(nil)), V((chan byte)(nil))},
  3172  	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  3173  	{V(([]byte)(nil)), V(([]byte)(nil))},
  3174  	{V(([]MyByte)(nil)), V(([]MyByte)(nil))},
  3175  	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  3176  	{V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
  3177  	{V((map[byte]int)(nil)), V((map[byte]int)(nil))},
  3178  	{V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
  3179  	{V([2]byte{}), V([2]byte{})},
  3180  	{V([2]MyByte{}), V([2]MyByte{})},
  3181  
  3182  	// other
  3183  	{V((***int)(nil)), V((***int)(nil))},
  3184  	{V((***byte)(nil)), V((***byte)(nil))},
  3185  	{V((***int32)(nil)), V((***int32)(nil))},
  3186  	{V((***int64)(nil)), V((***int64)(nil))},
  3187  	{V((chan int)(nil)), V((<-chan int)(nil))},
  3188  	{V((chan int)(nil)), V((chan<- int)(nil))},
  3189  	{V((chan string)(nil)), V((<-chan string)(nil))},
  3190  	{V((chan string)(nil)), V((chan<- string)(nil))},
  3191  	{V((chan byte)(nil)), V((chan byte)(nil))},
  3192  	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  3193  	{V((map[int]bool)(nil)), V((map[int]bool)(nil))},
  3194  	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  3195  	{V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
  3196  	{V([]uint(nil)), V([]uint(nil))},
  3197  	{V([]int(nil)), V([]int(nil))},
  3198  	{V(new(interface{})), V(new(interface{}))},
  3199  	{V(new(io.Reader)), V(new(io.Reader))},
  3200  	{V(new(io.Writer)), V(new(io.Writer))},
  3201  
  3202  	// interfaces
  3203  	{V(int(1)), EmptyInterfaceV(int(1))},
  3204  	{V(string("hello")), EmptyInterfaceV(string("hello"))},
  3205  	{V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  3206  	{ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  3207  	{V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
  3208  }
  3209  
  3210  func TestConvert(t *testing.T) {
  3211  	canConvert := map[[2]Type]bool{}
  3212  	all := map[Type]bool{}
  3213  
  3214  	for _, tt := range convertTests {
  3215  		t1 := tt.in.Type()
  3216  		if !t1.ConvertibleTo(t1) {
  3217  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
  3218  			continue
  3219  		}
  3220  
  3221  		t2 := tt.out.Type()
  3222  		if !t1.ConvertibleTo(t2) {
  3223  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
  3224  			continue
  3225  		}
  3226  
  3227  		all[t1] = true
  3228  		all[t2] = true
  3229  		canConvert[[2]Type{t1, t2}] = true
  3230  
  3231  		// vout1 represents the in value converted to the in type.
  3232  		v1 := tt.in
  3233  		vout1 := v1.Convert(t1)
  3234  		out1 := vout1.Interface()
  3235  		if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
  3236  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
  3237  		}
  3238  
  3239  		// vout2 represents the in value converted to the out type.
  3240  		vout2 := v1.Convert(t2)
  3241  		out2 := vout2.Interface()
  3242  		if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
  3243  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
  3244  		}
  3245  
  3246  		// vout3 represents a new value of the out type, set to vout2.  This makes
  3247  		// sure the converted value vout2 is really usable as a regular value.
  3248  		vout3 := New(t2).Elem()
  3249  		vout3.Set(vout2)
  3250  		out3 := vout3.Interface()
  3251  		if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
  3252  			t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
  3253  		}
  3254  
  3255  		if IsRO(v1) {
  3256  			t.Errorf("table entry %v is RO, should not be", v1)
  3257  		}
  3258  		if IsRO(vout1) {
  3259  			t.Errorf("self-conversion output %v is RO, should not be", vout1)
  3260  		}
  3261  		if IsRO(vout2) {
  3262  			t.Errorf("conversion output %v is RO, should not be", vout2)
  3263  		}
  3264  		if IsRO(vout3) {
  3265  			t.Errorf("set(conversion output) %v is RO, should not be", vout3)
  3266  		}
  3267  		if !IsRO(MakeRO(v1).Convert(t1)) {
  3268  			t.Errorf("RO self-conversion output %v is not RO, should be", v1)
  3269  		}
  3270  		if !IsRO(MakeRO(v1).Convert(t2)) {
  3271  			t.Errorf("RO conversion output %v is not RO, should be", v1)
  3272  		}
  3273  	}
  3274  
  3275  	// Assume that of all the types we saw during the tests,
  3276  	// if there wasn't an explicit entry for a conversion between
  3277  	// a pair of types, then it's not to be allowed. This checks for
  3278  	// things like 'int64' converting to '*int'.
  3279  	for t1 := range all {
  3280  		for t2 := range all {
  3281  			expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
  3282  			if ok := t1.ConvertibleTo(t2); ok != expectOK {
  3283  				t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
  3284  			}
  3285  		}
  3286  	}
  3287  }
  3288  
  3289  type ComparableStruct struct {
  3290  	X int
  3291  }
  3292  
  3293  type NonComparableStruct struct {
  3294  	X int
  3295  	Y map[string]int
  3296  }
  3297  
  3298  var comparableTests = []struct {
  3299  	typ Type
  3300  	ok  bool
  3301  }{
  3302  	{TypeOf(1), true},
  3303  	{TypeOf("hello"), true},
  3304  	{TypeOf(new(byte)), true},
  3305  	{TypeOf((func())(nil)), false},
  3306  	{TypeOf([]byte{}), false},
  3307  	{TypeOf(map[string]int{}), false},
  3308  	{TypeOf(make(chan int)), true},
  3309  	{TypeOf(1.5), true},
  3310  	{TypeOf(false), true},
  3311  	{TypeOf(1i), true},
  3312  	{TypeOf(ComparableStruct{}), true},
  3313  	{TypeOf(NonComparableStruct{}), false},
  3314  	{TypeOf([10]map[string]int{}), false},
  3315  	{TypeOf([10]string{}), true},
  3316  	{TypeOf(new(interface{})).Elem(), true},
  3317  }
  3318  
  3319  func TestComparable(t *testing.T) {
  3320  	for _, tt := range comparableTests {
  3321  		if ok := tt.typ.Comparable(); ok != tt.ok {
  3322  			t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
  3323  		}
  3324  	}
  3325  }
  3326  
  3327  func TestOverflow(t *testing.T) {
  3328  	if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
  3329  		t.Errorf("%v wrongly overflows float64", 1e300)
  3330  	}
  3331  
  3332  	maxFloat32 := float64((1<<24 - 1) << (127 - 23))
  3333  	if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
  3334  		t.Errorf("%v wrongly overflows float32", maxFloat32)
  3335  	}
  3336  	ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
  3337  	if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
  3338  		t.Errorf("%v should overflow float32", ovfFloat32)
  3339  	}
  3340  	if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
  3341  		t.Errorf("%v should overflow float32", -ovfFloat32)
  3342  	}
  3343  
  3344  	maxInt32 := int64(0x7fffffff)
  3345  	if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
  3346  		t.Errorf("%v wrongly overflows int32", maxInt32)
  3347  	}
  3348  	if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
  3349  		t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
  3350  	}
  3351  	ovfInt32 := int64(1 << 31)
  3352  	if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
  3353  		t.Errorf("%v should overflow int32", ovfInt32)
  3354  	}
  3355  
  3356  	maxUint32 := uint64(0xffffffff)
  3357  	if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
  3358  		t.Errorf("%v wrongly overflows uint32", maxUint32)
  3359  	}
  3360  	ovfUint32 := uint64(1 << 32)
  3361  	if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
  3362  		t.Errorf("%v should overflow uint32", ovfUint32)
  3363  	}
  3364  }
  3365  
  3366  func checkSameType(t *testing.T, x, y interface{}) {
  3367  	if TypeOf(x) != TypeOf(y) {
  3368  		t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
  3369  	}
  3370  }
  3371  
  3372  func TestArrayOf(t *testing.T) {
  3373  	// TODO(rsc): Finish ArrayOf and enable-test.
  3374  	t.Skip("ArrayOf is not finished (and not exported)")
  3375  
  3376  	// check construction and use of type not in binary
  3377  	type T int
  3378  	at := ArrayOf(10, TypeOf(T(1)))
  3379  	v := New(at).Elem()
  3380  	for i := 0; i < v.Len(); i++ {
  3381  		v.Index(i).Set(ValueOf(T(i)))
  3382  	}
  3383  	s := fmt.Sprint(v.Interface())
  3384  	want := "[0 1 2 3 4 5 6 7 8 9]"
  3385  	if s != want {
  3386  		t.Errorf("constructed array = %s, want %s", s, want)
  3387  	}
  3388  
  3389  	// check that type already in binary is found
  3390  	checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
  3391  }
  3392  
  3393  func TestSliceOf(t *testing.T) {
  3394  	// check construction and use of type not in binary
  3395  	type T int
  3396  	st := SliceOf(TypeOf(T(1)))
  3397  	v := MakeSlice(st, 10, 10)
  3398  	runtime.GC()
  3399  	for i := 0; i < v.Len(); i++ {
  3400  		v.Index(i).Set(ValueOf(T(i)))
  3401  		runtime.GC()
  3402  	}
  3403  	s := fmt.Sprint(v.Interface())
  3404  	want := "[0 1 2 3 4 5 6 7 8 9]"
  3405  	if s != want {
  3406  		t.Errorf("constructed slice = %s, want %s", s, want)
  3407  	}
  3408  
  3409  	// check that type already in binary is found
  3410  	type T1 int
  3411  	checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
  3412  }
  3413  
  3414  func TestSliceOverflow(t *testing.T) {
  3415  	// check that MakeSlice panics when size of slice overflows uint
  3416  	const S = 1e6
  3417  	s := uint(S)
  3418  	l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
  3419  	if l*s >= s {
  3420  		t.Fatal("slice size does not overflow")
  3421  	}
  3422  	var x [S]byte
  3423  	st := SliceOf(TypeOf(x))
  3424  	defer func() {
  3425  		err := recover()
  3426  		if err == nil {
  3427  			t.Fatal("slice overflow does not panic")
  3428  		}
  3429  	}()
  3430  	MakeSlice(st, int(l), int(l))
  3431  }
  3432  
  3433  func TestSliceOfGC(t *testing.T) {
  3434  	type T *uintptr
  3435  	tt := TypeOf(T(nil))
  3436  	st := SliceOf(tt)
  3437  	const n = 100
  3438  	var x []interface{}
  3439  	for i := 0; i < n; i++ {
  3440  		v := MakeSlice(st, n, n)
  3441  		for j := 0; j < v.Len(); j++ {
  3442  			p := new(uintptr)
  3443  			*p = uintptr(i*n + j)
  3444  			v.Index(j).Set(ValueOf(p).Convert(tt))
  3445  		}
  3446  		x = append(x, v.Interface())
  3447  	}
  3448  	runtime.GC()
  3449  
  3450  	for i, xi := range x {
  3451  		v := ValueOf(xi)
  3452  		for j := 0; j < v.Len(); j++ {
  3453  			k := v.Index(j).Elem().Interface()
  3454  			if k != uintptr(i*n+j) {
  3455  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3456  			}
  3457  		}
  3458  	}
  3459  }
  3460  
  3461  func TestChanOf(t *testing.T) {
  3462  	// check construction and use of type not in binary
  3463  	type T string
  3464  	ct := ChanOf(BothDir, TypeOf(T("")))
  3465  	v := MakeChan(ct, 2)
  3466  	runtime.GC()
  3467  	v.Send(ValueOf(T("hello")))
  3468  	runtime.GC()
  3469  	v.Send(ValueOf(T("world")))
  3470  	runtime.GC()
  3471  
  3472  	sv1, _ := v.Recv()
  3473  	sv2, _ := v.Recv()
  3474  	s1 := sv1.String()
  3475  	s2 := sv2.String()
  3476  	if s1 != "hello" || s2 != "world" {
  3477  		t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
  3478  	}
  3479  
  3480  	// check that type already in binary is found
  3481  	type T1 int
  3482  	checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
  3483  }
  3484  
  3485  func TestChanOfGC(t *testing.T) {
  3486  	done := make(chan bool, 1)
  3487  	go func() {
  3488  		select {
  3489  		case <-done:
  3490  		case <-time.After(5 * time.Second):
  3491  			panic("deadlock in TestChanOfGC")
  3492  		}
  3493  	}()
  3494  
  3495  	defer func() {
  3496  		done <- true
  3497  	}()
  3498  
  3499  	type T *uintptr
  3500  	tt := TypeOf(T(nil))
  3501  	ct := ChanOf(BothDir, tt)
  3502  
  3503  	// NOTE: The garbage collector handles allocated channels specially,
  3504  	// so we have to save pointers to channels in x; the pointer code will
  3505  	// use the gc info in the newly constructed chan type.
  3506  	const n = 100
  3507  	var x []interface{}
  3508  	for i := 0; i < n; i++ {
  3509  		v := MakeChan(ct, n)
  3510  		for j := 0; j < n; j++ {
  3511  			p := new(uintptr)
  3512  			*p = uintptr(i*n + j)
  3513  			v.Send(ValueOf(p).Convert(tt))
  3514  		}
  3515  		pv := New(ct)
  3516  		pv.Elem().Set(v)
  3517  		x = append(x, pv.Interface())
  3518  	}
  3519  	runtime.GC()
  3520  
  3521  	for i, xi := range x {
  3522  		v := ValueOf(xi).Elem()
  3523  		for j := 0; j < n; j++ {
  3524  			pv, _ := v.Recv()
  3525  			k := pv.Elem().Interface()
  3526  			if k != uintptr(i*n+j) {
  3527  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3528  			}
  3529  		}
  3530  	}
  3531  }
  3532  
  3533  func TestMapOf(t *testing.T) {
  3534  	// check construction and use of type not in binary
  3535  	type K string
  3536  	type V float64
  3537  
  3538  	v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
  3539  	runtime.GC()
  3540  	v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
  3541  	runtime.GC()
  3542  
  3543  	s := fmt.Sprint(v.Interface())
  3544  	want := "map[a:1]"
  3545  	if s != want {
  3546  		t.Errorf("constructed map = %s, want %s", s, want)
  3547  	}
  3548  
  3549  	// check that type already in binary is found
  3550  	checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
  3551  
  3552  	// check that invalid key type panics
  3553  	shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
  3554  }
  3555  
  3556  func TestMapOfGCKeys(t *testing.T) {
  3557  	type T *uintptr
  3558  	tt := TypeOf(T(nil))
  3559  	mt := MapOf(tt, TypeOf(false))
  3560  
  3561  	// NOTE: The garbage collector handles allocated maps specially,
  3562  	// so we have to save pointers to maps in x; the pointer code will
  3563  	// use the gc info in the newly constructed map type.
  3564  	const n = 100
  3565  	var x []interface{}
  3566  	for i := 0; i < n; i++ {
  3567  		v := MakeMap(mt)
  3568  		for j := 0; j < n; j++ {
  3569  			p := new(uintptr)
  3570  			*p = uintptr(i*n + j)
  3571  			v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
  3572  		}
  3573  		pv := New(mt)
  3574  		pv.Elem().Set(v)
  3575  		x = append(x, pv.Interface())
  3576  	}
  3577  	runtime.GC()
  3578  
  3579  	for i, xi := range x {
  3580  		v := ValueOf(xi).Elem()
  3581  		var out []int
  3582  		for _, kv := range v.MapKeys() {
  3583  			out = append(out, int(kv.Elem().Interface().(uintptr)))
  3584  		}
  3585  		sort.Ints(out)
  3586  		for j, k := range out {
  3587  			if k != i*n+j {
  3588  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3589  			}
  3590  		}
  3591  	}
  3592  }
  3593  
  3594  func TestMapOfGCValues(t *testing.T) {
  3595  	type T *uintptr
  3596  	tt := TypeOf(T(nil))
  3597  	mt := MapOf(TypeOf(1), tt)
  3598  
  3599  	// NOTE: The garbage collector handles allocated maps specially,
  3600  	// so we have to save pointers to maps in x; the pointer code will
  3601  	// use the gc info in the newly constructed map type.
  3602  	const n = 100
  3603  	var x []interface{}
  3604  	for i := 0; i < n; i++ {
  3605  		v := MakeMap(mt)
  3606  		for j := 0; j < n; j++ {
  3607  			p := new(uintptr)
  3608  			*p = uintptr(i*n + j)
  3609  			v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
  3610  		}
  3611  		pv := New(mt)
  3612  		pv.Elem().Set(v)
  3613  		x = append(x, pv.Interface())
  3614  	}
  3615  	runtime.GC()
  3616  
  3617  	for i, xi := range x {
  3618  		v := ValueOf(xi).Elem()
  3619  		for j := 0; j < n; j++ {
  3620  			k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
  3621  			if k != uintptr(i*n+j) {
  3622  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3623  			}
  3624  		}
  3625  	}
  3626  }
  3627  
  3628  type B1 struct {
  3629  	X int
  3630  	Y int
  3631  	Z int
  3632  }
  3633  
  3634  func BenchmarkFieldByName1(b *testing.B) {
  3635  	t := TypeOf(B1{})
  3636  	for i := 0; i < b.N; i++ {
  3637  		t.FieldByName("Z")
  3638  	}
  3639  }
  3640  
  3641  func BenchmarkFieldByName2(b *testing.B) {
  3642  	t := TypeOf(S3{})
  3643  	for i := 0; i < b.N; i++ {
  3644  		t.FieldByName("B")
  3645  	}
  3646  }
  3647  
  3648  type R0 struct {
  3649  	*R1
  3650  	*R2
  3651  	*R3
  3652  	*R4
  3653  }
  3654  
  3655  type R1 struct {
  3656  	*R5
  3657  	*R6
  3658  	*R7
  3659  	*R8
  3660  }
  3661  
  3662  type R2 R1
  3663  type R3 R1
  3664  type R4 R1
  3665  
  3666  type R5 struct {
  3667  	*R9
  3668  	*R10
  3669  	*R11
  3670  	*R12
  3671  }
  3672  
  3673  type R6 R5
  3674  type R7 R5
  3675  type R8 R5
  3676  
  3677  type R9 struct {
  3678  	*R13
  3679  	*R14
  3680  	*R15
  3681  	*R16
  3682  }
  3683  
  3684  type R10 R9
  3685  type R11 R9
  3686  type R12 R9
  3687  
  3688  type R13 struct {
  3689  	*R17
  3690  	*R18
  3691  	*R19
  3692  	*R20
  3693  }
  3694  
  3695  type R14 R13
  3696  type R15 R13
  3697  type R16 R13
  3698  
  3699  type R17 struct {
  3700  	*R21
  3701  	*R22
  3702  	*R23
  3703  	*R24
  3704  }
  3705  
  3706  type R18 R17
  3707  type R19 R17
  3708  type R20 R17
  3709  
  3710  type R21 struct {
  3711  	X int
  3712  }
  3713  
  3714  type R22 R21
  3715  type R23 R21
  3716  type R24 R21
  3717  
  3718  func TestEmbed(t *testing.T) {
  3719  	typ := TypeOf(R0{})
  3720  	f, ok := typ.FieldByName("X")
  3721  	if ok {
  3722  		t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
  3723  	}
  3724  }
  3725  
  3726  func BenchmarkFieldByName3(b *testing.B) {
  3727  	t := TypeOf(R0{})
  3728  	for i := 0; i < b.N; i++ {
  3729  		t.FieldByName("X")
  3730  	}
  3731  }
  3732  
  3733  type S struct {
  3734  	i1 int64
  3735  	i2 int64
  3736  }
  3737  
  3738  func BenchmarkInterfaceBig(b *testing.B) {
  3739  	v := ValueOf(S{})
  3740  	for i := 0; i < b.N; i++ {
  3741  		v.Interface()
  3742  	}
  3743  	b.StopTimer()
  3744  }
  3745  
  3746  func TestAllocsInterfaceBig(t *testing.T) {
  3747  	if testing.Short() {
  3748  		t.Skip("skipping malloc count in short mode")
  3749  	}
  3750  	v := ValueOf(S{})
  3751  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  3752  		t.Error("allocs:", allocs)
  3753  	}
  3754  }
  3755  
  3756  func BenchmarkInterfaceSmall(b *testing.B) {
  3757  	v := ValueOf(int64(0))
  3758  	for i := 0; i < b.N; i++ {
  3759  		v.Interface()
  3760  	}
  3761  }
  3762  
  3763  func TestAllocsInterfaceSmall(t *testing.T) {
  3764  	if testing.Short() {
  3765  		t.Skip("skipping malloc count in short mode")
  3766  	}
  3767  	v := ValueOf(int64(0))
  3768  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  3769  		t.Error("allocs:", allocs)
  3770  	}
  3771  }
  3772  
  3773  // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
  3774  // The basic usage is:
  3775  //
  3776  //	for x.Next() {
  3777  //		... code using x.Maybe() or x.Choice(n) to create test cases ...
  3778  //	}
  3779  //
  3780  // Each iteration of the loop returns a different set of results, until all
  3781  // possible result sets have been explored. It is okay for different code paths
  3782  // to make different method call sequences on x, but there must be no
  3783  // other source of non-determinism in the call sequences.
  3784  //
  3785  // When faced with a new decision, x chooses randomly. Future explorations
  3786  // of that path will choose successive values for the result. Thus, stopping
  3787  // the loop after a fixed number of iterations gives somewhat stochastic
  3788  // testing.
  3789  //
  3790  // Example:
  3791  //
  3792  //	for x.Next() {
  3793  //		v := make([]bool, x.Choose(4))
  3794  //		for i := range v {
  3795  //			v[i] = x.Maybe()
  3796  //		}
  3797  //		fmt.Println(v)
  3798  //	}
  3799  //
  3800  // prints (in some order):
  3801  //
  3802  //	[]
  3803  //	[false]
  3804  //	[true]
  3805  //	[false false]
  3806  //	[false true]
  3807  //	...
  3808  //	[true true]
  3809  //	[false false false]
  3810  //	...
  3811  //	[true true true]
  3812  //	[false false false false]
  3813  //	...
  3814  //	[true true true true]
  3815  //
  3816  type exhaustive struct {
  3817  	r    *rand.Rand
  3818  	pos  int
  3819  	last []choice
  3820  }
  3821  
  3822  type choice struct {
  3823  	off int
  3824  	n   int
  3825  	max int
  3826  }
  3827  
  3828  func (x *exhaustive) Next() bool {
  3829  	if x.r == nil {
  3830  		x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
  3831  	}
  3832  	x.pos = 0
  3833  	if x.last == nil {
  3834  		x.last = []choice{}
  3835  		return true
  3836  	}
  3837  	for i := len(x.last) - 1; i >= 0; i-- {
  3838  		c := &x.last[i]
  3839  		if c.n+1 < c.max {
  3840  			c.n++
  3841  			x.last = x.last[:i+1]
  3842  			return true
  3843  		}
  3844  	}
  3845  	return false
  3846  }
  3847  
  3848  func (x *exhaustive) Choose(max int) int {
  3849  	if x.pos >= len(x.last) {
  3850  		x.last = append(x.last, choice{x.r.Intn(max), 0, max})
  3851  	}
  3852  	c := &x.last[x.pos]
  3853  	x.pos++
  3854  	if c.max != max {
  3855  		panic("inconsistent use of exhaustive tester")
  3856  	}
  3857  	return (c.n + c.off) % max
  3858  }
  3859  
  3860  func (x *exhaustive) Maybe() bool {
  3861  	return x.Choose(2) == 1
  3862  }
  3863  
  3864  func GCFunc(args []Value) []Value {
  3865  	runtime.GC()
  3866  	return []Value{}
  3867  }
  3868  
  3869  func TestReflectFuncTraceback(t *testing.T) {
  3870  	f := MakeFunc(TypeOf(func() {}), GCFunc)
  3871  	f.Call([]Value{})
  3872  }
  3873  
  3874  func TestReflectMethodTraceback(t *testing.T) {
  3875  	p := Point{3, 4}
  3876  	m := ValueOf(p).MethodByName("GCMethod")
  3877  	i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
  3878  	if i != 8 {
  3879  		t.Errorf("Call returned %d; want 8", i)
  3880  	}
  3881  }
  3882  
  3883  func TestBigZero(t *testing.T) {
  3884  	const size = 1 << 10
  3885  	var v [size]byte
  3886  	z := Zero(ValueOf(v).Type()).Interface().([size]byte)
  3887  	for i := 0; i < size; i++ {
  3888  		if z[i] != 0 {
  3889  			t.Fatalf("Zero object not all zero, index %d", i)
  3890  		}
  3891  	}
  3892  }
  3893  
  3894  func TestFieldByIndexNil(t *testing.T) {
  3895  	type P struct {
  3896  		F int
  3897  	}
  3898  	type T struct {
  3899  		*P
  3900  	}
  3901  	v := ValueOf(T{})
  3902  
  3903  	v.FieldByName("P") // should be fine
  3904  
  3905  	defer func() {
  3906  		if err := recover(); err == nil {
  3907  			t.Fatalf("no error")
  3908  		} else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
  3909  			t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
  3910  		}
  3911  	}()
  3912  	v.FieldByName("F") // should panic
  3913  
  3914  	t.Fatalf("did not panic")
  3915  }
  3916  
  3917  // Given
  3918  //	type Outer struct {
  3919  //		*Inner
  3920  //		...
  3921  //	}
  3922  // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
  3923  // The implementation is logically:
  3924  //	func (p *Outer) M() {
  3925  //		(p.Inner).M()
  3926  //	}
  3927  // but since the only change here is the replacement of one pointer receiver with another,
  3928  // the actual generated code overwrites the original receiver with the p.Inner pointer and
  3929  // then jumps to the M method expecting the *Inner receiver.
  3930  //
  3931  // During reflect.Value.Call, we create an argument frame and the associated data structures
  3932  // to describe it to the garbage collector, populate the frame, call reflect.call to
  3933  // run a function call using that frame, and then copy the results back out of the frame.
  3934  // The reflect.call function does a memmove of the frame structure onto the
  3935  // stack (to set up the inputs), runs the call, and the memmoves the stack back to
  3936  // the frame structure (to preserve the outputs).
  3937  //
  3938  // Originally reflect.call did not distinguish inputs from outputs: both memmoves
  3939  // were for the full stack frame. However, in the case where the called function was
  3940  // one of these wrappers, the rewritten receiver is almost certainly a different type
  3941  // than the original receiver. This is not a problem on the stack, where we use the
  3942  // program counter to determine the type information and understand that
  3943  // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
  3944  // memory word is now an *Inner. But in the statically typed argument frame created
  3945  // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
  3946  // off the stack into the frame will store an *Inner there, and then if a garbage collection
  3947  // happens to scan that argument frame before it is discarded, it will scan the *Inner
  3948  // memory as if it were an *Outer. If the two have different memory layouts, the
  3949  // collection will intepret the memory incorrectly.
  3950  //
  3951  // One such possible incorrect interpretation is to treat two arbitrary memory words
  3952  // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
  3953  // an interface requires dereferencing the itab word, the misinterpretation will try to
  3954  // deference Inner.P1, causing a crash during garbage collection.
  3955  //
  3956  // This came up in a real program in issue 7725.
  3957  
  3958  type Outer struct {
  3959  	*Inner
  3960  	R io.Reader
  3961  }
  3962  
  3963  type Inner struct {
  3964  	X  *Outer
  3965  	P1 uintptr
  3966  	P2 uintptr
  3967  }
  3968  
  3969  func (pi *Inner) M() {
  3970  	// Clear references to pi so that the only way the
  3971  	// garbage collection will find the pointer is in the
  3972  	// argument frame, typed as a *Outer.
  3973  	pi.X.Inner = nil
  3974  
  3975  	// Set up an interface value that will cause a crash.
  3976  	// P1 = 1 is a non-zero, so the interface looks non-nil.
  3977  	// P2 = pi ensures that the data word points into the
  3978  	// allocated heap; if not the collection skips the interface
  3979  	// value as irrelevant, without dereferencing P1.
  3980  	pi.P1 = 1
  3981  	pi.P2 = uintptr(unsafe.Pointer(pi))
  3982  }
  3983  
  3984  func TestCallMethodJump(t *testing.T) {
  3985  	// In reflect.Value.Call, trigger a garbage collection after reflect.call
  3986  	// returns but before the args frame has been discarded.
  3987  	// This is a little clumsy but makes the failure repeatable.
  3988  	*CallGC = true
  3989  
  3990  	p := &Outer{Inner: new(Inner)}
  3991  	p.Inner.X = p
  3992  	ValueOf(p).Method(0).Call(nil)
  3993  
  3994  	// Stop garbage collecting during reflect.call.
  3995  	*CallGC = false
  3996  }
  3997  
  3998  func TestMakeFuncStackCopy(t *testing.T) {
  3999  	target := func(in []Value) []Value {
  4000  		runtime.GC()
  4001  		useStack(16)
  4002  		return []Value{ValueOf(9)}
  4003  	}
  4004  
  4005  	var concrete func(*int, int) int
  4006  	fn := MakeFunc(ValueOf(concrete).Type(), target)
  4007  	ValueOf(&concrete).Elem().Set(fn)
  4008  	x := concrete(nil, 7)
  4009  	if x != 9 {
  4010  		t.Errorf("have %#q want 9", x)
  4011  	}
  4012  }
  4013  
  4014  // use about n KB of stack
  4015  func useStack(n int) {
  4016  	if n == 0 {
  4017  		return
  4018  	}
  4019  	var b [1024]byte // makes frame about 1KB
  4020  	useStack(n - 1 + int(b[99]))
  4021  }
  4022  
  4023  type Impl struct{}
  4024  
  4025  func (Impl) f() {}
  4026  
  4027  func TestValueString(t *testing.T) {
  4028  	rv := ValueOf(Impl{})
  4029  	if rv.String() != "<reflect_test.Impl Value>" {
  4030  		t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
  4031  	}
  4032  
  4033  	method := rv.Method(0)
  4034  	if method.String() != "<func() Value>" {
  4035  		t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
  4036  	}
  4037  }
  4038  
  4039  func TestInvalid(t *testing.T) {
  4040  	// Used to have inconsistency between IsValid() and Kind() != Invalid.
  4041  	type T struct{ v interface{} }
  4042  
  4043  	v := ValueOf(T{}).Field(0)
  4044  	if v.IsValid() != true || v.Kind() != Interface {
  4045  		t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
  4046  	}
  4047  	v = v.Elem()
  4048  	if v.IsValid() != false || v.Kind() != Invalid {
  4049  		t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
  4050  	}
  4051  }
  4052  
  4053  // Issue 8917.
  4054  func TestLargeGCProg(t *testing.T) {
  4055  	fv := ValueOf(func([256]*byte) {})
  4056  	fv.Call([]Value{ValueOf([256]*byte{})})
  4057  }