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