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