github.com/bgentry/go@v0.0.0-20150121062915-6cf5a733d54d/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  			select {
  1056  			case x := <-c:
  1057  				t.Errorf("TrySend failed but it did send %d", x)
  1058  			default:
  1059  			}
  1060  		} else {
  1061  			if i = <-c; i != 6 {
  1062  				t.Errorf("TrySend 6, recv %d", i)
  1063  			}
  1064  		}
  1065  
  1066  		// Close
  1067  		c <- 123
  1068  		cv.Close()
  1069  		if i, ok := cv.Recv(); i.Int() != 123 || !ok {
  1070  			t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
  1071  		}
  1072  		if i, ok := cv.Recv(); i.Int() != 0 || ok {
  1073  			t.Errorf("after close Recv %d, %t", i.Int(), ok)
  1074  		}
  1075  	}
  1076  
  1077  	// check creation of unbuffered channel
  1078  	var c chan int
  1079  	cv := MakeChan(TypeOf(c), 0)
  1080  	c = cv.Interface().(chan int)
  1081  	if cv.TrySend(ValueOf(7)) {
  1082  		t.Errorf("TrySend on sync chan succeeded")
  1083  	}
  1084  	if v, ok := cv.TryRecv(); v.IsValid() || ok {
  1085  		t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
  1086  	}
  1087  
  1088  	// len/cap
  1089  	cv = MakeChan(TypeOf(c), 10)
  1090  	c = cv.Interface().(chan int)
  1091  	for i := 0; i < 3; i++ {
  1092  		c <- i
  1093  	}
  1094  	if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
  1095  		t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
  1096  	}
  1097  }
  1098  
  1099  // caseInfo describes a single case in a select test.
  1100  type caseInfo struct {
  1101  	desc      string
  1102  	canSelect bool
  1103  	recv      Value
  1104  	closed    bool
  1105  	helper    func()
  1106  	panic     bool
  1107  }
  1108  
  1109  var allselect = flag.Bool("allselect", false, "exhaustive select test")
  1110  
  1111  func TestSelect(t *testing.T) {
  1112  	selectWatch.once.Do(func() { go selectWatcher() })
  1113  
  1114  	var x exhaustive
  1115  	nch := 0
  1116  	newop := func(n int, cap int) (ch, val Value) {
  1117  		nch++
  1118  		if nch%101%2 == 1 {
  1119  			c := make(chan int, cap)
  1120  			ch = ValueOf(c)
  1121  			val = ValueOf(n)
  1122  		} else {
  1123  			c := make(chan string, cap)
  1124  			ch = ValueOf(c)
  1125  			val = ValueOf(fmt.Sprint(n))
  1126  		}
  1127  		return
  1128  	}
  1129  
  1130  	for n := 0; x.Next(); n++ {
  1131  		if testing.Short() && n >= 1000 {
  1132  			break
  1133  		}
  1134  		if n >= 100000 && !*allselect {
  1135  			break
  1136  		}
  1137  		if n%100000 == 0 && testing.Verbose() {
  1138  			println("TestSelect", n)
  1139  		}
  1140  		var cases []SelectCase
  1141  		var info []caseInfo
  1142  
  1143  		// Ready send.
  1144  		if x.Maybe() {
  1145  			ch, val := newop(len(cases), 1)
  1146  			cases = append(cases, SelectCase{
  1147  				Dir:  SelectSend,
  1148  				Chan: ch,
  1149  				Send: val,
  1150  			})
  1151  			info = append(info, caseInfo{desc: "ready send", canSelect: true})
  1152  		}
  1153  
  1154  		// Ready recv.
  1155  		if x.Maybe() {
  1156  			ch, val := newop(len(cases), 1)
  1157  			ch.Send(val)
  1158  			cases = append(cases, SelectCase{
  1159  				Dir:  SelectRecv,
  1160  				Chan: ch,
  1161  			})
  1162  			info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
  1163  		}
  1164  
  1165  		// Blocking send.
  1166  		if x.Maybe() {
  1167  			ch, val := newop(len(cases), 0)
  1168  			cases = append(cases, SelectCase{
  1169  				Dir:  SelectSend,
  1170  				Chan: ch,
  1171  				Send: val,
  1172  			})
  1173  			// Let it execute?
  1174  			if x.Maybe() {
  1175  				f := func() { ch.Recv() }
  1176  				info = append(info, caseInfo{desc: "blocking send", helper: f})
  1177  			} else {
  1178  				info = append(info, caseInfo{desc: "blocking send"})
  1179  			}
  1180  		}
  1181  
  1182  		// Blocking recv.
  1183  		if x.Maybe() {
  1184  			ch, val := newop(len(cases), 0)
  1185  			cases = append(cases, SelectCase{
  1186  				Dir:  SelectRecv,
  1187  				Chan: ch,
  1188  			})
  1189  			// Let it execute?
  1190  			if x.Maybe() {
  1191  				f := func() { ch.Send(val) }
  1192  				info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
  1193  			} else {
  1194  				info = append(info, caseInfo{desc: "blocking recv"})
  1195  			}
  1196  		}
  1197  
  1198  		// Zero Chan send.
  1199  		if x.Maybe() {
  1200  			// Maybe include value to send.
  1201  			var val Value
  1202  			if x.Maybe() {
  1203  				val = ValueOf(100)
  1204  			}
  1205  			cases = append(cases, SelectCase{
  1206  				Dir:  SelectSend,
  1207  				Send: val,
  1208  			})
  1209  			info = append(info, caseInfo{desc: "zero Chan send"})
  1210  		}
  1211  
  1212  		// Zero Chan receive.
  1213  		if x.Maybe() {
  1214  			cases = append(cases, SelectCase{
  1215  				Dir: SelectRecv,
  1216  			})
  1217  			info = append(info, caseInfo{desc: "zero Chan recv"})
  1218  		}
  1219  
  1220  		// nil Chan send.
  1221  		if x.Maybe() {
  1222  			cases = append(cases, SelectCase{
  1223  				Dir:  SelectSend,
  1224  				Chan: ValueOf((chan int)(nil)),
  1225  				Send: ValueOf(101),
  1226  			})
  1227  			info = append(info, caseInfo{desc: "nil Chan send"})
  1228  		}
  1229  
  1230  		// nil Chan recv.
  1231  		if x.Maybe() {
  1232  			cases = append(cases, SelectCase{
  1233  				Dir:  SelectRecv,
  1234  				Chan: ValueOf((chan int)(nil)),
  1235  			})
  1236  			info = append(info, caseInfo{desc: "nil Chan recv"})
  1237  		}
  1238  
  1239  		// closed Chan send.
  1240  		if x.Maybe() {
  1241  			ch := make(chan int)
  1242  			close(ch)
  1243  			cases = append(cases, SelectCase{
  1244  				Dir:  SelectSend,
  1245  				Chan: ValueOf(ch),
  1246  				Send: ValueOf(101),
  1247  			})
  1248  			info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
  1249  		}
  1250  
  1251  		// closed Chan recv.
  1252  		if x.Maybe() {
  1253  			ch, val := newop(len(cases), 0)
  1254  			ch.Close()
  1255  			val = Zero(val.Type())
  1256  			cases = append(cases, SelectCase{
  1257  				Dir:  SelectRecv,
  1258  				Chan: ch,
  1259  			})
  1260  			info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
  1261  		}
  1262  
  1263  		var helper func() // goroutine to help the select complete
  1264  
  1265  		// Add default? Must be last case here, but will permute.
  1266  		// Add the default if the select would otherwise
  1267  		// block forever, and maybe add it anyway.
  1268  		numCanSelect := 0
  1269  		canProceed := false
  1270  		canBlock := true
  1271  		canPanic := false
  1272  		helpers := []int{}
  1273  		for i, c := range info {
  1274  			if c.canSelect {
  1275  				canProceed = true
  1276  				canBlock = false
  1277  				numCanSelect++
  1278  				if c.panic {
  1279  					canPanic = true
  1280  				}
  1281  			} else if c.helper != nil {
  1282  				canProceed = true
  1283  				helpers = append(helpers, i)
  1284  			}
  1285  		}
  1286  		if !canProceed || x.Maybe() {
  1287  			cases = append(cases, SelectCase{
  1288  				Dir: SelectDefault,
  1289  			})
  1290  			info = append(info, caseInfo{desc: "default", canSelect: canBlock})
  1291  			numCanSelect++
  1292  		} else if canBlock {
  1293  			// Select needs to communicate with another goroutine.
  1294  			cas := &info[helpers[x.Choose(len(helpers))]]
  1295  			helper = cas.helper
  1296  			cas.canSelect = true
  1297  			numCanSelect++
  1298  		}
  1299  
  1300  		// Permute cases and case info.
  1301  		// Doing too much here makes the exhaustive loop
  1302  		// too exhausting, so just do two swaps.
  1303  		for loop := 0; loop < 2; loop++ {
  1304  			i := x.Choose(len(cases))
  1305  			j := x.Choose(len(cases))
  1306  			cases[i], cases[j] = cases[j], cases[i]
  1307  			info[i], info[j] = info[j], info[i]
  1308  		}
  1309  
  1310  		if helper != nil {
  1311  			// We wait before kicking off a goroutine to satisfy a blocked select.
  1312  			// The pause needs to be big enough to let the select block before
  1313  			// we run the helper, but if we lose that race once in a while it's okay: the
  1314  			// select will just proceed immediately. Not a big deal.
  1315  			// For short tests we can grow [sic] the timeout a bit without fear of taking too long
  1316  			pause := 10 * time.Microsecond
  1317  			if testing.Short() {
  1318  				pause = 100 * time.Microsecond
  1319  			}
  1320  			time.AfterFunc(pause, helper)
  1321  		}
  1322  
  1323  		// Run select.
  1324  		i, recv, recvOK, panicErr := runSelect(cases, info)
  1325  		if panicErr != nil && !canPanic {
  1326  			t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
  1327  		}
  1328  		if panicErr == nil && canPanic && numCanSelect == 1 {
  1329  			t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
  1330  		}
  1331  		if panicErr != nil {
  1332  			continue
  1333  		}
  1334  
  1335  		cas := info[i]
  1336  		if !cas.canSelect {
  1337  			recvStr := ""
  1338  			if recv.IsValid() {
  1339  				recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
  1340  			}
  1341  			t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
  1342  			continue
  1343  		}
  1344  		if cas.panic {
  1345  			t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
  1346  			continue
  1347  		}
  1348  
  1349  		if cases[i].Dir == SelectRecv {
  1350  			if !recv.IsValid() {
  1351  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
  1352  			}
  1353  			if !cas.recv.IsValid() {
  1354  				t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
  1355  			}
  1356  			if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
  1357  				if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
  1358  					t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
  1359  				}
  1360  				t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
  1361  			}
  1362  		} else {
  1363  			if recv.IsValid() || recvOK {
  1364  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
  1365  			}
  1366  		}
  1367  	}
  1368  }
  1369  
  1370  // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
  1371  // If the selectWatcher notices that the select has been blocked for >1 second, it prints
  1372  // an error describing the select and panics the entire test binary.
  1373  var selectWatch struct {
  1374  	sync.Mutex
  1375  	once sync.Once
  1376  	now  time.Time
  1377  	info []caseInfo
  1378  }
  1379  
  1380  func selectWatcher() {
  1381  	for {
  1382  		time.Sleep(1 * time.Second)
  1383  		selectWatch.Lock()
  1384  		if selectWatch.info != nil && time.Since(selectWatch.now) > 1*time.Second {
  1385  			fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
  1386  			panic("select stuck")
  1387  		}
  1388  		selectWatch.Unlock()
  1389  	}
  1390  }
  1391  
  1392  // runSelect runs a single select test.
  1393  // It returns the values returned by Select but also returns
  1394  // a panic value if the Select panics.
  1395  func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
  1396  	defer func() {
  1397  		panicErr = recover()
  1398  
  1399  		selectWatch.Lock()
  1400  		selectWatch.info = nil
  1401  		selectWatch.Unlock()
  1402  	}()
  1403  
  1404  	selectWatch.Lock()
  1405  	selectWatch.now = time.Now()
  1406  	selectWatch.info = info
  1407  	selectWatch.Unlock()
  1408  
  1409  	chosen, recv, recvOK = Select(cases)
  1410  	return
  1411  }
  1412  
  1413  // fmtSelect formats the information about a single select test.
  1414  func fmtSelect(info []caseInfo) string {
  1415  	var buf bytes.Buffer
  1416  	fmt.Fprintf(&buf, "\nselect {\n")
  1417  	for i, cas := range info {
  1418  		fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
  1419  		if cas.recv.IsValid() {
  1420  			fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
  1421  		}
  1422  		if cas.canSelect {
  1423  			fmt.Fprintf(&buf, " canselect")
  1424  		}
  1425  		if cas.panic {
  1426  			fmt.Fprintf(&buf, " panic")
  1427  		}
  1428  		fmt.Fprintf(&buf, "\n")
  1429  	}
  1430  	fmt.Fprintf(&buf, "}")
  1431  	return buf.String()
  1432  }
  1433  
  1434  type two [2]uintptr
  1435  
  1436  // Difficult test for function call because of
  1437  // implicit padding between arguments.
  1438  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) {
  1439  	return b, c, d, e, f, g, h
  1440  }
  1441  
  1442  func TestFunc(t *testing.T) {
  1443  	ret := ValueOf(dummy).Call([]Value{
  1444  		ValueOf(byte(10)),
  1445  		ValueOf(20),
  1446  		ValueOf(byte(30)),
  1447  		ValueOf(two{40, 50}),
  1448  		ValueOf(byte(60)),
  1449  		ValueOf(float32(70)),
  1450  		ValueOf(byte(80)),
  1451  	})
  1452  	if len(ret) != 7 {
  1453  		t.Fatalf("Call returned %d values, want 7", len(ret))
  1454  	}
  1455  
  1456  	i := byte(ret[0].Uint())
  1457  	j := int(ret[1].Int())
  1458  	k := byte(ret[2].Uint())
  1459  	l := ret[3].Interface().(two)
  1460  	m := byte(ret[4].Uint())
  1461  	n := float32(ret[5].Float())
  1462  	o := byte(ret[6].Uint())
  1463  
  1464  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1465  		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)
  1466  	}
  1467  }
  1468  
  1469  type emptyStruct struct{}
  1470  
  1471  type nonEmptyStruct struct {
  1472  	member int
  1473  }
  1474  
  1475  func returnEmpty() emptyStruct {
  1476  	return emptyStruct{}
  1477  }
  1478  
  1479  func takesEmpty(e emptyStruct) {
  1480  }
  1481  
  1482  func returnNonEmpty(i int) nonEmptyStruct {
  1483  	return nonEmptyStruct{member: i}
  1484  }
  1485  
  1486  func takesNonEmpty(n nonEmptyStruct) int {
  1487  	return n.member
  1488  }
  1489  
  1490  func TestCallWithStruct(t *testing.T) {
  1491  	r := ValueOf(returnEmpty).Call(nil)
  1492  	if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
  1493  		t.Errorf("returning empty struct returned %#v instead", r)
  1494  	}
  1495  	r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
  1496  	if len(r) != 0 {
  1497  		t.Errorf("takesEmpty returned values: %#v", r)
  1498  	}
  1499  	r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
  1500  	if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
  1501  		t.Errorf("returnNonEmpty returned %#v", r)
  1502  	}
  1503  	r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
  1504  	if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
  1505  		t.Errorf("takesNonEmpty returned %#v", r)
  1506  	}
  1507  }
  1508  
  1509  func TestMakeFunc(t *testing.T) {
  1510  	f := dummy
  1511  	fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
  1512  	ValueOf(&f).Elem().Set(fv)
  1513  
  1514  	// Call g with small arguments so that there is
  1515  	// something predictable (and different from the
  1516  	// correct results) in those positions on the stack.
  1517  	g := dummy
  1518  	g(1, 2, 3, two{4, 5}, 6, 7, 8)
  1519  
  1520  	// Call constructed function f.
  1521  	i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
  1522  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1523  		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)
  1524  	}
  1525  }
  1526  
  1527  func TestMakeFuncInterface(t *testing.T) {
  1528  	fn := func(i int) int { return i }
  1529  	incr := func(in []Value) []Value {
  1530  		return []Value{ValueOf(int(in[0].Int() + 1))}
  1531  	}
  1532  	fv := MakeFunc(TypeOf(fn), incr)
  1533  	ValueOf(&fn).Elem().Set(fv)
  1534  	if r := fn(2); r != 3 {
  1535  		t.Errorf("Call returned %d, want 3", r)
  1536  	}
  1537  	if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
  1538  		t.Errorf("Call returned %d, want 15", r)
  1539  	}
  1540  	if r := fv.Interface().(func(int) int)(26); r != 27 {
  1541  		t.Errorf("Call returned %d, want 27", r)
  1542  	}
  1543  }
  1544  
  1545  func TestMakeFuncVariadic(t *testing.T) {
  1546  	// Test that variadic arguments are packed into a slice and passed as last arg
  1547  	fn := func(_ int, is ...int) []int { return nil }
  1548  	fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
  1549  	ValueOf(&fn).Elem().Set(fv)
  1550  
  1551  	r := fn(1, 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 = fn(1, []int{2, 3}...)
  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.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(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  	r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
  1567  	if r[0] != 2 || r[1] != 3 {
  1568  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1569  	}
  1570  
  1571  	f := fv.Interface().(func(int, ...int) []int)
  1572  
  1573  	r = f(1, 2, 3)
  1574  	if r[0] != 2 || r[1] != 3 {
  1575  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1576  	}
  1577  	r = f(1, []int{2, 3}...)
  1578  	if r[0] != 2 || r[1] != 3 {
  1579  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1580  	}
  1581  }
  1582  
  1583  type Point struct {
  1584  	x, y int
  1585  }
  1586  
  1587  // This will be index 0.
  1588  func (p Point) AnotherMethod(scale int) int {
  1589  	return -1
  1590  }
  1591  
  1592  // This will be index 1.
  1593  func (p Point) Dist(scale int) int {
  1594  	//println("Point.Dist", p.x, p.y, scale)
  1595  	return p.x*p.x*scale + p.y*p.y*scale
  1596  }
  1597  
  1598  // This will be index 2.
  1599  func (p Point) GCMethod(k int) int {
  1600  	runtime.GC()
  1601  	return k + p.x
  1602  }
  1603  
  1604  // This will be index 3.
  1605  func (p Point) TotalDist(points ...Point) int {
  1606  	tot := 0
  1607  	for _, q := range points {
  1608  		dx := q.x - p.x
  1609  		dy := q.y - p.y
  1610  		tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
  1611  
  1612  	}
  1613  	return tot
  1614  }
  1615  
  1616  func TestMethod(t *testing.T) {
  1617  	// Non-curried method of type.
  1618  	p := Point{3, 4}
  1619  	i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
  1620  	if i != 250 {
  1621  		t.Errorf("Type Method returned %d; want 250", i)
  1622  	}
  1623  
  1624  	m, ok := TypeOf(p).MethodByName("Dist")
  1625  	if !ok {
  1626  		t.Fatalf("method by name failed")
  1627  	}
  1628  	i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
  1629  	if i != 275 {
  1630  		t.Errorf("Type MethodByName returned %d; want 275", i)
  1631  	}
  1632  
  1633  	i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
  1634  	if i != 300 {
  1635  		t.Errorf("Pointer Type Method returned %d; want 300", i)
  1636  	}
  1637  
  1638  	m, ok = TypeOf(&p).MethodByName("Dist")
  1639  	if !ok {
  1640  		t.Fatalf("ptr method by name failed")
  1641  	}
  1642  	i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
  1643  	if i != 325 {
  1644  		t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
  1645  	}
  1646  
  1647  	// Curried method of value.
  1648  	tfunc := TypeOf((func(int) int)(nil))
  1649  	v := ValueOf(p).Method(1)
  1650  	if tt := v.Type(); tt != tfunc {
  1651  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1652  	}
  1653  	i = v.Call([]Value{ValueOf(14)})[0].Int()
  1654  	if i != 350 {
  1655  		t.Errorf("Value Method returned %d; want 350", i)
  1656  	}
  1657  	v = ValueOf(p).MethodByName("Dist")
  1658  	if tt := v.Type(); tt != tfunc {
  1659  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  1660  	}
  1661  	i = v.Call([]Value{ValueOf(15)})[0].Int()
  1662  	if i != 375 {
  1663  		t.Errorf("Value MethodByName returned %d; want 375", i)
  1664  	}
  1665  
  1666  	// Curried method of pointer.
  1667  	v = ValueOf(&p).Method(1)
  1668  	if tt := v.Type(); tt != tfunc {
  1669  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  1670  	}
  1671  	i = v.Call([]Value{ValueOf(16)})[0].Int()
  1672  	if i != 400 {
  1673  		t.Errorf("Pointer Value Method returned %d; want 400", i)
  1674  	}
  1675  	v = ValueOf(&p).MethodByName("Dist")
  1676  	if tt := v.Type(); tt != tfunc {
  1677  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1678  	}
  1679  	i = v.Call([]Value{ValueOf(17)})[0].Int()
  1680  	if i != 425 {
  1681  		t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
  1682  	}
  1683  
  1684  	// Curried method of interface value.
  1685  	// Have to wrap interface value in a struct to get at it.
  1686  	// Passing it to ValueOf directly would
  1687  	// access the underlying Point, not the interface.
  1688  	var x interface {
  1689  		Dist(int) int
  1690  	} = p
  1691  	pv := ValueOf(&x).Elem()
  1692  	v = pv.Method(0)
  1693  	if tt := v.Type(); tt != tfunc {
  1694  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  1695  	}
  1696  	i = v.Call([]Value{ValueOf(18)})[0].Int()
  1697  	if i != 450 {
  1698  		t.Errorf("Interface Method returned %d; want 450", i)
  1699  	}
  1700  	v = pv.MethodByName("Dist")
  1701  	if tt := v.Type(); tt != tfunc {
  1702  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  1703  	}
  1704  	i = v.Call([]Value{ValueOf(19)})[0].Int()
  1705  	if i != 475 {
  1706  		t.Errorf("Interface MethodByName returned %d; want 475", i)
  1707  	}
  1708  }
  1709  
  1710  func TestMethodValue(t *testing.T) {
  1711  	p := Point{3, 4}
  1712  	var i int64
  1713  
  1714  	// Curried method of value.
  1715  	tfunc := TypeOf((func(int) int)(nil))
  1716  	v := ValueOf(p).Method(1)
  1717  	if tt := v.Type(); tt != tfunc {
  1718  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1719  	}
  1720  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
  1721  	if i != 250 {
  1722  		t.Errorf("Value Method returned %d; want 250", i)
  1723  	}
  1724  	v = ValueOf(p).MethodByName("Dist")
  1725  	if tt := v.Type(); tt != tfunc {
  1726  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  1727  	}
  1728  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
  1729  	if i != 275 {
  1730  		t.Errorf("Value MethodByName returned %d; want 275", i)
  1731  	}
  1732  
  1733  	// Curried method of pointer.
  1734  	v = ValueOf(&p).Method(1)
  1735  	if tt := v.Type(); tt != tfunc {
  1736  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  1737  	}
  1738  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
  1739  	if i != 300 {
  1740  		t.Errorf("Pointer Value Method returned %d; want 300", i)
  1741  	}
  1742  	v = ValueOf(&p).MethodByName("Dist")
  1743  	if tt := v.Type(); tt != tfunc {
  1744  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1745  	}
  1746  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
  1747  	if i != 325 {
  1748  		t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
  1749  	}
  1750  
  1751  	// Curried method of pointer to pointer.
  1752  	pp := &p
  1753  	v = ValueOf(&pp).Elem().Method(1)
  1754  	if tt := v.Type(); tt != tfunc {
  1755  		t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
  1756  	}
  1757  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
  1758  	if i != 350 {
  1759  		t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
  1760  	}
  1761  	v = ValueOf(&pp).Elem().MethodByName("Dist")
  1762  	if tt := v.Type(); tt != tfunc {
  1763  		t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1764  	}
  1765  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
  1766  	if i != 375 {
  1767  		t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
  1768  	}
  1769  
  1770  	// Curried method of interface value.
  1771  	// Have to wrap interface value in a struct to get at it.
  1772  	// Passing it to ValueOf directly would
  1773  	// access the underlying Point, not the interface.
  1774  	var s = struct {
  1775  		X interface {
  1776  			Dist(int) int
  1777  		}
  1778  	}{p}
  1779  	pv := ValueOf(s).Field(0)
  1780  	v = pv.Method(0)
  1781  	if tt := v.Type(); tt != tfunc {
  1782  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  1783  	}
  1784  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
  1785  	if i != 400 {
  1786  		t.Errorf("Interface Method returned %d; want 400", i)
  1787  	}
  1788  	v = pv.MethodByName("Dist")
  1789  	if tt := v.Type(); tt != tfunc {
  1790  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  1791  	}
  1792  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
  1793  	if i != 425 {
  1794  		t.Errorf("Interface MethodByName returned %d; want 425", i)
  1795  	}
  1796  }
  1797  
  1798  func TestVariadicMethodValue(t *testing.T) {
  1799  	p := Point{3, 4}
  1800  	points := []Point{{20, 21}, {22, 23}, {24, 25}}
  1801  	want := int64(p.TotalDist(points[0], points[1], points[2]))
  1802  
  1803  	// Curried method of value.
  1804  	tfunc := TypeOf((func(...Point) int)(nil))
  1805  	v := ValueOf(p).Method(3)
  1806  	if tt := v.Type(); tt != tfunc {
  1807  		t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
  1808  	}
  1809  	i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
  1810  	if i != want {
  1811  		t.Errorf("Variadic Method returned %d; want %d", i, want)
  1812  	}
  1813  	i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
  1814  	if i != want {
  1815  		t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
  1816  	}
  1817  
  1818  	f := v.Interface().(func(...Point) int)
  1819  	i = int64(f(points[0], points[1], points[2]))
  1820  	if i != want {
  1821  		t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
  1822  	}
  1823  	i = int64(f(points...))
  1824  	if i != want {
  1825  		t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
  1826  	}
  1827  }
  1828  
  1829  // Reflect version of $GOROOT/test/method5.go
  1830  
  1831  // Concrete types implementing M method.
  1832  // Smaller than a word, word-sized, larger than a word.
  1833  // Value and pointer receivers.
  1834  
  1835  type Tinter interface {
  1836  	M(int, byte) (byte, int)
  1837  }
  1838  
  1839  type Tsmallv byte
  1840  
  1841  func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  1842  
  1843  type Tsmallp byte
  1844  
  1845  func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  1846  
  1847  type Twordv uintptr
  1848  
  1849  func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  1850  
  1851  type Twordp uintptr
  1852  
  1853  func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  1854  
  1855  type Tbigv [2]uintptr
  1856  
  1857  func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  1858  
  1859  type Tbigp [2]uintptr
  1860  
  1861  func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  1862  
  1863  // Again, with an unexported method.
  1864  
  1865  type tsmallv byte
  1866  
  1867  func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
  1868  
  1869  type tsmallp byte
  1870  
  1871  func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
  1872  
  1873  type twordv uintptr
  1874  
  1875  func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
  1876  
  1877  type twordp uintptr
  1878  
  1879  func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
  1880  
  1881  type tbigv [2]uintptr
  1882  
  1883  func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  1884  
  1885  type tbigp [2]uintptr
  1886  
  1887  func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  1888  
  1889  type tinter interface {
  1890  	m(int, byte) (byte, int)
  1891  }
  1892  
  1893  // Embedding via pointer.
  1894  
  1895  type Tm1 struct {
  1896  	Tm2
  1897  }
  1898  
  1899  type Tm2 struct {
  1900  	*Tm3
  1901  }
  1902  
  1903  type Tm3 struct {
  1904  	*Tm4
  1905  }
  1906  
  1907  type Tm4 struct {
  1908  }
  1909  
  1910  func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
  1911  
  1912  func TestMethod5(t *testing.T) {
  1913  	CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
  1914  		b, x := f(1000, 99)
  1915  		if b != 99 || x != 1000+inc {
  1916  			t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  1917  		}
  1918  	}
  1919  
  1920  	CheckV := func(name string, i Value, inc int) {
  1921  		bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
  1922  		b := bx[0].Interface()
  1923  		x := bx[1].Interface()
  1924  		if b != byte(99) || x != 1000+inc {
  1925  			t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  1926  		}
  1927  
  1928  		CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
  1929  	}
  1930  
  1931  	var TinterType = TypeOf(new(Tinter)).Elem()
  1932  	var tinterType = TypeOf(new(tinter)).Elem()
  1933  
  1934  	CheckI := func(name string, i interface{}, inc int) {
  1935  		v := ValueOf(i)
  1936  		CheckV(name, v, inc)
  1937  		CheckV("(i="+name+")", v.Convert(TinterType), inc)
  1938  	}
  1939  
  1940  	sv := Tsmallv(1)
  1941  	CheckI("sv", sv, 1)
  1942  	CheckI("&sv", &sv, 1)
  1943  
  1944  	sp := Tsmallp(2)
  1945  	CheckI("&sp", &sp, 2)
  1946  
  1947  	wv := Twordv(3)
  1948  	CheckI("wv", wv, 3)
  1949  	CheckI("&wv", &wv, 3)
  1950  
  1951  	wp := Twordp(4)
  1952  	CheckI("&wp", &wp, 4)
  1953  
  1954  	bv := Tbigv([2]uintptr{5, 6})
  1955  	CheckI("bv", bv, 11)
  1956  	CheckI("&bv", &bv, 11)
  1957  
  1958  	bp := Tbigp([2]uintptr{7, 8})
  1959  	CheckI("&bp", &bp, 15)
  1960  
  1961  	t4 := Tm4{}
  1962  	t3 := Tm3{&t4}
  1963  	t2 := Tm2{&t3}
  1964  	t1 := Tm1{t2}
  1965  	CheckI("t4", t4, 40)
  1966  	CheckI("&t4", &t4, 40)
  1967  	CheckI("t3", t3, 40)
  1968  	CheckI("&t3", &t3, 40)
  1969  	CheckI("t2", t2, 40)
  1970  	CheckI("&t2", &t2, 40)
  1971  	CheckI("t1", t1, 40)
  1972  	CheckI("&t1", &t1, 40)
  1973  
  1974  	methodShouldPanic := func(name string, i interface{}) {
  1975  		v := ValueOf(i)
  1976  		m := v.Method(0)
  1977  		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
  1978  		shouldPanic(func() { m.Interface() })
  1979  
  1980  		v = v.Convert(tinterType)
  1981  		m = v.Method(0)
  1982  		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
  1983  		shouldPanic(func() { m.Interface() })
  1984  	}
  1985  
  1986  	_sv := tsmallv(1)
  1987  	methodShouldPanic("_sv", _sv)
  1988  	methodShouldPanic("&_sv", &_sv)
  1989  
  1990  	_sp := tsmallp(2)
  1991  	methodShouldPanic("&_sp", &_sp)
  1992  
  1993  	_wv := twordv(3)
  1994  	methodShouldPanic("_wv", _wv)
  1995  	methodShouldPanic("&_wv", &_wv)
  1996  
  1997  	_wp := twordp(4)
  1998  	methodShouldPanic("&_wp", &_wp)
  1999  
  2000  	_bv := tbigv([2]uintptr{5, 6})
  2001  	methodShouldPanic("_bv", _bv)
  2002  	methodShouldPanic("&_bv", &_bv)
  2003  
  2004  	_bp := tbigp([2]uintptr{7, 8})
  2005  	methodShouldPanic("&_bp", &_bp)
  2006  
  2007  	var tnil Tinter
  2008  	vnil := ValueOf(&tnil).Elem()
  2009  	shouldPanic(func() { vnil.Method(0) })
  2010  }
  2011  
  2012  func TestInterfaceSet(t *testing.T) {
  2013  	p := &Point{3, 4}
  2014  
  2015  	var s struct {
  2016  		I interface{}
  2017  		P interface {
  2018  			Dist(int) int
  2019  		}
  2020  	}
  2021  	sv := ValueOf(&s).Elem()
  2022  	sv.Field(0).Set(ValueOf(p))
  2023  	if q := s.I.(*Point); q != p {
  2024  		t.Errorf("i: have %p want %p", q, p)
  2025  	}
  2026  
  2027  	pv := sv.Field(1)
  2028  	pv.Set(ValueOf(p))
  2029  	if q := s.P.(*Point); q != p {
  2030  		t.Errorf("i: have %p want %p", q, p)
  2031  	}
  2032  
  2033  	i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
  2034  	if i != 250 {
  2035  		t.Errorf("Interface Method returned %d; want 250", i)
  2036  	}
  2037  }
  2038  
  2039  type T1 struct {
  2040  	a string
  2041  	int
  2042  }
  2043  
  2044  func TestAnonymousFields(t *testing.T) {
  2045  	var field StructField
  2046  	var ok bool
  2047  	var t1 T1
  2048  	type1 := TypeOf(t1)
  2049  	if field, ok = type1.FieldByName("int"); !ok {
  2050  		t.Fatal("no field 'int'")
  2051  	}
  2052  	if field.Index[0] != 1 {
  2053  		t.Error("field index should be 1; is", field.Index)
  2054  	}
  2055  }
  2056  
  2057  type FTest struct {
  2058  	s     interface{}
  2059  	name  string
  2060  	index []int
  2061  	value int
  2062  }
  2063  
  2064  type D1 struct {
  2065  	d int
  2066  }
  2067  type D2 struct {
  2068  	d int
  2069  }
  2070  
  2071  type S0 struct {
  2072  	A, B, C int
  2073  	D1
  2074  	D2
  2075  }
  2076  
  2077  type S1 struct {
  2078  	B int
  2079  	S0
  2080  }
  2081  
  2082  type S2 struct {
  2083  	A int
  2084  	*S1
  2085  }
  2086  
  2087  type S1x struct {
  2088  	S1
  2089  }
  2090  
  2091  type S1y struct {
  2092  	S1
  2093  }
  2094  
  2095  type S3 struct {
  2096  	S1x
  2097  	S2
  2098  	D, E int
  2099  	*S1y
  2100  }
  2101  
  2102  type S4 struct {
  2103  	*S4
  2104  	A int
  2105  }
  2106  
  2107  // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
  2108  type S5 struct {
  2109  	S6
  2110  	S7
  2111  	S8
  2112  }
  2113  
  2114  type S6 struct {
  2115  	X int
  2116  }
  2117  
  2118  type S7 S6
  2119  
  2120  type S8 struct {
  2121  	S9
  2122  }
  2123  
  2124  type S9 struct {
  2125  	X int
  2126  	Y int
  2127  }
  2128  
  2129  // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
  2130  type S10 struct {
  2131  	S11
  2132  	S12
  2133  	S13
  2134  }
  2135  
  2136  type S11 struct {
  2137  	S6
  2138  }
  2139  
  2140  type S12 struct {
  2141  	S6
  2142  }
  2143  
  2144  type S13 struct {
  2145  	S8
  2146  }
  2147  
  2148  // The X in S15.S11.S1 and S16.S11.S1 annihilate.
  2149  type S14 struct {
  2150  	S15
  2151  	S16
  2152  }
  2153  
  2154  type S15 struct {
  2155  	S11
  2156  }
  2157  
  2158  type S16 struct {
  2159  	S11
  2160  }
  2161  
  2162  var fieldTests = []FTest{
  2163  	{struct{}{}, "", nil, 0},
  2164  	{struct{}{}, "Foo", nil, 0},
  2165  	{S0{A: 'a'}, "A", []int{0}, 'a'},
  2166  	{S0{}, "D", nil, 0},
  2167  	{S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
  2168  	{S1{B: 'b'}, "B", []int{0}, 'b'},
  2169  	{S1{}, "S0", []int{1}, 0},
  2170  	{S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
  2171  	{S2{A: 'a'}, "A", []int{0}, 'a'},
  2172  	{S2{}, "S1", []int{1}, 0},
  2173  	{S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
  2174  	{S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
  2175  	{S2{}, "D", nil, 0},
  2176  	{S3{}, "S1", nil, 0},
  2177  	{S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
  2178  	{S3{}, "B", nil, 0},
  2179  	{S3{D: 'd'}, "D", []int{2}, 0},
  2180  	{S3{E: 'e'}, "E", []int{3}, 'e'},
  2181  	{S4{A: 'a'}, "A", []int{1}, 'a'},
  2182  	{S4{}, "B", nil, 0},
  2183  	{S5{}, "X", nil, 0},
  2184  	{S5{}, "Y", []int{2, 0, 1}, 0},
  2185  	{S10{}, "X", nil, 0},
  2186  	{S10{}, "Y", []int{2, 0, 0, 1}, 0},
  2187  	{S14{}, "X", nil, 0},
  2188  }
  2189  
  2190  func TestFieldByIndex(t *testing.T) {
  2191  	for _, test := range fieldTests {
  2192  		s := TypeOf(test.s)
  2193  		f := s.FieldByIndex(test.index)
  2194  		if f.Name != "" {
  2195  			if test.index != nil {
  2196  				if f.Name != test.name {
  2197  					t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
  2198  				}
  2199  			} else {
  2200  				t.Errorf("%s.%s found", s.Name(), f.Name)
  2201  			}
  2202  		} else if len(test.index) > 0 {
  2203  			t.Errorf("%s.%s not found", s.Name(), test.name)
  2204  		}
  2205  
  2206  		if test.value != 0 {
  2207  			v := ValueOf(test.s).FieldByIndex(test.index)
  2208  			if v.IsValid() {
  2209  				if x, ok := v.Interface().(int); ok {
  2210  					if x != test.value {
  2211  						t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
  2212  					}
  2213  				} else {
  2214  					t.Errorf("%s%v value not an int", s.Name(), test.index)
  2215  				}
  2216  			} else {
  2217  				t.Errorf("%s%v value not found", s.Name(), test.index)
  2218  			}
  2219  		}
  2220  	}
  2221  }
  2222  
  2223  func TestFieldByName(t *testing.T) {
  2224  	for _, test := range fieldTests {
  2225  		s := TypeOf(test.s)
  2226  		f, found := s.FieldByName(test.name)
  2227  		if found {
  2228  			if test.index != nil {
  2229  				// Verify field depth and index.
  2230  				if len(f.Index) != len(test.index) {
  2231  					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)
  2232  				} else {
  2233  					for i, x := range f.Index {
  2234  						if x != test.index[i] {
  2235  							t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
  2236  						}
  2237  					}
  2238  				}
  2239  			} else {
  2240  				t.Errorf("%s.%s found", s.Name(), f.Name)
  2241  			}
  2242  		} else if len(test.index) > 0 {
  2243  			t.Errorf("%s.%s not found", s.Name(), test.name)
  2244  		}
  2245  
  2246  		if test.value != 0 {
  2247  			v := ValueOf(test.s).FieldByName(test.name)
  2248  			if v.IsValid() {
  2249  				if x, ok := v.Interface().(int); ok {
  2250  					if x != test.value {
  2251  						t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
  2252  					}
  2253  				} else {
  2254  					t.Errorf("%s.%s value not an int", s.Name(), test.name)
  2255  				}
  2256  			} else {
  2257  				t.Errorf("%s.%s value not found", s.Name(), test.name)
  2258  			}
  2259  		}
  2260  	}
  2261  }
  2262  
  2263  func TestImportPath(t *testing.T) {
  2264  	tests := []struct {
  2265  		t    Type
  2266  		path string
  2267  	}{
  2268  		{TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
  2269  		{TypeOf(int(0)), ""},
  2270  		{TypeOf(int8(0)), ""},
  2271  		{TypeOf(int16(0)), ""},
  2272  		{TypeOf(int32(0)), ""},
  2273  		{TypeOf(int64(0)), ""},
  2274  		{TypeOf(uint(0)), ""},
  2275  		{TypeOf(uint8(0)), ""},
  2276  		{TypeOf(uint16(0)), ""},
  2277  		{TypeOf(uint32(0)), ""},
  2278  		{TypeOf(uint64(0)), ""},
  2279  		{TypeOf(uintptr(0)), ""},
  2280  		{TypeOf(float32(0)), ""},
  2281  		{TypeOf(float64(0)), ""},
  2282  		{TypeOf(complex64(0)), ""},
  2283  		{TypeOf(complex128(0)), ""},
  2284  		{TypeOf(byte(0)), ""},
  2285  		{TypeOf(rune(0)), ""},
  2286  		{TypeOf([]byte(nil)), ""},
  2287  		{TypeOf([]rune(nil)), ""},
  2288  		{TypeOf(string("")), ""},
  2289  		{TypeOf((*interface{})(nil)).Elem(), ""},
  2290  		{TypeOf((*byte)(nil)), ""},
  2291  		{TypeOf((*rune)(nil)), ""},
  2292  		{TypeOf((*int64)(nil)), ""},
  2293  		{TypeOf(map[string]int{}), ""},
  2294  		{TypeOf((*error)(nil)).Elem(), ""},
  2295  	}
  2296  	for _, test := range tests {
  2297  		if path := test.t.PkgPath(); path != test.path {
  2298  			t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
  2299  		}
  2300  	}
  2301  }
  2302  
  2303  func TestVariadicType(t *testing.T) {
  2304  	// Test example from Type documentation.
  2305  	var f func(x int, y ...float64)
  2306  	typ := TypeOf(f)
  2307  	if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
  2308  		sl := typ.In(1)
  2309  		if sl.Kind() == Slice {
  2310  			if sl.Elem() == TypeOf(0.0) {
  2311  				// ok
  2312  				return
  2313  			}
  2314  		}
  2315  	}
  2316  
  2317  	// Failed
  2318  	t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
  2319  	s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
  2320  	for i := 0; i < typ.NumIn(); i++ {
  2321  		s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
  2322  	}
  2323  	t.Error(s)
  2324  }
  2325  
  2326  type inner struct {
  2327  	x int
  2328  }
  2329  
  2330  type outer struct {
  2331  	y int
  2332  	inner
  2333  }
  2334  
  2335  func (*inner) m() {}
  2336  func (*outer) m() {}
  2337  
  2338  func TestNestedMethods(t *testing.T) {
  2339  	typ := TypeOf((*outer)(nil))
  2340  	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
  2341  		t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
  2342  		for i := 0; i < typ.NumMethod(); i++ {
  2343  			m := typ.Method(i)
  2344  			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2345  		}
  2346  	}
  2347  }
  2348  
  2349  type InnerInt struct {
  2350  	X int
  2351  }
  2352  
  2353  type OuterInt struct {
  2354  	Y int
  2355  	InnerInt
  2356  }
  2357  
  2358  func (i *InnerInt) M() int {
  2359  	return i.X
  2360  }
  2361  
  2362  func TestEmbeddedMethods(t *testing.T) {
  2363  	typ := TypeOf((*OuterInt)(nil))
  2364  	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
  2365  		t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
  2366  		for i := 0; i < typ.NumMethod(); i++ {
  2367  			m := typ.Method(i)
  2368  			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2369  		}
  2370  	}
  2371  
  2372  	i := &InnerInt{3}
  2373  	if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
  2374  		t.Errorf("i.M() = %d, want 3", v)
  2375  	}
  2376  
  2377  	o := &OuterInt{1, InnerInt{2}}
  2378  	if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
  2379  		t.Errorf("i.M() = %d, want 2", v)
  2380  	}
  2381  
  2382  	f := (*OuterInt).M
  2383  	if v := f(o); v != 2 {
  2384  		t.Errorf("f(o) = %d, want 2", v)
  2385  	}
  2386  }
  2387  
  2388  func TestPtrTo(t *testing.T) {
  2389  	var i int
  2390  
  2391  	typ := TypeOf(i)
  2392  	for i = 0; i < 100; i++ {
  2393  		typ = PtrTo(typ)
  2394  	}
  2395  	for i = 0; i < 100; i++ {
  2396  		typ = typ.Elem()
  2397  	}
  2398  	if typ != TypeOf(i) {
  2399  		t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
  2400  	}
  2401  }
  2402  
  2403  func TestPtrToGC(t *testing.T) {
  2404  	type T *uintptr
  2405  	tt := TypeOf(T(nil))
  2406  	pt := PtrTo(tt)
  2407  	const n = 100
  2408  	var x []interface{}
  2409  	for i := 0; i < n; i++ {
  2410  		v := New(pt)
  2411  		p := new(*uintptr)
  2412  		*p = new(uintptr)
  2413  		**p = uintptr(i)
  2414  		v.Elem().Set(ValueOf(p).Convert(pt))
  2415  		x = append(x, v.Interface())
  2416  	}
  2417  	runtime.GC()
  2418  
  2419  	for i, xi := range x {
  2420  		k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
  2421  		if k != uintptr(i) {
  2422  			t.Errorf("lost x[%d] = %d, want %d", i, k, i)
  2423  		}
  2424  	}
  2425  }
  2426  
  2427  func TestAddr(t *testing.T) {
  2428  	var p struct {
  2429  		X, Y int
  2430  	}
  2431  
  2432  	v := ValueOf(&p)
  2433  	v = v.Elem()
  2434  	v = v.Addr()
  2435  	v = v.Elem()
  2436  	v = v.Field(0)
  2437  	v.SetInt(2)
  2438  	if p.X != 2 {
  2439  		t.Errorf("Addr.Elem.Set failed to set value")
  2440  	}
  2441  
  2442  	// Again but take address of the ValueOf value.
  2443  	// Exercises generation of PtrTypes not present in the binary.
  2444  	q := &p
  2445  	v = ValueOf(&q).Elem()
  2446  	v = v.Addr()
  2447  	v = v.Elem()
  2448  	v = v.Elem()
  2449  	v = v.Addr()
  2450  	v = v.Elem()
  2451  	v = v.Field(0)
  2452  	v.SetInt(3)
  2453  	if p.X != 3 {
  2454  		t.Errorf("Addr.Elem.Set failed to set value")
  2455  	}
  2456  
  2457  	// Starting without pointer we should get changed value
  2458  	// in interface.
  2459  	qq := p
  2460  	v = ValueOf(&qq).Elem()
  2461  	v0 := v
  2462  	v = v.Addr()
  2463  	v = v.Elem()
  2464  	v = v.Field(0)
  2465  	v.SetInt(4)
  2466  	if p.X != 3 { // should be unchanged from last time
  2467  		t.Errorf("somehow value Set changed original p")
  2468  	}
  2469  	p = v0.Interface().(struct {
  2470  		X, Y int
  2471  	})
  2472  	if p.X != 4 {
  2473  		t.Errorf("Addr.Elem.Set valued to set value in top value")
  2474  	}
  2475  
  2476  	// Verify that taking the address of a type gives us a pointer
  2477  	// which we can convert back using the usual interface
  2478  	// notation.
  2479  	var s struct {
  2480  		B *bool
  2481  	}
  2482  	ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
  2483  	*(ps.(**bool)) = new(bool)
  2484  	if s.B == nil {
  2485  		t.Errorf("Addr.Interface direct assignment failed")
  2486  	}
  2487  }
  2488  
  2489  func noAlloc(t *testing.T, n int, f func(int)) {
  2490  	if testing.Short() {
  2491  		t.Skip("skipping malloc count in short mode")
  2492  	}
  2493  	if runtime.GOMAXPROCS(0) > 1 {
  2494  		t.Skip("skipping; GOMAXPROCS>1")
  2495  	}
  2496  	i := -1
  2497  	allocs := testing.AllocsPerRun(n, func() {
  2498  		f(i)
  2499  		i++
  2500  	})
  2501  	if allocs > 0 {
  2502  		t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
  2503  	}
  2504  }
  2505  
  2506  func TestAllocations(t *testing.T) {
  2507  	noAlloc(t, 100, func(j int) {
  2508  		var i interface{}
  2509  		var v Value
  2510  
  2511  		// We can uncomment this when compiler escape analysis
  2512  		// is good enough to see that the integer assigned to i
  2513  		// does not escape and therefore need not be allocated.
  2514  		//
  2515  		// i = 42 + j
  2516  		// v = ValueOf(i)
  2517  		// if int(v.Int()) != 42+j {
  2518  		// 	panic("wrong int")
  2519  		// }
  2520  
  2521  		i = func(j int) int { return j }
  2522  		v = ValueOf(i)
  2523  		if v.Interface().(func(int) int)(j) != j {
  2524  			panic("wrong result")
  2525  		}
  2526  	})
  2527  }
  2528  
  2529  func TestSmallNegativeInt(t *testing.T) {
  2530  	i := int16(-1)
  2531  	v := ValueOf(i)
  2532  	if v.Int() != -1 {
  2533  		t.Errorf("int16(-1).Int() returned %v", v.Int())
  2534  	}
  2535  }
  2536  
  2537  func TestIndex(t *testing.T) {
  2538  	xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
  2539  	v := ValueOf(xs).Index(3).Interface().(byte)
  2540  	if v != xs[3] {
  2541  		t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
  2542  	}
  2543  	xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
  2544  	v = ValueOf(xa).Index(2).Interface().(byte)
  2545  	if v != xa[2] {
  2546  		t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
  2547  	}
  2548  	s := "0123456789"
  2549  	v = ValueOf(s).Index(3).Interface().(byte)
  2550  	if v != s[3] {
  2551  		t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
  2552  	}
  2553  }
  2554  
  2555  func TestSlice(t *testing.T) {
  2556  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2557  	v := ValueOf(xs).Slice(3, 5).Interface().([]int)
  2558  	if len(v) != 2 {
  2559  		t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
  2560  	}
  2561  	if cap(v) != 5 {
  2562  		t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
  2563  	}
  2564  	if !DeepEqual(v[0:5], xs[3:]) {
  2565  		t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
  2566  	}
  2567  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2568  	v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
  2569  	if len(v) != 3 {
  2570  		t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
  2571  	}
  2572  	if cap(v) != 6 {
  2573  		t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
  2574  	}
  2575  	if !DeepEqual(v[0:6], xa[2:]) {
  2576  		t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
  2577  	}
  2578  	s := "0123456789"
  2579  	vs := ValueOf(s).Slice(3, 5).Interface().(string)
  2580  	if vs != s[3:5] {
  2581  		t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
  2582  	}
  2583  
  2584  	rv := ValueOf(&xs).Elem()
  2585  	rv = rv.Slice(3, 4)
  2586  	ptr2 := rv.Pointer()
  2587  	rv = rv.Slice(5, 5)
  2588  	ptr3 := rv.Pointer()
  2589  	if ptr3 != ptr2 {
  2590  		t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
  2591  	}
  2592  }
  2593  
  2594  func TestSlice3(t *testing.T) {
  2595  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2596  	v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
  2597  	if len(v) != 2 {
  2598  		t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
  2599  	}
  2600  	if cap(v) != 4 {
  2601  		t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
  2602  	}
  2603  	if !DeepEqual(v[0:4], xs[3:7:7]) {
  2604  		t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
  2605  	}
  2606  	rv := ValueOf(&xs).Elem()
  2607  	shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2608  	shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2609  	shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2610  
  2611  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2612  	v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
  2613  	if len(v) != 3 {
  2614  		t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
  2615  	}
  2616  	if cap(v) != 4 {
  2617  		t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
  2618  	}
  2619  	if !DeepEqual(v[0:4], xa[2:6:6]) {
  2620  		t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
  2621  	}
  2622  	rv = ValueOf(&xa).Elem()
  2623  	shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2624  	shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2625  	shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2626  
  2627  	s := "hello world"
  2628  	rv = ValueOf(&s).Elem()
  2629  	shouldPanic(func() { rv.Slice3(1, 2, 3) })
  2630  
  2631  	rv = ValueOf(&xs).Elem()
  2632  	rv = rv.Slice3(3, 5, 7)
  2633  	ptr2 := rv.Pointer()
  2634  	rv = rv.Slice3(4, 4, 4)
  2635  	ptr3 := rv.Pointer()
  2636  	if ptr3 != ptr2 {
  2637  		t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
  2638  	}
  2639  }
  2640  
  2641  func TestSetLenCap(t *testing.T) {
  2642  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2643  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2644  
  2645  	vs := ValueOf(&xs).Elem()
  2646  	shouldPanic(func() { vs.SetLen(10) })
  2647  	shouldPanic(func() { vs.SetCap(10) })
  2648  	shouldPanic(func() { vs.SetLen(-1) })
  2649  	shouldPanic(func() { vs.SetCap(-1) })
  2650  	shouldPanic(func() { vs.SetCap(6) }) // smaller than len
  2651  	vs.SetLen(5)
  2652  	if len(xs) != 5 || cap(xs) != 8 {
  2653  		t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
  2654  	}
  2655  	vs.SetCap(6)
  2656  	if len(xs) != 5 || cap(xs) != 6 {
  2657  		t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
  2658  	}
  2659  	vs.SetCap(5)
  2660  	if len(xs) != 5 || cap(xs) != 5 {
  2661  		t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
  2662  	}
  2663  	shouldPanic(func() { vs.SetCap(4) }) // smaller than len
  2664  	shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
  2665  
  2666  	va := ValueOf(&xa).Elem()
  2667  	shouldPanic(func() { va.SetLen(8) })
  2668  	shouldPanic(func() { va.SetCap(8) })
  2669  }
  2670  
  2671  func TestVariadic(t *testing.T) {
  2672  	var b bytes.Buffer
  2673  	V := ValueOf
  2674  
  2675  	b.Reset()
  2676  	V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
  2677  	if b.String() != "hello, 42 world" {
  2678  		t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
  2679  	}
  2680  
  2681  	b.Reset()
  2682  	V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
  2683  	if b.String() != "hello, 42 world" {
  2684  		t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
  2685  	}
  2686  }
  2687  
  2688  func TestFuncArg(t *testing.T) {
  2689  	f1 := func(i int, f func(int) int) int { return f(i) }
  2690  	f2 := func(i int) int { return i + 1 }
  2691  	r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
  2692  	if r[0].Int() != 101 {
  2693  		t.Errorf("function returned %d, want 101", r[0].Int())
  2694  	}
  2695  }
  2696  
  2697  func TestStructArg(t *testing.T) {
  2698  	type padded struct {
  2699  		B string
  2700  		C int32
  2701  	}
  2702  	var (
  2703  		gotA  padded
  2704  		gotB  uint32
  2705  		wantA = padded{"3", 4}
  2706  		wantB = uint32(5)
  2707  	)
  2708  	f := func(a padded, b uint32) {
  2709  		gotA, gotB = a, b
  2710  	}
  2711  	ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
  2712  	if gotA != wantA || gotB != wantB {
  2713  		t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
  2714  	}
  2715  }
  2716  
  2717  var tagGetTests = []struct {
  2718  	Tag   StructTag
  2719  	Key   string
  2720  	Value string
  2721  }{
  2722  	{`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
  2723  	{`protobuf:"PB(1,2)"`, `foo`, ``},
  2724  	{`protobuf:"PB(1,2)"`, `rotobuf`, ``},
  2725  	{`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
  2726  	{`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
  2727  }
  2728  
  2729  func TestTagGet(t *testing.T) {
  2730  	for _, tt := range tagGetTests {
  2731  		if v := tt.Tag.Get(tt.Key); v != tt.Value {
  2732  			t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
  2733  		}
  2734  	}
  2735  }
  2736  
  2737  func TestBytes(t *testing.T) {
  2738  	type B []byte
  2739  	x := B{1, 2, 3, 4}
  2740  	y := ValueOf(x).Bytes()
  2741  	if !bytes.Equal(x, y) {
  2742  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  2743  	}
  2744  	if &x[0] != &y[0] {
  2745  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  2746  	}
  2747  }
  2748  
  2749  func TestSetBytes(t *testing.T) {
  2750  	type B []byte
  2751  	var x B
  2752  	y := []byte{1, 2, 3, 4}
  2753  	ValueOf(&x).Elem().SetBytes(y)
  2754  	if !bytes.Equal(x, y) {
  2755  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  2756  	}
  2757  	if &x[0] != &y[0] {
  2758  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  2759  	}
  2760  }
  2761  
  2762  type Private struct {
  2763  	x int
  2764  	y **int
  2765  }
  2766  
  2767  func (p *Private) m() {
  2768  }
  2769  
  2770  type Public struct {
  2771  	X int
  2772  	Y **int
  2773  }
  2774  
  2775  func (p *Public) M() {
  2776  }
  2777  
  2778  func TestUnexported(t *testing.T) {
  2779  	var pub Public
  2780  	v := ValueOf(&pub)
  2781  	isValid(v.Elem().Field(0))
  2782  	isValid(v.Elem().Field(1))
  2783  	isValid(v.Elem().FieldByName("X"))
  2784  	isValid(v.Elem().FieldByName("Y"))
  2785  	isValid(v.Type().Method(0).Func)
  2786  	isNonNil(v.Elem().Field(0).Interface())
  2787  	isNonNil(v.Elem().Field(1).Interface())
  2788  	isNonNil(v.Elem().FieldByName("X").Interface())
  2789  	isNonNil(v.Elem().FieldByName("Y").Interface())
  2790  	isNonNil(v.Type().Method(0).Func.Interface())
  2791  
  2792  	var priv Private
  2793  	v = ValueOf(&priv)
  2794  	isValid(v.Elem().Field(0))
  2795  	isValid(v.Elem().Field(1))
  2796  	isValid(v.Elem().FieldByName("x"))
  2797  	isValid(v.Elem().FieldByName("y"))
  2798  	isValid(v.Type().Method(0).Func)
  2799  	shouldPanic(func() { v.Elem().Field(0).Interface() })
  2800  	shouldPanic(func() { v.Elem().Field(1).Interface() })
  2801  	shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
  2802  	shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
  2803  	shouldPanic(func() { v.Type().Method(0).Func.Interface() })
  2804  }
  2805  
  2806  func shouldPanic(f func()) {
  2807  	defer func() {
  2808  		if recover() == nil {
  2809  			panic("did not panic")
  2810  		}
  2811  	}()
  2812  	f()
  2813  }
  2814  
  2815  func isNonNil(x interface{}) {
  2816  	if x == nil {
  2817  		panic("nil interface")
  2818  	}
  2819  }
  2820  
  2821  func isValid(v Value) {
  2822  	if !v.IsValid() {
  2823  		panic("zero Value")
  2824  	}
  2825  }
  2826  
  2827  func TestAlias(t *testing.T) {
  2828  	x := string("hello")
  2829  	v := ValueOf(&x).Elem()
  2830  	oldvalue := v.Interface()
  2831  	v.SetString("world")
  2832  	newvalue := v.Interface()
  2833  
  2834  	if oldvalue != "hello" || newvalue != "world" {
  2835  		t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
  2836  	}
  2837  }
  2838  
  2839  var V = ValueOf
  2840  
  2841  func EmptyInterfaceV(x interface{}) Value {
  2842  	return ValueOf(&x).Elem()
  2843  }
  2844  
  2845  func ReaderV(x io.Reader) Value {
  2846  	return ValueOf(&x).Elem()
  2847  }
  2848  
  2849  func ReadWriterV(x io.ReadWriter) Value {
  2850  	return ValueOf(&x).Elem()
  2851  }
  2852  
  2853  type Empty struct{}
  2854  type MyString string
  2855  type MyBytes []byte
  2856  type MyRunes []int32
  2857  type MyFunc func()
  2858  type MyByte byte
  2859  
  2860  var convertTests = []struct {
  2861  	in  Value
  2862  	out Value
  2863  }{
  2864  	// numbers
  2865  	/*
  2866  		Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
  2867  
  2868  		package main
  2869  
  2870  		import "fmt"
  2871  
  2872  		var numbers = []string{
  2873  			"int8", "uint8", "int16", "uint16",
  2874  			"int32", "uint32", "int64", "uint64",
  2875  			"int", "uint", "uintptr",
  2876  			"float32", "float64",
  2877  		}
  2878  
  2879  		func main() {
  2880  			// all pairs but in an unusual order,
  2881  			// to emit all the int8, uint8 cases
  2882  			// before n grows too big.
  2883  			n := 1
  2884  			for i, f := range numbers {
  2885  				for _, g := range numbers[i:] {
  2886  					fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
  2887  					n++
  2888  					if f != g {
  2889  						fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
  2890  						n++
  2891  					}
  2892  				}
  2893  			}
  2894  		}
  2895  	*/
  2896  	{V(int8(1)), V(int8(1))},
  2897  	{V(int8(2)), V(uint8(2))},
  2898  	{V(uint8(3)), V(int8(3))},
  2899  	{V(int8(4)), V(int16(4))},
  2900  	{V(int16(5)), V(int8(5))},
  2901  	{V(int8(6)), V(uint16(6))},
  2902  	{V(uint16(7)), V(int8(7))},
  2903  	{V(int8(8)), V(int32(8))},
  2904  	{V(int32(9)), V(int8(9))},
  2905  	{V(int8(10)), V(uint32(10))},
  2906  	{V(uint32(11)), V(int8(11))},
  2907  	{V(int8(12)), V(int64(12))},
  2908  	{V(int64(13)), V(int8(13))},
  2909  	{V(int8(14)), V(uint64(14))},
  2910  	{V(uint64(15)), V(int8(15))},
  2911  	{V(int8(16)), V(int(16))},
  2912  	{V(int(17)), V(int8(17))},
  2913  	{V(int8(18)), V(uint(18))},
  2914  	{V(uint(19)), V(int8(19))},
  2915  	{V(int8(20)), V(uintptr(20))},
  2916  	{V(uintptr(21)), V(int8(21))},
  2917  	{V(int8(22)), V(float32(22))},
  2918  	{V(float32(23)), V(int8(23))},
  2919  	{V(int8(24)), V(float64(24))},
  2920  	{V(float64(25)), V(int8(25))},
  2921  	{V(uint8(26)), V(uint8(26))},
  2922  	{V(uint8(27)), V(int16(27))},
  2923  	{V(int16(28)), V(uint8(28))},
  2924  	{V(uint8(29)), V(uint16(29))},
  2925  	{V(uint16(30)), V(uint8(30))},
  2926  	{V(uint8(31)), V(int32(31))},
  2927  	{V(int32(32)), V(uint8(32))},
  2928  	{V(uint8(33)), V(uint32(33))},
  2929  	{V(uint32(34)), V(uint8(34))},
  2930  	{V(uint8(35)), V(int64(35))},
  2931  	{V(int64(36)), V(uint8(36))},
  2932  	{V(uint8(37)), V(uint64(37))},
  2933  	{V(uint64(38)), V(uint8(38))},
  2934  	{V(uint8(39)), V(int(39))},
  2935  	{V(int(40)), V(uint8(40))},
  2936  	{V(uint8(41)), V(uint(41))},
  2937  	{V(uint(42)), V(uint8(42))},
  2938  	{V(uint8(43)), V(uintptr(43))},
  2939  	{V(uintptr(44)), V(uint8(44))},
  2940  	{V(uint8(45)), V(float32(45))},
  2941  	{V(float32(46)), V(uint8(46))},
  2942  	{V(uint8(47)), V(float64(47))},
  2943  	{V(float64(48)), V(uint8(48))},
  2944  	{V(int16(49)), V(int16(49))},
  2945  	{V(int16(50)), V(uint16(50))},
  2946  	{V(uint16(51)), V(int16(51))},
  2947  	{V(int16(52)), V(int32(52))},
  2948  	{V(int32(53)), V(int16(53))},
  2949  	{V(int16(54)), V(uint32(54))},
  2950  	{V(uint32(55)), V(int16(55))},
  2951  	{V(int16(56)), V(int64(56))},
  2952  	{V(int64(57)), V(int16(57))},
  2953  	{V(int16(58)), V(uint64(58))},
  2954  	{V(uint64(59)), V(int16(59))},
  2955  	{V(int16(60)), V(int(60))},
  2956  	{V(int(61)), V(int16(61))},
  2957  	{V(int16(62)), V(uint(62))},
  2958  	{V(uint(63)), V(int16(63))},
  2959  	{V(int16(64)), V(uintptr(64))},
  2960  	{V(uintptr(65)), V(int16(65))},
  2961  	{V(int16(66)), V(float32(66))},
  2962  	{V(float32(67)), V(int16(67))},
  2963  	{V(int16(68)), V(float64(68))},
  2964  	{V(float64(69)), V(int16(69))},
  2965  	{V(uint16(70)), V(uint16(70))},
  2966  	{V(uint16(71)), V(int32(71))},
  2967  	{V(int32(72)), V(uint16(72))},
  2968  	{V(uint16(73)), V(uint32(73))},
  2969  	{V(uint32(74)), V(uint16(74))},
  2970  	{V(uint16(75)), V(int64(75))},
  2971  	{V(int64(76)), V(uint16(76))},
  2972  	{V(uint16(77)), V(uint64(77))},
  2973  	{V(uint64(78)), V(uint16(78))},
  2974  	{V(uint16(79)), V(int(79))},
  2975  	{V(int(80)), V(uint16(80))},
  2976  	{V(uint16(81)), V(uint(81))},
  2977  	{V(uint(82)), V(uint16(82))},
  2978  	{V(uint16(83)), V(uintptr(83))},
  2979  	{V(uintptr(84)), V(uint16(84))},
  2980  	{V(uint16(85)), V(float32(85))},
  2981  	{V(float32(86)), V(uint16(86))},
  2982  	{V(uint16(87)), V(float64(87))},
  2983  	{V(float64(88)), V(uint16(88))},
  2984  	{V(int32(89)), V(int32(89))},
  2985  	{V(int32(90)), V(uint32(90))},
  2986  	{V(uint32(91)), V(int32(91))},
  2987  	{V(int32(92)), V(int64(92))},
  2988  	{V(int64(93)), V(int32(93))},
  2989  	{V(int32(94)), V(uint64(94))},
  2990  	{V(uint64(95)), V(int32(95))},
  2991  	{V(int32(96)), V(int(96))},
  2992  	{V(int(97)), V(int32(97))},
  2993  	{V(int32(98)), V(uint(98))},
  2994  	{V(uint(99)), V(int32(99))},
  2995  	{V(int32(100)), V(uintptr(100))},
  2996  	{V(uintptr(101)), V(int32(101))},
  2997  	{V(int32(102)), V(float32(102))},
  2998  	{V(float32(103)), V(int32(103))},
  2999  	{V(int32(104)), V(float64(104))},
  3000  	{V(float64(105)), V(int32(105))},
  3001  	{V(uint32(106)), V(uint32(106))},
  3002  	{V(uint32(107)), V(int64(107))},
  3003  	{V(int64(108)), V(uint32(108))},
  3004  	{V(uint32(109)), V(uint64(109))},
  3005  	{V(uint64(110)), V(uint32(110))},
  3006  	{V(uint32(111)), V(int(111))},
  3007  	{V(int(112)), V(uint32(112))},
  3008  	{V(uint32(113)), V(uint(113))},
  3009  	{V(uint(114)), V(uint32(114))},
  3010  	{V(uint32(115)), V(uintptr(115))},
  3011  	{V(uintptr(116)), V(uint32(116))},
  3012  	{V(uint32(117)), V(float32(117))},
  3013  	{V(float32(118)), V(uint32(118))},
  3014  	{V(uint32(119)), V(float64(119))},
  3015  	{V(float64(120)), V(uint32(120))},
  3016  	{V(int64(121)), V(int64(121))},
  3017  	{V(int64(122)), V(uint64(122))},
  3018  	{V(uint64(123)), V(int64(123))},
  3019  	{V(int64(124)), V(int(124))},
  3020  	{V(int(125)), V(int64(125))},
  3021  	{V(int64(126)), V(uint(126))},
  3022  	{V(uint(127)), V(int64(127))},
  3023  	{V(int64(128)), V(uintptr(128))},
  3024  	{V(uintptr(129)), V(int64(129))},
  3025  	{V(int64(130)), V(float32(130))},
  3026  	{V(float32(131)), V(int64(131))},
  3027  	{V(int64(132)), V(float64(132))},
  3028  	{V(float64(133)), V(int64(133))},
  3029  	{V(uint64(134)), V(uint64(134))},
  3030  	{V(uint64(135)), V(int(135))},
  3031  	{V(int(136)), V(uint64(136))},
  3032  	{V(uint64(137)), V(uint(137))},
  3033  	{V(uint(138)), V(uint64(138))},
  3034  	{V(uint64(139)), V(uintptr(139))},
  3035  	{V(uintptr(140)), V(uint64(140))},
  3036  	{V(uint64(141)), V(float32(141))},
  3037  	{V(float32(142)), V(uint64(142))},
  3038  	{V(uint64(143)), V(float64(143))},
  3039  	{V(float64(144)), V(uint64(144))},
  3040  	{V(int(145)), V(int(145))},
  3041  	{V(int(146)), V(uint(146))},
  3042  	{V(uint(147)), V(int(147))},
  3043  	{V(int(148)), V(uintptr(148))},
  3044  	{V(uintptr(149)), V(int(149))},
  3045  	{V(int(150)), V(float32(150))},
  3046  	{V(float32(151)), V(int(151))},
  3047  	{V(int(152)), V(float64(152))},
  3048  	{V(float64(153)), V(int(153))},
  3049  	{V(uint(154)), V(uint(154))},
  3050  	{V(uint(155)), V(uintptr(155))},
  3051  	{V(uintptr(156)), V(uint(156))},
  3052  	{V(uint(157)), V(float32(157))},
  3053  	{V(float32(158)), V(uint(158))},
  3054  	{V(uint(159)), V(float64(159))},
  3055  	{V(float64(160)), V(uint(160))},
  3056  	{V(uintptr(161)), V(uintptr(161))},
  3057  	{V(uintptr(162)), V(float32(162))},
  3058  	{V(float32(163)), V(uintptr(163))},
  3059  	{V(uintptr(164)), V(float64(164))},
  3060  	{V(float64(165)), V(uintptr(165))},
  3061  	{V(float32(166)), V(float32(166))},
  3062  	{V(float32(167)), V(float64(167))},
  3063  	{V(float64(168)), V(float32(168))},
  3064  	{V(float64(169)), V(float64(169))},
  3065  
  3066  	// truncation
  3067  	{V(float64(1.5)), V(int(1))},
  3068  
  3069  	// complex
  3070  	{V(complex64(1i)), V(complex64(1i))},
  3071  	{V(complex64(2i)), V(complex128(2i))},
  3072  	{V(complex128(3i)), V(complex64(3i))},
  3073  	{V(complex128(4i)), V(complex128(4i))},
  3074  
  3075  	// string
  3076  	{V(string("hello")), V(string("hello"))},
  3077  	{V(string("bytes1")), V([]byte("bytes1"))},
  3078  	{V([]byte("bytes2")), V(string("bytes2"))},
  3079  	{V([]byte("bytes3")), V([]byte("bytes3"))},
  3080  	{V(string("runes♝")), V([]rune("runes♝"))},
  3081  	{V([]rune("runes♕")), V(string("runes♕"))},
  3082  	{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  3083  	{V(int('a')), V(string("a"))},
  3084  	{V(int8('a')), V(string("a"))},
  3085  	{V(int16('a')), V(string("a"))},
  3086  	{V(int32('a')), V(string("a"))},
  3087  	{V(int64('a')), V(string("a"))},
  3088  	{V(uint('a')), V(string("a"))},
  3089  	{V(uint8('a')), V(string("a"))},
  3090  	{V(uint16('a')), V(string("a"))},
  3091  	{V(uint32('a')), V(string("a"))},
  3092  	{V(uint64('a')), V(string("a"))},
  3093  	{V(uintptr('a')), V(string("a"))},
  3094  	{V(int(-1)), V(string("\uFFFD"))},
  3095  	{V(int8(-2)), V(string("\uFFFD"))},
  3096  	{V(int16(-3)), V(string("\uFFFD"))},
  3097  	{V(int32(-4)), V(string("\uFFFD"))},
  3098  	{V(int64(-5)), V(string("\uFFFD"))},
  3099  	{V(uint(0x110001)), V(string("\uFFFD"))},
  3100  	{V(uint32(0x110002)), V(string("\uFFFD"))},
  3101  	{V(uint64(0x110003)), V(string("\uFFFD"))},
  3102  	{V(uintptr(0x110004)), V(string("\uFFFD"))},
  3103  
  3104  	// named string
  3105  	{V(MyString("hello")), V(string("hello"))},
  3106  	{V(string("hello")), V(MyString("hello"))},
  3107  	{V(string("hello")), V(string("hello"))},
  3108  	{V(MyString("hello")), V(MyString("hello"))},
  3109  	{V(MyString("bytes1")), V([]byte("bytes1"))},
  3110  	{V([]byte("bytes2")), V(MyString("bytes2"))},
  3111  	{V([]byte("bytes3")), V([]byte("bytes3"))},
  3112  	{V(MyString("runes♝")), V([]rune("runes♝"))},
  3113  	{V([]rune("runes♕")), V(MyString("runes♕"))},
  3114  	{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  3115  	{V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  3116  	{V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  3117  	{V(int('a')), V(MyString("a"))},
  3118  	{V(int8('a')), V(MyString("a"))},
  3119  	{V(int16('a')), V(MyString("a"))},
  3120  	{V(int32('a')), V(MyString("a"))},
  3121  	{V(int64('a')), V(MyString("a"))},
  3122  	{V(uint('a')), V(MyString("a"))},
  3123  	{V(uint8('a')), V(MyString("a"))},
  3124  	{V(uint16('a')), V(MyString("a"))},
  3125  	{V(uint32('a')), V(MyString("a"))},
  3126  	{V(uint64('a')), V(MyString("a"))},
  3127  	{V(uintptr('a')), V(MyString("a"))},
  3128  	{V(int(-1)), V(MyString("\uFFFD"))},
  3129  	{V(int8(-2)), V(MyString("\uFFFD"))},
  3130  	{V(int16(-3)), V(MyString("\uFFFD"))},
  3131  	{V(int32(-4)), V(MyString("\uFFFD"))},
  3132  	{V(int64(-5)), V(MyString("\uFFFD"))},
  3133  	{V(uint(0x110001)), V(MyString("\uFFFD"))},
  3134  	{V(uint32(0x110002)), V(MyString("\uFFFD"))},
  3135  	{V(uint64(0x110003)), V(MyString("\uFFFD"))},
  3136  	{V(uintptr(0x110004)), V(MyString("\uFFFD"))},
  3137  
  3138  	// named []byte
  3139  	{V(string("bytes1")), V(MyBytes("bytes1"))},
  3140  	{V(MyBytes("bytes2")), V(string("bytes2"))},
  3141  	{V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
  3142  	{V(MyString("bytes1")), V(MyBytes("bytes1"))},
  3143  	{V(MyBytes("bytes2")), V(MyString("bytes2"))},
  3144  
  3145  	// named []rune
  3146  	{V(string("runes♝")), V(MyRunes("runes♝"))},
  3147  	{V(MyRunes("runes♕")), V(string("runes♕"))},
  3148  	{V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  3149  	{V(MyString("runes♝")), V(MyRunes("runes♝"))},
  3150  	{V(MyRunes("runes♕")), V(MyString("runes♕"))},
  3151  
  3152  	// named types and equal underlying types
  3153  	{V(new(int)), V(new(integer))},
  3154  	{V(new(integer)), V(new(int))},
  3155  	{V(Empty{}), V(struct{}{})},
  3156  	{V(new(Empty)), V(new(struct{}))},
  3157  	{V(struct{}{}), V(Empty{})},
  3158  	{V(new(struct{})), V(new(Empty))},
  3159  	{V(Empty{}), V(Empty{})},
  3160  	{V(MyBytes{}), V([]byte{})},
  3161  	{V([]byte{}), V(MyBytes{})},
  3162  	{V((func())(nil)), V(MyFunc(nil))},
  3163  	{V((MyFunc)(nil)), V((func())(nil))},
  3164  
  3165  	// can convert *byte and *MyByte
  3166  	{V((*byte)(nil)), V((*MyByte)(nil))},
  3167  	{V((*MyByte)(nil)), V((*byte)(nil))},
  3168  
  3169  	// cannot convert mismatched array sizes
  3170  	{V([2]byte{}), V([2]byte{})},
  3171  	{V([3]byte{}), V([3]byte{})},
  3172  
  3173  	// cannot convert other instances
  3174  	{V((**byte)(nil)), V((**byte)(nil))},
  3175  	{V((**MyByte)(nil)), V((**MyByte)(nil))},
  3176  	{V((chan byte)(nil)), V((chan byte)(nil))},
  3177  	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  3178  	{V(([]byte)(nil)), V(([]byte)(nil))},
  3179  	{V(([]MyByte)(nil)), V(([]MyByte)(nil))},
  3180  	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  3181  	{V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
  3182  	{V((map[byte]int)(nil)), V((map[byte]int)(nil))},
  3183  	{V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
  3184  	{V([2]byte{}), V([2]byte{})},
  3185  	{V([2]MyByte{}), V([2]MyByte{})},
  3186  
  3187  	// other
  3188  	{V((***int)(nil)), V((***int)(nil))},
  3189  	{V((***byte)(nil)), V((***byte)(nil))},
  3190  	{V((***int32)(nil)), V((***int32)(nil))},
  3191  	{V((***int64)(nil)), V((***int64)(nil))},
  3192  	{V((chan int)(nil)), V((<-chan int)(nil))},
  3193  	{V((chan int)(nil)), V((chan<- int)(nil))},
  3194  	{V((chan string)(nil)), V((<-chan string)(nil))},
  3195  	{V((chan string)(nil)), V((chan<- string)(nil))},
  3196  	{V((chan byte)(nil)), V((chan byte)(nil))},
  3197  	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  3198  	{V((map[int]bool)(nil)), V((map[int]bool)(nil))},
  3199  	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  3200  	{V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
  3201  	{V([]uint(nil)), V([]uint(nil))},
  3202  	{V([]int(nil)), V([]int(nil))},
  3203  	{V(new(interface{})), V(new(interface{}))},
  3204  	{V(new(io.Reader)), V(new(io.Reader))},
  3205  	{V(new(io.Writer)), V(new(io.Writer))},
  3206  
  3207  	// interfaces
  3208  	{V(int(1)), EmptyInterfaceV(int(1))},
  3209  	{V(string("hello")), EmptyInterfaceV(string("hello"))},
  3210  	{V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  3211  	{ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  3212  	{V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
  3213  }
  3214  
  3215  func TestConvert(t *testing.T) {
  3216  	canConvert := map[[2]Type]bool{}
  3217  	all := map[Type]bool{}
  3218  
  3219  	for _, tt := range convertTests {
  3220  		t1 := tt.in.Type()
  3221  		if !t1.ConvertibleTo(t1) {
  3222  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
  3223  			continue
  3224  		}
  3225  
  3226  		t2 := tt.out.Type()
  3227  		if !t1.ConvertibleTo(t2) {
  3228  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
  3229  			continue
  3230  		}
  3231  
  3232  		all[t1] = true
  3233  		all[t2] = true
  3234  		canConvert[[2]Type{t1, t2}] = true
  3235  
  3236  		// vout1 represents the in value converted to the in type.
  3237  		v1 := tt.in
  3238  		vout1 := v1.Convert(t1)
  3239  		out1 := vout1.Interface()
  3240  		if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
  3241  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
  3242  		}
  3243  
  3244  		// vout2 represents the in value converted to the out type.
  3245  		vout2 := v1.Convert(t2)
  3246  		out2 := vout2.Interface()
  3247  		if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
  3248  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
  3249  		}
  3250  
  3251  		// vout3 represents a new value of the out type, set to vout2.  This makes
  3252  		// sure the converted value vout2 is really usable as a regular value.
  3253  		vout3 := New(t2).Elem()
  3254  		vout3.Set(vout2)
  3255  		out3 := vout3.Interface()
  3256  		if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
  3257  			t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
  3258  		}
  3259  
  3260  		if IsRO(v1) {
  3261  			t.Errorf("table entry %v is RO, should not be", v1)
  3262  		}
  3263  		if IsRO(vout1) {
  3264  			t.Errorf("self-conversion output %v is RO, should not be", vout1)
  3265  		}
  3266  		if IsRO(vout2) {
  3267  			t.Errorf("conversion output %v is RO, should not be", vout2)
  3268  		}
  3269  		if IsRO(vout3) {
  3270  			t.Errorf("set(conversion output) %v is RO, should not be", vout3)
  3271  		}
  3272  		if !IsRO(MakeRO(v1).Convert(t1)) {
  3273  			t.Errorf("RO self-conversion output %v is not RO, should be", v1)
  3274  		}
  3275  		if !IsRO(MakeRO(v1).Convert(t2)) {
  3276  			t.Errorf("RO conversion output %v is not RO, should be", v1)
  3277  		}
  3278  	}
  3279  
  3280  	// Assume that of all the types we saw during the tests,
  3281  	// if there wasn't an explicit entry for a conversion between
  3282  	// a pair of types, then it's not to be allowed. This checks for
  3283  	// things like 'int64' converting to '*int'.
  3284  	for t1 := range all {
  3285  		for t2 := range all {
  3286  			expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
  3287  			if ok := t1.ConvertibleTo(t2); ok != expectOK {
  3288  				t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
  3289  			}
  3290  		}
  3291  	}
  3292  }
  3293  
  3294  type ComparableStruct struct {
  3295  	X int
  3296  }
  3297  
  3298  type NonComparableStruct struct {
  3299  	X int
  3300  	Y map[string]int
  3301  }
  3302  
  3303  var comparableTests = []struct {
  3304  	typ Type
  3305  	ok  bool
  3306  }{
  3307  	{TypeOf(1), true},
  3308  	{TypeOf("hello"), true},
  3309  	{TypeOf(new(byte)), true},
  3310  	{TypeOf((func())(nil)), false},
  3311  	{TypeOf([]byte{}), false},
  3312  	{TypeOf(map[string]int{}), false},
  3313  	{TypeOf(make(chan int)), true},
  3314  	{TypeOf(1.5), true},
  3315  	{TypeOf(false), true},
  3316  	{TypeOf(1i), true},
  3317  	{TypeOf(ComparableStruct{}), true},
  3318  	{TypeOf(NonComparableStruct{}), false},
  3319  	{TypeOf([10]map[string]int{}), false},
  3320  	{TypeOf([10]string{}), true},
  3321  	{TypeOf(new(interface{})).Elem(), true},
  3322  }
  3323  
  3324  func TestComparable(t *testing.T) {
  3325  	for _, tt := range comparableTests {
  3326  		if ok := tt.typ.Comparable(); ok != tt.ok {
  3327  			t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
  3328  		}
  3329  	}
  3330  }
  3331  
  3332  func TestOverflow(t *testing.T) {
  3333  	if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
  3334  		t.Errorf("%v wrongly overflows float64", 1e300)
  3335  	}
  3336  
  3337  	maxFloat32 := float64((1<<24 - 1) << (127 - 23))
  3338  	if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
  3339  		t.Errorf("%v wrongly overflows float32", maxFloat32)
  3340  	}
  3341  	ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
  3342  	if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
  3343  		t.Errorf("%v should overflow float32", ovfFloat32)
  3344  	}
  3345  	if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
  3346  		t.Errorf("%v should overflow float32", -ovfFloat32)
  3347  	}
  3348  
  3349  	maxInt32 := int64(0x7fffffff)
  3350  	if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
  3351  		t.Errorf("%v wrongly overflows int32", maxInt32)
  3352  	}
  3353  	if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
  3354  		t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
  3355  	}
  3356  	ovfInt32 := int64(1 << 31)
  3357  	if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
  3358  		t.Errorf("%v should overflow int32", ovfInt32)
  3359  	}
  3360  
  3361  	maxUint32 := uint64(0xffffffff)
  3362  	if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
  3363  		t.Errorf("%v wrongly overflows uint32", maxUint32)
  3364  	}
  3365  	ovfUint32 := uint64(1 << 32)
  3366  	if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
  3367  		t.Errorf("%v should overflow uint32", ovfUint32)
  3368  	}
  3369  }
  3370  
  3371  func checkSameType(t *testing.T, x, y interface{}) {
  3372  	if TypeOf(x) != TypeOf(y) {
  3373  		t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
  3374  	}
  3375  }
  3376  
  3377  func TestArrayOf(t *testing.T) {
  3378  	// TODO(rsc): Finish ArrayOf and enable-test.
  3379  	t.Skip("ArrayOf is not finished (and not exported)")
  3380  
  3381  	// check construction and use of type not in binary
  3382  	type T int
  3383  	at := ArrayOf(10, TypeOf(T(1)))
  3384  	v := New(at).Elem()
  3385  	for i := 0; i < v.Len(); i++ {
  3386  		v.Index(i).Set(ValueOf(T(i)))
  3387  	}
  3388  	s := fmt.Sprint(v.Interface())
  3389  	want := "[0 1 2 3 4 5 6 7 8 9]"
  3390  	if s != want {
  3391  		t.Errorf("constructed array = %s, want %s", s, want)
  3392  	}
  3393  
  3394  	// check that type already in binary is found
  3395  	checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
  3396  }
  3397  
  3398  func TestSliceOf(t *testing.T) {
  3399  	// check construction and use of type not in binary
  3400  	type T int
  3401  	st := SliceOf(TypeOf(T(1)))
  3402  	v := MakeSlice(st, 10, 10)
  3403  	runtime.GC()
  3404  	for i := 0; i < v.Len(); i++ {
  3405  		v.Index(i).Set(ValueOf(T(i)))
  3406  		runtime.GC()
  3407  	}
  3408  	s := fmt.Sprint(v.Interface())
  3409  	want := "[0 1 2 3 4 5 6 7 8 9]"
  3410  	if s != want {
  3411  		t.Errorf("constructed slice = %s, want %s", s, want)
  3412  	}
  3413  
  3414  	// check that type already in binary is found
  3415  	type T1 int
  3416  	checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
  3417  }
  3418  
  3419  func TestSliceOverflow(t *testing.T) {
  3420  	// check that MakeSlice panics when size of slice overflows uint
  3421  	const S = 1e6
  3422  	s := uint(S)
  3423  	l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
  3424  	if l*s >= s {
  3425  		t.Fatal("slice size does not overflow")
  3426  	}
  3427  	var x [S]byte
  3428  	st := SliceOf(TypeOf(x))
  3429  	defer func() {
  3430  		err := recover()
  3431  		if err == nil {
  3432  			t.Fatal("slice overflow does not panic")
  3433  		}
  3434  	}()
  3435  	MakeSlice(st, int(l), int(l))
  3436  }
  3437  
  3438  func TestSliceOfGC(t *testing.T) {
  3439  	type T *uintptr
  3440  	tt := TypeOf(T(nil))
  3441  	st := SliceOf(tt)
  3442  	const n = 100
  3443  	var x []interface{}
  3444  	for i := 0; i < n; i++ {
  3445  		v := MakeSlice(st, n, n)
  3446  		for j := 0; j < v.Len(); j++ {
  3447  			p := new(uintptr)
  3448  			*p = uintptr(i*n + j)
  3449  			v.Index(j).Set(ValueOf(p).Convert(tt))
  3450  		}
  3451  		x = append(x, v.Interface())
  3452  	}
  3453  	runtime.GC()
  3454  
  3455  	for i, xi := range x {
  3456  		v := ValueOf(xi)
  3457  		for j := 0; j < v.Len(); j++ {
  3458  			k := v.Index(j).Elem().Interface()
  3459  			if k != uintptr(i*n+j) {
  3460  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3461  			}
  3462  		}
  3463  	}
  3464  }
  3465  
  3466  func TestChanOf(t *testing.T) {
  3467  	// check construction and use of type not in binary
  3468  	type T string
  3469  	ct := ChanOf(BothDir, TypeOf(T("")))
  3470  	v := MakeChan(ct, 2)
  3471  	runtime.GC()
  3472  	v.Send(ValueOf(T("hello")))
  3473  	runtime.GC()
  3474  	v.Send(ValueOf(T("world")))
  3475  	runtime.GC()
  3476  
  3477  	sv1, _ := v.Recv()
  3478  	sv2, _ := v.Recv()
  3479  	s1 := sv1.String()
  3480  	s2 := sv2.String()
  3481  	if s1 != "hello" || s2 != "world" {
  3482  		t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
  3483  	}
  3484  
  3485  	// check that type already in binary is found
  3486  	type T1 int
  3487  	checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
  3488  }
  3489  
  3490  func TestChanOfDir(t *testing.T) {
  3491  	// check construction and use of type not in binary
  3492  	type T string
  3493  	crt := ChanOf(RecvDir, TypeOf(T("")))
  3494  	cst := ChanOf(SendDir, TypeOf(T("")))
  3495  
  3496  	// check that type already in binary is found
  3497  	type T1 int
  3498  	checkSameType(t, Zero(ChanOf(RecvDir, TypeOf(T1(1)))).Interface(), (<-chan T1)(nil))
  3499  	checkSameType(t, Zero(ChanOf(SendDir, TypeOf(T1(1)))).Interface(), (chan<- T1)(nil))
  3500  
  3501  	// check String form of ChanDir
  3502  	if crt.ChanDir().String() != "<-chan" {
  3503  		t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
  3504  	}
  3505  	if cst.ChanDir().String() != "chan<-" {
  3506  		t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
  3507  	}
  3508  }
  3509  
  3510  func TestChanOfGC(t *testing.T) {
  3511  	done := make(chan bool, 1)
  3512  	go func() {
  3513  		select {
  3514  		case <-done:
  3515  		case <-time.After(5 * time.Second):
  3516  			panic("deadlock in TestChanOfGC")
  3517  		}
  3518  	}()
  3519  
  3520  	defer func() {
  3521  		done <- true
  3522  	}()
  3523  
  3524  	type T *uintptr
  3525  	tt := TypeOf(T(nil))
  3526  	ct := ChanOf(BothDir, tt)
  3527  
  3528  	// NOTE: The garbage collector handles allocated channels specially,
  3529  	// so we have to save pointers to channels in x; the pointer code will
  3530  	// use the gc info in the newly constructed chan type.
  3531  	const n = 100
  3532  	var x []interface{}
  3533  	for i := 0; i < n; i++ {
  3534  		v := MakeChan(ct, n)
  3535  		for j := 0; j < n; j++ {
  3536  			p := new(uintptr)
  3537  			*p = uintptr(i*n + j)
  3538  			v.Send(ValueOf(p).Convert(tt))
  3539  		}
  3540  		pv := New(ct)
  3541  		pv.Elem().Set(v)
  3542  		x = append(x, pv.Interface())
  3543  	}
  3544  	runtime.GC()
  3545  
  3546  	for i, xi := range x {
  3547  		v := ValueOf(xi).Elem()
  3548  		for j := 0; j < n; j++ {
  3549  			pv, _ := v.Recv()
  3550  			k := pv.Elem().Interface()
  3551  			if k != uintptr(i*n+j) {
  3552  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3553  			}
  3554  		}
  3555  	}
  3556  }
  3557  
  3558  func TestMapOf(t *testing.T) {
  3559  	// check construction and use of type not in binary
  3560  	type K string
  3561  	type V float64
  3562  
  3563  	v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
  3564  	runtime.GC()
  3565  	v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
  3566  	runtime.GC()
  3567  
  3568  	s := fmt.Sprint(v.Interface())
  3569  	want := "map[a:1]"
  3570  	if s != want {
  3571  		t.Errorf("constructed map = %s, want %s", s, want)
  3572  	}
  3573  
  3574  	// check that type already in binary is found
  3575  	checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
  3576  
  3577  	// check that invalid key type panics
  3578  	shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
  3579  }
  3580  
  3581  func TestMapOfGCKeys(t *testing.T) {
  3582  	type T *uintptr
  3583  	tt := TypeOf(T(nil))
  3584  	mt := MapOf(tt, TypeOf(false))
  3585  
  3586  	// NOTE: The garbage collector handles allocated maps specially,
  3587  	// so we have to save pointers to maps in x; the pointer code will
  3588  	// use the gc info in the newly constructed map type.
  3589  	const n = 100
  3590  	var x []interface{}
  3591  	for i := 0; i < n; i++ {
  3592  		v := MakeMap(mt)
  3593  		for j := 0; j < n; j++ {
  3594  			p := new(uintptr)
  3595  			*p = uintptr(i*n + j)
  3596  			v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
  3597  		}
  3598  		pv := New(mt)
  3599  		pv.Elem().Set(v)
  3600  		x = append(x, pv.Interface())
  3601  	}
  3602  	runtime.GC()
  3603  
  3604  	for i, xi := range x {
  3605  		v := ValueOf(xi).Elem()
  3606  		var out []int
  3607  		for _, kv := range v.MapKeys() {
  3608  			out = append(out, int(kv.Elem().Interface().(uintptr)))
  3609  		}
  3610  		sort.Ints(out)
  3611  		for j, k := range out {
  3612  			if k != i*n+j {
  3613  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3614  			}
  3615  		}
  3616  	}
  3617  }
  3618  
  3619  func TestMapOfGCValues(t *testing.T) {
  3620  	type T *uintptr
  3621  	tt := TypeOf(T(nil))
  3622  	mt := MapOf(TypeOf(1), tt)
  3623  
  3624  	// NOTE: The garbage collector handles allocated maps specially,
  3625  	// so we have to save pointers to maps in x; the pointer code will
  3626  	// use the gc info in the newly constructed map type.
  3627  	const n = 100
  3628  	var x []interface{}
  3629  	for i := 0; i < n; i++ {
  3630  		v := MakeMap(mt)
  3631  		for j := 0; j < n; j++ {
  3632  			p := new(uintptr)
  3633  			*p = uintptr(i*n + j)
  3634  			v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
  3635  		}
  3636  		pv := New(mt)
  3637  		pv.Elem().Set(v)
  3638  		x = append(x, pv.Interface())
  3639  	}
  3640  	runtime.GC()
  3641  
  3642  	for i, xi := range x {
  3643  		v := ValueOf(xi).Elem()
  3644  		for j := 0; j < n; j++ {
  3645  			k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
  3646  			if k != uintptr(i*n+j) {
  3647  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3648  			}
  3649  		}
  3650  	}
  3651  }
  3652  
  3653  type B1 struct {
  3654  	X int
  3655  	Y int
  3656  	Z int
  3657  }
  3658  
  3659  func BenchmarkFieldByName1(b *testing.B) {
  3660  	t := TypeOf(B1{})
  3661  	for i := 0; i < b.N; i++ {
  3662  		t.FieldByName("Z")
  3663  	}
  3664  }
  3665  
  3666  func BenchmarkFieldByName2(b *testing.B) {
  3667  	t := TypeOf(S3{})
  3668  	for i := 0; i < b.N; i++ {
  3669  		t.FieldByName("B")
  3670  	}
  3671  }
  3672  
  3673  type R0 struct {
  3674  	*R1
  3675  	*R2
  3676  	*R3
  3677  	*R4
  3678  }
  3679  
  3680  type R1 struct {
  3681  	*R5
  3682  	*R6
  3683  	*R7
  3684  	*R8
  3685  }
  3686  
  3687  type R2 R1
  3688  type R3 R1
  3689  type R4 R1
  3690  
  3691  type R5 struct {
  3692  	*R9
  3693  	*R10
  3694  	*R11
  3695  	*R12
  3696  }
  3697  
  3698  type R6 R5
  3699  type R7 R5
  3700  type R8 R5
  3701  
  3702  type R9 struct {
  3703  	*R13
  3704  	*R14
  3705  	*R15
  3706  	*R16
  3707  }
  3708  
  3709  type R10 R9
  3710  type R11 R9
  3711  type R12 R9
  3712  
  3713  type R13 struct {
  3714  	*R17
  3715  	*R18
  3716  	*R19
  3717  	*R20
  3718  }
  3719  
  3720  type R14 R13
  3721  type R15 R13
  3722  type R16 R13
  3723  
  3724  type R17 struct {
  3725  	*R21
  3726  	*R22
  3727  	*R23
  3728  	*R24
  3729  }
  3730  
  3731  type R18 R17
  3732  type R19 R17
  3733  type R20 R17
  3734  
  3735  type R21 struct {
  3736  	X int
  3737  }
  3738  
  3739  type R22 R21
  3740  type R23 R21
  3741  type R24 R21
  3742  
  3743  func TestEmbed(t *testing.T) {
  3744  	typ := TypeOf(R0{})
  3745  	f, ok := typ.FieldByName("X")
  3746  	if ok {
  3747  		t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
  3748  	}
  3749  }
  3750  
  3751  func BenchmarkFieldByName3(b *testing.B) {
  3752  	t := TypeOf(R0{})
  3753  	for i := 0; i < b.N; i++ {
  3754  		t.FieldByName("X")
  3755  	}
  3756  }
  3757  
  3758  type S struct {
  3759  	i1 int64
  3760  	i2 int64
  3761  }
  3762  
  3763  func BenchmarkInterfaceBig(b *testing.B) {
  3764  	v := ValueOf(S{})
  3765  	for i := 0; i < b.N; i++ {
  3766  		v.Interface()
  3767  	}
  3768  	b.StopTimer()
  3769  }
  3770  
  3771  func TestAllocsInterfaceBig(t *testing.T) {
  3772  	if testing.Short() {
  3773  		t.Skip("skipping malloc count in short mode")
  3774  	}
  3775  	v := ValueOf(S{})
  3776  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  3777  		t.Error("allocs:", allocs)
  3778  	}
  3779  }
  3780  
  3781  func BenchmarkInterfaceSmall(b *testing.B) {
  3782  	v := ValueOf(int64(0))
  3783  	for i := 0; i < b.N; i++ {
  3784  		v.Interface()
  3785  	}
  3786  }
  3787  
  3788  func TestAllocsInterfaceSmall(t *testing.T) {
  3789  	if testing.Short() {
  3790  		t.Skip("skipping malloc count in short mode")
  3791  	}
  3792  	v := ValueOf(int64(0))
  3793  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  3794  		t.Error("allocs:", allocs)
  3795  	}
  3796  }
  3797  
  3798  // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
  3799  // The basic usage is:
  3800  //
  3801  //	for x.Next() {
  3802  //		... code using x.Maybe() or x.Choice(n) to create test cases ...
  3803  //	}
  3804  //
  3805  // Each iteration of the loop returns a different set of results, until all
  3806  // possible result sets have been explored. It is okay for different code paths
  3807  // to make different method call sequences on x, but there must be no
  3808  // other source of non-determinism in the call sequences.
  3809  //
  3810  // When faced with a new decision, x chooses randomly. Future explorations
  3811  // of that path will choose successive values for the result. Thus, stopping
  3812  // the loop after a fixed number of iterations gives somewhat stochastic
  3813  // testing.
  3814  //
  3815  // Example:
  3816  //
  3817  //	for x.Next() {
  3818  //		v := make([]bool, x.Choose(4))
  3819  //		for i := range v {
  3820  //			v[i] = x.Maybe()
  3821  //		}
  3822  //		fmt.Println(v)
  3823  //	}
  3824  //
  3825  // prints (in some order):
  3826  //
  3827  //	[]
  3828  //	[false]
  3829  //	[true]
  3830  //	[false false]
  3831  //	[false true]
  3832  //	...
  3833  //	[true true]
  3834  //	[false false false]
  3835  //	...
  3836  //	[true true true]
  3837  //	[false false false false]
  3838  //	...
  3839  //	[true true true true]
  3840  //
  3841  type exhaustive struct {
  3842  	r    *rand.Rand
  3843  	pos  int
  3844  	last []choice
  3845  }
  3846  
  3847  type choice struct {
  3848  	off int
  3849  	n   int
  3850  	max int
  3851  }
  3852  
  3853  func (x *exhaustive) Next() bool {
  3854  	if x.r == nil {
  3855  		x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
  3856  	}
  3857  	x.pos = 0
  3858  	if x.last == nil {
  3859  		x.last = []choice{}
  3860  		return true
  3861  	}
  3862  	for i := len(x.last) - 1; i >= 0; i-- {
  3863  		c := &x.last[i]
  3864  		if c.n+1 < c.max {
  3865  			c.n++
  3866  			x.last = x.last[:i+1]
  3867  			return true
  3868  		}
  3869  	}
  3870  	return false
  3871  }
  3872  
  3873  func (x *exhaustive) Choose(max int) int {
  3874  	if x.pos >= len(x.last) {
  3875  		x.last = append(x.last, choice{x.r.Intn(max), 0, max})
  3876  	}
  3877  	c := &x.last[x.pos]
  3878  	x.pos++
  3879  	if c.max != max {
  3880  		panic("inconsistent use of exhaustive tester")
  3881  	}
  3882  	return (c.n + c.off) % max
  3883  }
  3884  
  3885  func (x *exhaustive) Maybe() bool {
  3886  	return x.Choose(2) == 1
  3887  }
  3888  
  3889  func GCFunc(args []Value) []Value {
  3890  	runtime.GC()
  3891  	return []Value{}
  3892  }
  3893  
  3894  func TestReflectFuncTraceback(t *testing.T) {
  3895  	f := MakeFunc(TypeOf(func() {}), GCFunc)
  3896  	f.Call([]Value{})
  3897  }
  3898  
  3899  func TestReflectMethodTraceback(t *testing.T) {
  3900  	p := Point{3, 4}
  3901  	m := ValueOf(p).MethodByName("GCMethod")
  3902  	i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
  3903  	if i != 8 {
  3904  		t.Errorf("Call returned %d; want 8", i)
  3905  	}
  3906  }
  3907  
  3908  func TestBigZero(t *testing.T) {
  3909  	const size = 1 << 10
  3910  	var v [size]byte
  3911  	z := Zero(ValueOf(v).Type()).Interface().([size]byte)
  3912  	for i := 0; i < size; i++ {
  3913  		if z[i] != 0 {
  3914  			t.Fatalf("Zero object not all zero, index %d", i)
  3915  		}
  3916  	}
  3917  }
  3918  
  3919  func TestFieldByIndexNil(t *testing.T) {
  3920  	type P struct {
  3921  		F int
  3922  	}
  3923  	type T struct {
  3924  		*P
  3925  	}
  3926  	v := ValueOf(T{})
  3927  
  3928  	v.FieldByName("P") // should be fine
  3929  
  3930  	defer func() {
  3931  		if err := recover(); err == nil {
  3932  			t.Fatalf("no error")
  3933  		} else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
  3934  			t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
  3935  		}
  3936  	}()
  3937  	v.FieldByName("F") // should panic
  3938  
  3939  	t.Fatalf("did not panic")
  3940  }
  3941  
  3942  // Given
  3943  //	type Outer struct {
  3944  //		*Inner
  3945  //		...
  3946  //	}
  3947  // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
  3948  // The implementation is logically:
  3949  //	func (p *Outer) M() {
  3950  //		(p.Inner).M()
  3951  //	}
  3952  // but since the only change here is the replacement of one pointer receiver with another,
  3953  // the actual generated code overwrites the original receiver with the p.Inner pointer and
  3954  // then jumps to the M method expecting the *Inner receiver.
  3955  //
  3956  // During reflect.Value.Call, we create an argument frame and the associated data structures
  3957  // to describe it to the garbage collector, populate the frame, call reflect.call to
  3958  // run a function call using that frame, and then copy the results back out of the frame.
  3959  // The reflect.call function does a memmove of the frame structure onto the
  3960  // stack (to set up the inputs), runs the call, and the memmoves the stack back to
  3961  // the frame structure (to preserve the outputs).
  3962  //
  3963  // Originally reflect.call did not distinguish inputs from outputs: both memmoves
  3964  // were for the full stack frame. However, in the case where the called function was
  3965  // one of these wrappers, the rewritten receiver is almost certainly a different type
  3966  // than the original receiver. This is not a problem on the stack, where we use the
  3967  // program counter to determine the type information and understand that
  3968  // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
  3969  // memory word is now an *Inner. But in the statically typed argument frame created
  3970  // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
  3971  // off the stack into the frame will store an *Inner there, and then if a garbage collection
  3972  // happens to scan that argument frame before it is discarded, it will scan the *Inner
  3973  // memory as if it were an *Outer. If the two have different memory layouts, the
  3974  // collection will intepret the memory incorrectly.
  3975  //
  3976  // One such possible incorrect interpretation is to treat two arbitrary memory words
  3977  // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
  3978  // an interface requires dereferencing the itab word, the misinterpretation will try to
  3979  // deference Inner.P1, causing a crash during garbage collection.
  3980  //
  3981  // This came up in a real program in issue 7725.
  3982  
  3983  type Outer struct {
  3984  	*Inner
  3985  	R io.Reader
  3986  }
  3987  
  3988  type Inner struct {
  3989  	X  *Outer
  3990  	P1 uintptr
  3991  	P2 uintptr
  3992  }
  3993  
  3994  func (pi *Inner) M() {
  3995  	// Clear references to pi so that the only way the
  3996  	// garbage collection will find the pointer is in the
  3997  	// argument frame, typed as a *Outer.
  3998  	pi.X.Inner = nil
  3999  
  4000  	// Set up an interface value that will cause a crash.
  4001  	// P1 = 1 is a non-zero, so the interface looks non-nil.
  4002  	// P2 = pi ensures that the data word points into the
  4003  	// allocated heap; if not the collection skips the interface
  4004  	// value as irrelevant, without dereferencing P1.
  4005  	pi.P1 = 1
  4006  	pi.P2 = uintptr(unsafe.Pointer(pi))
  4007  }
  4008  
  4009  func TestCallMethodJump(t *testing.T) {
  4010  	// In reflect.Value.Call, trigger a garbage collection after reflect.call
  4011  	// returns but before the args frame has been discarded.
  4012  	// This is a little clumsy but makes the failure repeatable.
  4013  	*CallGC = true
  4014  
  4015  	p := &Outer{Inner: new(Inner)}
  4016  	p.Inner.X = p
  4017  	ValueOf(p).Method(0).Call(nil)
  4018  
  4019  	// Stop garbage collecting during reflect.call.
  4020  	*CallGC = false
  4021  }
  4022  
  4023  func TestMakeFuncStackCopy(t *testing.T) {
  4024  	target := func(in []Value) []Value {
  4025  		runtime.GC()
  4026  		useStack(16)
  4027  		return []Value{ValueOf(9)}
  4028  	}
  4029  
  4030  	var concrete func(*int, int) int
  4031  	fn := MakeFunc(ValueOf(concrete).Type(), target)
  4032  	ValueOf(&concrete).Elem().Set(fn)
  4033  	x := concrete(nil, 7)
  4034  	if x != 9 {
  4035  		t.Errorf("have %#q want 9", x)
  4036  	}
  4037  }
  4038  
  4039  // use about n KB of stack
  4040  func useStack(n int) {
  4041  	if n == 0 {
  4042  		return
  4043  	}
  4044  	var b [1024]byte // makes frame about 1KB
  4045  	useStack(n - 1 + int(b[99]))
  4046  }
  4047  
  4048  type Impl struct{}
  4049  
  4050  func (Impl) f() {}
  4051  
  4052  func TestValueString(t *testing.T) {
  4053  	rv := ValueOf(Impl{})
  4054  	if rv.String() != "<reflect_test.Impl Value>" {
  4055  		t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
  4056  	}
  4057  
  4058  	method := rv.Method(0)
  4059  	if method.String() != "<func() Value>" {
  4060  		t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
  4061  	}
  4062  }
  4063  
  4064  func TestInvalid(t *testing.T) {
  4065  	// Used to have inconsistency between IsValid() and Kind() != Invalid.
  4066  	type T struct{ v interface{} }
  4067  
  4068  	v := ValueOf(T{}).Field(0)
  4069  	if v.IsValid() != true || v.Kind() != Interface {
  4070  		t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
  4071  	}
  4072  	v = v.Elem()
  4073  	if v.IsValid() != false || v.Kind() != Invalid {
  4074  		t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
  4075  	}
  4076  }
  4077  
  4078  // Issue 8917.
  4079  func TestLargeGCProg(t *testing.T) {
  4080  	fv := ValueOf(func([256]*byte) {})
  4081  	fv.Call([]Value{ValueOf([256]*byte{})})
  4082  }
  4083  
  4084  // Issue 9179.
  4085  func TestCallGC(t *testing.T) {
  4086  	f := func(a, b, c, d, e string) {
  4087  	}
  4088  	g := func(in []Value) []Value {
  4089  		runtime.GC()
  4090  		return nil
  4091  	}
  4092  	typ := ValueOf(f).Type()
  4093  	f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
  4094  	f2("four", "five5", "six666", "seven77", "eight888")
  4095  }
  4096  
  4097  type funcLayoutTest struct {
  4098  	rcvr, t                  Type
  4099  	size, argsize, retOffset uintptr
  4100  	stack                    []byte
  4101  	gc                       []byte
  4102  }
  4103  
  4104  var funcLayoutTests []funcLayoutTest
  4105  
  4106  func init() {
  4107  	var argAlign = PtrSize
  4108  	var naclExtra []byte
  4109  	if runtime.GOARCH == "amd64p32" {
  4110  		argAlign = 2 * PtrSize
  4111  		naclExtra = append(naclExtra, BitsScalar)
  4112  	}
  4113  	roundup := func(x uintptr, a uintptr) uintptr {
  4114  		return (x + a - 1) / a * a
  4115  	}
  4116  
  4117  	funcLayoutTests = append(funcLayoutTests,
  4118  		funcLayoutTest{
  4119  			nil,
  4120  			ValueOf(func(a, b string) string { return "" }).Type(),
  4121  			6 * PtrSize,
  4122  			4 * PtrSize,
  4123  			4 * PtrSize,
  4124  			[]byte{BitsPointer, BitsScalar, BitsPointer},
  4125  			[]byte{BitsPointer, BitsScalar, BitsPointer, BitsScalar, BitsPointer, BitsScalar},
  4126  		})
  4127  
  4128  	var r, s []byte
  4129  	if PtrSize == 4 {
  4130  		r = []byte{BitsScalar, BitsScalar, BitsScalar, BitsPointer}
  4131  		s = append([]byte{BitsScalar, BitsScalar, BitsScalar, BitsPointer, BitsScalar}, naclExtra...)
  4132  	} else {
  4133  		r = []byte{BitsScalar, BitsScalar, BitsPointer}
  4134  		s = []byte{BitsScalar, BitsScalar, BitsPointer, BitsScalar}
  4135  	}
  4136  	funcLayoutTests = append(funcLayoutTests,
  4137  		funcLayoutTest{
  4138  			nil,
  4139  			ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
  4140  			roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
  4141  			roundup(3*4, PtrSize) + PtrSize + 2,
  4142  			roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
  4143  			r,
  4144  			s,
  4145  		})
  4146  
  4147  	funcLayoutTests = append(funcLayoutTests,
  4148  		funcLayoutTest{
  4149  			nil,
  4150  			ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
  4151  			4 * PtrSize,
  4152  			4 * PtrSize,
  4153  			4 * PtrSize,
  4154  			[]byte{BitsPointer, BitsScalar, BitsPointer, BitsPointer},
  4155  			[]byte{BitsPointer, BitsScalar, BitsPointer, BitsPointer},
  4156  		})
  4157  
  4158  	type S struct {
  4159  		a, b uintptr
  4160  		c, d *byte
  4161  	}
  4162  	funcLayoutTests = append(funcLayoutTests,
  4163  		funcLayoutTest{
  4164  			nil,
  4165  			ValueOf(func(a S) {}).Type(),
  4166  			4 * PtrSize,
  4167  			4 * PtrSize,
  4168  			4 * PtrSize,
  4169  			[]byte{BitsScalar, BitsScalar, BitsPointer, BitsPointer},
  4170  			[]byte{BitsScalar, BitsScalar, BitsPointer, BitsPointer},
  4171  		})
  4172  
  4173  	funcLayoutTests = append(funcLayoutTests,
  4174  		funcLayoutTest{
  4175  			ValueOf((*byte)(nil)).Type(),
  4176  			ValueOf(func(a uintptr, b *int) {}).Type(),
  4177  			roundup(3*PtrSize, argAlign),
  4178  			3 * PtrSize,
  4179  			roundup(3*PtrSize, argAlign),
  4180  			[]byte{BitsPointer, BitsScalar, BitsPointer},
  4181  			append([]byte{BitsPointer, BitsScalar, BitsPointer}, naclExtra...),
  4182  		})
  4183  
  4184  	funcLayoutTests = append(funcLayoutTests,
  4185  		funcLayoutTest{
  4186  			nil,
  4187  			ValueOf(func(a uintptr) {}).Type(),
  4188  			roundup(PtrSize, argAlign),
  4189  			PtrSize,
  4190  			roundup(PtrSize, argAlign),
  4191  			[]byte{},
  4192  			append([]byte{BitsScalar}, naclExtra...),
  4193  		})
  4194  
  4195  	funcLayoutTests = append(funcLayoutTests,
  4196  		funcLayoutTest{
  4197  			nil,
  4198  			ValueOf(func() uintptr { return 0 }).Type(),
  4199  			PtrSize,
  4200  			0,
  4201  			0,
  4202  			[]byte{},
  4203  			[]byte{BitsScalar},
  4204  		})
  4205  
  4206  	funcLayoutTests = append(funcLayoutTests,
  4207  		funcLayoutTest{
  4208  			ValueOf(uintptr(0)).Type(),
  4209  			ValueOf(func(a uintptr) {}).Type(),
  4210  			2 * PtrSize,
  4211  			2 * PtrSize,
  4212  			2 * PtrSize,
  4213  			[]byte{BitsPointer},
  4214  			[]byte{BitsPointer, BitsScalar},
  4215  			// Note: this one is tricky, as the receiver is not a pointer.  But we
  4216  			// pass the receiver by reference to the autogenerated pointer-receiver
  4217  			// version of the function.
  4218  		})
  4219  }
  4220  
  4221  func TestFuncLayout(t *testing.T) {
  4222  	for _, lt := range funcLayoutTests {
  4223  		typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr)
  4224  		if typ.Size() != lt.size {
  4225  			t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size)
  4226  		}
  4227  		if argsize != lt.argsize {
  4228  			t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize)
  4229  		}
  4230  		if retOffset != lt.retOffset {
  4231  			t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset)
  4232  		}
  4233  		if !bytes.Equal(stack, lt.stack) {
  4234  			t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack)
  4235  		}
  4236  		if !bytes.Equal(gc, lt.gc) {
  4237  			t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc)
  4238  		}
  4239  		if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
  4240  			t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs)
  4241  		}
  4242  	}
  4243  }