Rebase.
[official-gcc.git] / libgo / go / reflect / all_test.go
blobf888d648c19b19ef8f6f6896a66cffd0d10e3e49
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.
5 package reflect_test
7 import (
8 "bytes"
9 "encoding/base64"
10 "flag"
11 "fmt"
12 "io"
13 "math/rand"
14 "os"
15 . "reflect"
16 "runtime"
17 "sort"
18 "strings"
19 "sync"
20 "testing"
21 "time"
22 "unsafe"
25 func TestBool(t *testing.T) {
26 v := ValueOf(true)
27 if v.Bool() != true {
28 t.Fatal("ValueOf(true).Bool() = false")
32 type integer int
33 type T struct {
34 a int
35 b float64
36 c string
37 d *int
40 type pair struct {
41 i interface{}
42 s string
45 func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
47 func assert(t *testing.T, s, want string) {
48 if s != want {
49 t.Errorf("have %#q want %#q", s, want)
53 func typestring(i interface{}) string { return TypeOf(i).String() }
55 var typeTests = []pair{
56 {struct{ x int }{}, "int"},
57 {struct{ x int8 }{}, "int8"},
58 {struct{ x int16 }{}, "int16"},
59 {struct{ x int32 }{}, "int32"},
60 {struct{ x int64 }{}, "int64"},
61 {struct{ x uint }{}, "uint"},
62 {struct{ x uint8 }{}, "uint8"},
63 {struct{ x uint16 }{}, "uint16"},
64 {struct{ x uint32 }{}, "uint32"},
65 {struct{ x uint64 }{}, "uint64"},
66 {struct{ x float32 }{}, "float32"},
67 {struct{ x float64 }{}, "float64"},
68 {struct{ x int8 }{}, "int8"},
69 {struct{ x (**int8) }{}, "**int8"},
70 {struct{ x (**integer) }{}, "**reflect_test.integer"},
71 {struct{ x ([32]int32) }{}, "[32]int32"},
72 {struct{ x ([]int8) }{}, "[]int8"},
73 {struct{ x (map[string]int32) }{}, "map[string]int32"},
74 {struct{ x (chan<- string) }{}, "chan<- string"},
75 {struct {
76 x struct {
77 c chan *int32
78 d float32
80 }{},
81 "struct { c chan *int32; d float32 }",
83 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
84 {struct {
85 x struct {
86 c func(chan *integer, *int8)
88 }{},
89 "struct { c func(chan *reflect_test.integer, *int8) }",
91 {struct {
92 x struct {
93 a int8
94 b int32
96 }{},
97 "struct { a int8; b int32 }",
99 {struct {
100 x struct {
101 a int8
102 b int8
103 c int32
105 }{},
106 "struct { a int8; b int8; c int32 }",
108 {struct {
109 x struct {
110 a int8
111 b int8
112 c int8
113 d int32
115 }{},
116 "struct { a int8; b int8; c int8; d int32 }",
118 {struct {
119 x struct {
120 a int8
121 b int8
122 c int8
123 d int8
124 e int32
126 }{},
127 "struct { a int8; b int8; c int8; d int8; e int32 }",
129 {struct {
130 x struct {
131 a int8
132 b int8
133 c int8
134 d int8
135 e int8
136 f int32
138 }{},
139 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
141 {struct {
142 x struct {
143 a int8 `reflect:"hi there"`
145 }{},
146 `struct { a int8 "reflect:\"hi there\"" }`,
148 {struct {
149 x struct {
150 a int8 `reflect:"hi \x00there\t\n\"\\"`
152 }{},
153 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
155 {struct {
156 x struct {
157 f func(args ...int)
159 }{},
160 "struct { f func(...int) }",
162 {struct {
163 x (interface {
164 a(func(func(int) int) func(func(int)) int)
167 }{},
168 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
172 var valueTests = []pair{
173 {new(int), "132"},
174 {new(int8), "8"},
175 {new(int16), "16"},
176 {new(int32), "32"},
177 {new(int64), "64"},
178 {new(uint), "132"},
179 {new(uint8), "8"},
180 {new(uint16), "16"},
181 {new(uint32), "32"},
182 {new(uint64), "64"},
183 {new(float32), "256.25"},
184 {new(float64), "512.125"},
185 {new(complex64), "532.125+10i"},
186 {new(complex128), "564.25+1i"},
187 {new(string), "stringy cheese"},
188 {new(bool), "true"},
189 {new(*int8), "*int8(0)"},
190 {new(**int8), "**int8(0)"},
191 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
192 {new(**integer), "**reflect_test.integer(0)"},
193 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
194 {new(chan<- string), "chan<- string"},
195 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
196 {new(struct {
197 c chan *int32
198 d float32
200 "struct { c chan *int32; d float32 }{chan *int32, 0}",
202 {new(struct{ c func(chan *integer, *int8) }),
203 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
205 {new(struct {
206 a int8
207 b int32
209 "struct { a int8; b int32 }{0, 0}",
211 {new(struct {
212 a int8
213 b int8
214 c int32
216 "struct { a int8; b int8; c int32 }{0, 0, 0}",
220 func testType(t *testing.T, i int, typ Type, want string) {
221 s := typ.String()
222 if s != want {
223 t.Errorf("#%d: have %#q, want %#q", i, s, want)
227 func TestTypes(t *testing.T) {
228 for i, tt := range typeTests {
229 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
233 func TestSet(t *testing.T) {
234 for i, tt := range valueTests {
235 v := ValueOf(tt.i)
236 v = v.Elem()
237 switch v.Kind() {
238 case Int:
239 v.SetInt(132)
240 case Int8:
241 v.SetInt(8)
242 case Int16:
243 v.SetInt(16)
244 case Int32:
245 v.SetInt(32)
246 case Int64:
247 v.SetInt(64)
248 case Uint:
249 v.SetUint(132)
250 case Uint8:
251 v.SetUint(8)
252 case Uint16:
253 v.SetUint(16)
254 case Uint32:
255 v.SetUint(32)
256 case Uint64:
257 v.SetUint(64)
258 case Float32:
259 v.SetFloat(256.25)
260 case Float64:
261 v.SetFloat(512.125)
262 case Complex64:
263 v.SetComplex(532.125 + 10i)
264 case Complex128:
265 v.SetComplex(564.25 + 1i)
266 case String:
267 v.SetString("stringy cheese")
268 case Bool:
269 v.SetBool(true)
271 s := valueToString(v)
272 if s != tt.s {
273 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
278 func TestSetValue(t *testing.T) {
279 for i, tt := range valueTests {
280 v := ValueOf(tt.i).Elem()
281 switch v.Kind() {
282 case Int:
283 v.Set(ValueOf(int(132)))
284 case Int8:
285 v.Set(ValueOf(int8(8)))
286 case Int16:
287 v.Set(ValueOf(int16(16)))
288 case Int32:
289 v.Set(ValueOf(int32(32)))
290 case Int64:
291 v.Set(ValueOf(int64(64)))
292 case Uint:
293 v.Set(ValueOf(uint(132)))
294 case Uint8:
295 v.Set(ValueOf(uint8(8)))
296 case Uint16:
297 v.Set(ValueOf(uint16(16)))
298 case Uint32:
299 v.Set(ValueOf(uint32(32)))
300 case Uint64:
301 v.Set(ValueOf(uint64(64)))
302 case Float32:
303 v.Set(ValueOf(float32(256.25)))
304 case Float64:
305 v.Set(ValueOf(512.125))
306 case Complex64:
307 v.Set(ValueOf(complex64(532.125 + 10i)))
308 case Complex128:
309 v.Set(ValueOf(complex128(564.25 + 1i)))
310 case String:
311 v.Set(ValueOf("stringy cheese"))
312 case Bool:
313 v.Set(ValueOf(true))
315 s := valueToString(v)
316 if s != tt.s {
317 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
322 var _i = 7
324 var valueToStringTests = []pair{
325 {123, "123"},
326 {123.5, "123.5"},
327 {byte(123), "123"},
328 {"abc", "abc"},
329 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
330 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
331 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
332 {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
333 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
334 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
337 func TestValueToString(t *testing.T) {
338 for i, test := range valueToStringTests {
339 s := valueToString(ValueOf(test.i))
340 if s != test.s {
341 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
346 func TestArrayElemSet(t *testing.T) {
347 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
348 v.Index(4).SetInt(123)
349 s := valueToString(v)
350 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
351 if s != want {
352 t.Errorf("[10]int: have %#q want %#q", s, want)
355 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
356 v.Index(4).SetInt(123)
357 s = valueToString(v)
358 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
359 if s != want1 {
360 t.Errorf("[]int: have %#q want %#q", s, want1)
364 func TestPtrPointTo(t *testing.T) {
365 var ip *int32
366 var i int32 = 1234
367 vip := ValueOf(&ip)
368 vi := ValueOf(&i).Elem()
369 vip.Elem().Set(vi.Addr())
370 if *ip != 1234 {
371 t.Errorf("got %d, want 1234", *ip)
374 ip = nil
375 vp := ValueOf(&ip).Elem()
376 vp.Set(Zero(vp.Type()))
377 if ip != nil {
378 t.Errorf("got non-nil (%p), want nil", ip)
382 func TestPtrSetNil(t *testing.T) {
383 var i int32 = 1234
384 ip := &i
385 vip := ValueOf(&ip)
386 vip.Elem().Set(Zero(vip.Elem().Type()))
387 if ip != nil {
388 t.Errorf("got non-nil (%d), want nil", *ip)
392 func TestMapSetNil(t *testing.T) {
393 m := make(map[string]int)
394 vm := ValueOf(&m)
395 vm.Elem().Set(Zero(vm.Elem().Type()))
396 if m != nil {
397 t.Errorf("got non-nil (%p), want nil", m)
401 func TestAll(t *testing.T) {
402 testType(t, 1, TypeOf((int8)(0)), "int8")
403 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
405 typ := TypeOf((*struct {
406 c chan *int32
407 d float32
408 })(nil))
409 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
410 etyp := typ.Elem()
411 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
412 styp := etyp
413 f := styp.Field(0)
414 testType(t, 5, f.Type, "chan *int32")
416 f, present := styp.FieldByName("d")
417 if !present {
418 t.Errorf("FieldByName says present field is absent")
420 testType(t, 6, f.Type, "float32")
422 f, present = styp.FieldByName("absent")
423 if present {
424 t.Errorf("FieldByName says absent field is present")
427 typ = TypeOf([32]int32{})
428 testType(t, 7, typ, "[32]int32")
429 testType(t, 8, typ.Elem(), "int32")
431 typ = TypeOf((map[string]*int32)(nil))
432 testType(t, 9, typ, "map[string]*int32")
433 mtyp := typ
434 testType(t, 10, mtyp.Key(), "string")
435 testType(t, 11, mtyp.Elem(), "*int32")
437 typ = TypeOf((chan<- string)(nil))
438 testType(t, 12, typ, "chan<- string")
439 testType(t, 13, typ.Elem(), "string")
441 // make sure tag strings are not part of element type
442 typ = TypeOf(struct {
443 d []uint32 `reflect:"TAG"`
444 }{}).Field(0).Type
445 testType(t, 14, typ, "[]uint32")
448 func TestInterfaceGet(t *testing.T) {
449 var inter struct {
450 E interface{}
452 inter.E = 123.456
453 v1 := ValueOf(&inter)
454 v2 := v1.Elem().Field(0)
455 assert(t, v2.Type().String(), "interface {}")
456 i2 := v2.Interface()
457 v3 := ValueOf(i2)
458 assert(t, v3.Type().String(), "float64")
461 func TestInterfaceValue(t *testing.T) {
462 var inter struct {
463 E interface{}
465 inter.E = 123.456
466 v1 := ValueOf(&inter)
467 v2 := v1.Elem().Field(0)
468 assert(t, v2.Type().String(), "interface {}")
469 v3 := v2.Elem()
470 assert(t, v3.Type().String(), "float64")
472 i3 := v2.Interface()
473 if _, ok := i3.(float64); !ok {
474 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
478 func TestFunctionValue(t *testing.T) {
479 var x interface{} = func() {}
480 v := ValueOf(x)
481 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
482 t.Fatalf("TestFunction returned wrong pointer")
484 assert(t, v.Type().String(), "func()")
487 var appendTests = []struct {
488 orig, extra []int
490 {make([]int, 2, 4), []int{22}},
491 {make([]int, 2, 4), []int{22, 33, 44}},
494 func sameInts(x, y []int) bool {
495 if len(x) != len(y) {
496 return false
498 for i, xx := range x {
499 if xx != y[i] {
500 return false
503 return true
506 func TestAppend(t *testing.T) {
507 for i, test := range appendTests {
508 origLen, extraLen := len(test.orig), len(test.extra)
509 want := append(test.orig, test.extra...)
510 // Convert extra from []int to []Value.
511 e0 := make([]Value, len(test.extra))
512 for j, e := range test.extra {
513 e0[j] = ValueOf(e)
515 // Convert extra from []int to *SliceValue.
516 e1 := ValueOf(test.extra)
517 // Test Append.
518 a0 := ValueOf(test.orig)
519 have0 := Append(a0, e0...).Interface().([]int)
520 if !sameInts(have0, want) {
521 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
523 // Check that the orig and extra slices were not modified.
524 if len(test.orig) != origLen {
525 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
527 if len(test.extra) != extraLen {
528 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
530 // Test AppendSlice.
531 a1 := ValueOf(test.orig)
532 have1 := AppendSlice(a1, e1).Interface().([]int)
533 if !sameInts(have1, want) {
534 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
536 // Check that the orig and extra slices were not modified.
537 if len(test.orig) != origLen {
538 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
540 if len(test.extra) != extraLen {
541 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
546 func TestCopy(t *testing.T) {
547 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
548 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
549 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
550 for i := 0; i < len(b); i++ {
551 if b[i] != c[i] {
552 t.Fatalf("b != c before test")
555 a1 := a
556 b1 := b
557 aa := ValueOf(&a1).Elem()
558 ab := ValueOf(&b1).Elem()
559 for tocopy := 1; tocopy <= 7; tocopy++ {
560 aa.SetLen(tocopy)
561 Copy(ab, aa)
562 aa.SetLen(8)
563 for i := 0; i < tocopy; i++ {
564 if a[i] != b[i] {
565 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
566 tocopy, i, a[i], i, b[i])
569 for i := tocopy; i < len(b); i++ {
570 if b[i] != c[i] {
571 if i < len(a) {
572 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
573 tocopy, i, a[i], i, b[i], i, c[i])
574 } else {
575 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
576 tocopy, i, b[i], i, c[i])
578 } else {
579 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
585 func TestCopyArray(t *testing.T) {
586 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
587 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
588 c := b
589 aa := ValueOf(&a).Elem()
590 ab := ValueOf(&b).Elem()
591 Copy(ab, aa)
592 for i := 0; i < len(a); i++ {
593 if a[i] != b[i] {
594 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
597 for i := len(a); i < len(b); i++ {
598 if b[i] != c[i] {
599 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
600 } else {
601 t.Logf("elem %d is okay\n", i)
606 func TestBigUnnamedStruct(t *testing.T) {
607 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
608 v := ValueOf(b)
609 b1 := v.Interface().(struct {
610 a, b, c, d int64
612 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
613 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
617 type big struct {
618 a, b, c, d, e int64
621 func TestBigStruct(t *testing.T) {
622 b := big{1, 2, 3, 4, 5}
623 v := ValueOf(b)
624 b1 := v.Interface().(big)
625 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
626 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
630 type Basic struct {
631 x int
632 y float32
635 type NotBasic Basic
637 type DeepEqualTest struct {
638 a, b interface{}
639 eq bool
642 // Simple functions for DeepEqual tests.
643 var (
644 fn1 func() // nil.
645 fn2 func() // nil.
646 fn3 = func() { fn1() } // Not nil.
649 var deepEqualTests = []DeepEqualTest{
650 // Equalities
651 {nil, nil, true},
652 {1, 1, true},
653 {int32(1), int32(1), true},
654 {0.5, 0.5, true},
655 {float32(0.5), float32(0.5), true},
656 {"hello", "hello", true},
657 {make([]int, 10), make([]int, 10), true},
658 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
659 {Basic{1, 0.5}, Basic{1, 0.5}, true},
660 {error(nil), error(nil), true},
661 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
662 {fn1, fn2, true},
664 // Inequalities
665 {1, 2, false},
666 {int32(1), int32(2), false},
667 {0.5, 0.6, false},
668 {float32(0.5), float32(0.6), false},
669 {"hello", "hey", false},
670 {make([]int, 10), make([]int, 11), false},
671 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
672 {Basic{1, 0.5}, Basic{1, 0.6}, false},
673 {Basic{1, 0}, Basic{2, 0}, false},
674 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
675 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
676 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
677 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
678 {nil, 1, false},
679 {1, nil, false},
680 {fn1, fn3, false},
681 {fn3, fn3, false},
682 {[][]int{[]int{1}}, [][]int{[]int{2}}, false},
684 // Nil vs empty: not the same.
685 {[]int{}, []int(nil), false},
686 {[]int{}, []int{}, true},
687 {[]int(nil), []int(nil), true},
688 {map[int]int{}, map[int]int(nil), false},
689 {map[int]int{}, map[int]int{}, true},
690 {map[int]int(nil), map[int]int(nil), true},
692 // Mismatched types
693 {1, 1.0, false},
694 {int32(1), int64(1), false},
695 {0.5, "hello", false},
696 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
697 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
698 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
699 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
702 func TestDeepEqual(t *testing.T) {
703 for _, test := range deepEqualTests {
704 if r := DeepEqual(test.a, test.b); r != test.eq {
705 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
710 func TestTypeOf(t *testing.T) {
711 // Special case for nil
712 if typ := TypeOf(nil); typ != nil {
713 t.Errorf("expected nil type for nil value; got %v", typ)
715 for _, test := range deepEqualTests {
716 v := ValueOf(test.a)
717 if !v.IsValid() {
718 continue
720 typ := TypeOf(test.a)
721 if typ != v.Type() {
722 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
727 type Recursive struct {
728 x int
729 r *Recursive
732 func TestDeepEqualRecursiveStruct(t *testing.T) {
733 a, b := new(Recursive), new(Recursive)
734 *a = Recursive{12, a}
735 *b = Recursive{12, b}
736 if !DeepEqual(a, b) {
737 t.Error("DeepEqual(recursive same) = false, want true")
741 type _Complex struct {
742 a int
743 b [3]*_Complex
744 c *string
745 d map[float64]float64
748 func TestDeepEqualComplexStruct(t *testing.T) {
749 m := make(map[float64]float64)
750 stra, strb := "hello", "hello"
751 a, b := new(_Complex), new(_Complex)
752 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
753 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
754 if !DeepEqual(a, b) {
755 t.Error("DeepEqual(complex same) = false, want true")
759 func TestDeepEqualComplexStructInequality(t *testing.T) {
760 m := make(map[float64]float64)
761 stra, strb := "hello", "helloo" // Difference is here
762 a, b := new(_Complex), new(_Complex)
763 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
764 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
765 if DeepEqual(a, b) {
766 t.Error("DeepEqual(complex different) = true, want false")
770 type UnexpT struct {
771 m map[int]int
774 func TestDeepEqualUnexportedMap(t *testing.T) {
775 // Check that DeepEqual can look at unexported fields.
776 x1 := UnexpT{map[int]int{1: 2}}
777 x2 := UnexpT{map[int]int{1: 2}}
778 if !DeepEqual(&x1, &x2) {
779 t.Error("DeepEqual(x1, x2) = false, want true")
782 y1 := UnexpT{map[int]int{2: 3}}
783 if DeepEqual(&x1, &y1) {
784 t.Error("DeepEqual(x1, y1) = true, want false")
788 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
789 s := ValueOf(x)
790 f := s.Type().Field(1)
791 if f.Offset != offs {
792 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
796 // Check that structure alignment & offsets viewed through reflect agree with those
797 // from the compiler itself.
798 func TestAlignment(t *testing.T) {
799 type T1inner struct {
800 a int
802 type T1 struct {
803 T1inner
804 f int
806 type T2inner struct {
807 a, b int
809 type T2 struct {
810 T2inner
811 f int
814 x := T1{T1inner{2}, 17}
815 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
817 x1 := T2{T2inner{2, 3}, 17}
818 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
821 func Nil(a interface{}, t *testing.T) {
822 n := ValueOf(a).Field(0)
823 if !n.IsNil() {
824 t.Errorf("%v should be nil", a)
828 func NotNil(a interface{}, t *testing.T) {
829 n := ValueOf(a).Field(0)
830 if n.IsNil() {
831 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
835 func TestIsNil(t *testing.T) {
836 // These implement IsNil.
837 // Wrap in extra struct to hide interface type.
838 doNil := []interface{}{
839 struct{ x *int }{},
840 struct{ x interface{} }{},
841 struct{ x map[string]int }{},
842 struct{ x func() bool }{},
843 struct{ x chan int }{},
844 struct{ x []string }{},
846 for _, ts := range doNil {
847 ty := TypeOf(ts).Field(0).Type
848 v := Zero(ty)
849 v.IsNil() // panics if not okay to call
852 // Check the implementations
853 var pi struct {
854 x *int
856 Nil(pi, t)
857 pi.x = new(int)
858 NotNil(pi, t)
860 var si struct {
861 x []int
863 Nil(si, t)
864 si.x = make([]int, 10)
865 NotNil(si, t)
867 var ci struct {
868 x chan int
870 Nil(ci, t)
871 ci.x = make(chan int)
872 NotNil(ci, t)
874 var mi struct {
875 x map[int]int
877 Nil(mi, t)
878 mi.x = make(map[int]int)
879 NotNil(mi, t)
881 var ii struct {
882 x interface{}
884 Nil(ii, t)
885 ii.x = 2
886 NotNil(ii, t)
888 var fi struct {
889 x func(t *testing.T)
891 Nil(fi, t)
892 fi.x = TestIsNil
893 NotNil(fi, t)
896 func TestInterfaceExtraction(t *testing.T) {
897 var s struct {
898 W io.Writer
901 s.W = os.Stdout
902 v := Indirect(ValueOf(&s)).Field(0).Interface()
903 if v != s.W.(interface{}) {
904 t.Error("Interface() on interface: ", v, s.W)
908 func TestNilPtrValueSub(t *testing.T) {
909 var pi *int
910 if pv := ValueOf(pi); pv.Elem().IsValid() {
911 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
915 func TestMap(t *testing.T) {
916 m := map[string]int{"a": 1, "b": 2}
917 mv := ValueOf(m)
918 if n := mv.Len(); n != len(m) {
919 t.Errorf("Len = %d, want %d", n, len(m))
921 keys := mv.MapKeys()
922 newmap := MakeMap(mv.Type())
923 for k, v := range m {
924 // Check that returned Keys match keys in range.
925 // These aren't required to be in the same order.
926 seen := false
927 for _, kv := range keys {
928 if kv.String() == k {
929 seen = true
930 break
933 if !seen {
934 t.Errorf("Missing key %q", k)
937 // Check that value lookup is correct.
938 vv := mv.MapIndex(ValueOf(k))
939 if vi := vv.Int(); vi != int64(v) {
940 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
943 // Copy into new map.
944 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
946 vv := mv.MapIndex(ValueOf("not-present"))
947 if vv.IsValid() {
948 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
951 newm := newmap.Interface().(map[string]int)
952 if len(newm) != len(m) {
953 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
956 for k, v := range newm {
957 mv, ok := m[k]
958 if mv != v {
959 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
963 newmap.SetMapIndex(ValueOf("a"), Value{})
964 v, ok := newm["a"]
965 if ok {
966 t.Errorf("newm[\"a\"] = %d after delete", v)
969 mv = ValueOf(&m).Elem()
970 mv.Set(Zero(mv.Type()))
971 if m != nil {
972 t.Errorf("mv.Set(nil) failed")
976 func TestNilMap(t *testing.T) {
977 var m map[string]int
978 mv := ValueOf(m)
979 keys := mv.MapKeys()
980 if len(keys) != 0 {
981 t.Errorf(">0 keys for nil map: %v", keys)
984 // Check that value for missing key is zero.
985 x := mv.MapIndex(ValueOf("hello"))
986 if x.Kind() != Invalid {
987 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
990 // Check big value too.
991 var mbig map[string][10 << 20]byte
992 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
993 if x.Kind() != Invalid {
994 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
997 // Test that deletes from a nil map succeed.
998 mv.SetMapIndex(ValueOf("hi"), Value{})
1001 func TestChan(t *testing.T) {
1002 for loop := 0; loop < 2; loop++ {
1003 var c chan int
1004 var cv Value
1006 // check both ways to allocate channels
1007 switch loop {
1008 case 1:
1009 c = make(chan int, 1)
1010 cv = ValueOf(c)
1011 case 0:
1012 cv = MakeChan(TypeOf(c), 1)
1013 c = cv.Interface().(chan int)
1016 // Send
1017 cv.Send(ValueOf(2))
1018 if i := <-c; i != 2 {
1019 t.Errorf("reflect Send 2, native recv %d", i)
1022 // Recv
1023 c <- 3
1024 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1025 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1028 // TryRecv fail
1029 val, ok := cv.TryRecv()
1030 if val.IsValid() || ok {
1031 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1034 // TryRecv success
1035 c <- 4
1036 val, ok = cv.TryRecv()
1037 if !val.IsValid() {
1038 t.Errorf("TryRecv on ready chan got nil")
1039 } else if i := val.Int(); i != 4 || !ok {
1040 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1043 // TrySend fail
1044 c <- 100
1045 ok = cv.TrySend(ValueOf(5))
1046 i := <-c
1047 if ok {
1048 t.Errorf("TrySend on full chan succeeded: value %d", i)
1051 // TrySend success
1052 ok = cv.TrySend(ValueOf(6))
1053 if !ok {
1054 t.Errorf("TrySend on empty chan failed")
1055 } else {
1056 if i = <-c; i != 6 {
1057 t.Errorf("TrySend 6, recv %d", i)
1061 // Close
1062 c <- 123
1063 cv.Close()
1064 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1065 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1067 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1068 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1072 // check creation of unbuffered channel
1073 var c chan int
1074 cv := MakeChan(TypeOf(c), 0)
1075 c = cv.Interface().(chan int)
1076 if cv.TrySend(ValueOf(7)) {
1077 t.Errorf("TrySend on sync chan succeeded")
1079 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1080 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1083 // len/cap
1084 cv = MakeChan(TypeOf(c), 10)
1085 c = cv.Interface().(chan int)
1086 for i := 0; i < 3; i++ {
1087 c <- i
1089 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1090 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1094 // caseInfo describes a single case in a select test.
1095 type caseInfo struct {
1096 desc string
1097 canSelect bool
1098 recv Value
1099 closed bool
1100 helper func()
1101 panic bool
1104 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1106 func TestSelect(t *testing.T) {
1107 selectWatch.once.Do(func() { go selectWatcher() })
1109 var x exhaustive
1110 nch := 0
1111 newop := func(n int, cap int) (ch, val Value) {
1112 nch++
1113 if nch%101%2 == 1 {
1114 c := make(chan int, cap)
1115 ch = ValueOf(c)
1116 val = ValueOf(n)
1117 } else {
1118 c := make(chan string, cap)
1119 ch = ValueOf(c)
1120 val = ValueOf(fmt.Sprint(n))
1122 return
1125 for n := 0; x.Next(); n++ {
1126 if testing.Short() && n >= 1000 {
1127 break
1129 if n >= 100000 && !*allselect {
1130 break
1132 if n%100000 == 0 && testing.Verbose() {
1133 println("TestSelect", n)
1135 var cases []SelectCase
1136 var info []caseInfo
1138 // Ready send.
1139 if x.Maybe() {
1140 ch, val := newop(len(cases), 1)
1141 cases = append(cases, SelectCase{
1142 Dir: SelectSend,
1143 Chan: ch,
1144 Send: val,
1146 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1149 // Ready recv.
1150 if x.Maybe() {
1151 ch, val := newop(len(cases), 1)
1152 ch.Send(val)
1153 cases = append(cases, SelectCase{
1154 Dir: SelectRecv,
1155 Chan: ch,
1157 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1160 // Blocking send.
1161 if x.Maybe() {
1162 ch, val := newop(len(cases), 0)
1163 cases = append(cases, SelectCase{
1164 Dir: SelectSend,
1165 Chan: ch,
1166 Send: val,
1168 // Let it execute?
1169 if x.Maybe() {
1170 f := func() { ch.Recv() }
1171 info = append(info, caseInfo{desc: "blocking send", helper: f})
1172 } else {
1173 info = append(info, caseInfo{desc: "blocking send"})
1177 // Blocking recv.
1178 if x.Maybe() {
1179 ch, val := newop(len(cases), 0)
1180 cases = append(cases, SelectCase{
1181 Dir: SelectRecv,
1182 Chan: ch,
1184 // Let it execute?
1185 if x.Maybe() {
1186 f := func() { ch.Send(val) }
1187 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1188 } else {
1189 info = append(info, caseInfo{desc: "blocking recv"})
1193 // Zero Chan send.
1194 if x.Maybe() {
1195 // Maybe include value to send.
1196 var val Value
1197 if x.Maybe() {
1198 val = ValueOf(100)
1200 cases = append(cases, SelectCase{
1201 Dir: SelectSend,
1202 Send: val,
1204 info = append(info, caseInfo{desc: "zero Chan send"})
1207 // Zero Chan receive.
1208 if x.Maybe() {
1209 cases = append(cases, SelectCase{
1210 Dir: SelectRecv,
1212 info = append(info, caseInfo{desc: "zero Chan recv"})
1215 // nil Chan send.
1216 if x.Maybe() {
1217 cases = append(cases, SelectCase{
1218 Dir: SelectSend,
1219 Chan: ValueOf((chan int)(nil)),
1220 Send: ValueOf(101),
1222 info = append(info, caseInfo{desc: "nil Chan send"})
1225 // nil Chan recv.
1226 if x.Maybe() {
1227 cases = append(cases, SelectCase{
1228 Dir: SelectRecv,
1229 Chan: ValueOf((chan int)(nil)),
1231 info = append(info, caseInfo{desc: "nil Chan recv"})
1234 // closed Chan send.
1235 if x.Maybe() {
1236 ch := make(chan int)
1237 close(ch)
1238 cases = append(cases, SelectCase{
1239 Dir: SelectSend,
1240 Chan: ValueOf(ch),
1241 Send: ValueOf(101),
1243 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1246 // closed Chan recv.
1247 if x.Maybe() {
1248 ch, val := newop(len(cases), 0)
1249 ch.Close()
1250 val = Zero(val.Type())
1251 cases = append(cases, SelectCase{
1252 Dir: SelectRecv,
1253 Chan: ch,
1255 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1258 var helper func() // goroutine to help the select complete
1260 // Add default? Must be last case here, but will permute.
1261 // Add the default if the select would otherwise
1262 // block forever, and maybe add it anyway.
1263 numCanSelect := 0
1264 canProceed := false
1265 canBlock := true
1266 canPanic := false
1267 helpers := []int{}
1268 for i, c := range info {
1269 if c.canSelect {
1270 canProceed = true
1271 canBlock = false
1272 numCanSelect++
1273 if c.panic {
1274 canPanic = true
1276 } else if c.helper != nil {
1277 canProceed = true
1278 helpers = append(helpers, i)
1281 if !canProceed || x.Maybe() {
1282 cases = append(cases, SelectCase{
1283 Dir: SelectDefault,
1285 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1286 numCanSelect++
1287 } else if canBlock {
1288 // Select needs to communicate with another goroutine.
1289 cas := &info[helpers[x.Choose(len(helpers))]]
1290 helper = cas.helper
1291 cas.canSelect = true
1292 numCanSelect++
1295 // Permute cases and case info.
1296 // Doing too much here makes the exhaustive loop
1297 // too exhausting, so just do two swaps.
1298 for loop := 0; loop < 2; loop++ {
1299 i := x.Choose(len(cases))
1300 j := x.Choose(len(cases))
1301 cases[i], cases[j] = cases[j], cases[i]
1302 info[i], info[j] = info[j], info[i]
1305 if helper != nil {
1306 // We wait before kicking off a goroutine to satisfy a blocked select.
1307 // The pause needs to be big enough to let the select block before
1308 // we run the helper, but if we lose that race once in a while it's okay: the
1309 // select will just proceed immediately. Not a big deal.
1310 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1311 pause := 10 * time.Microsecond
1312 if testing.Short() {
1313 pause = 100 * time.Microsecond
1315 time.AfterFunc(pause, helper)
1318 // Run select.
1319 i, recv, recvOK, panicErr := runSelect(cases, info)
1320 if panicErr != nil && !canPanic {
1321 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1323 if panicErr == nil && canPanic && numCanSelect == 1 {
1324 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1326 if panicErr != nil {
1327 continue
1330 cas := info[i]
1331 if !cas.canSelect {
1332 recvStr := ""
1333 if recv.IsValid() {
1334 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1336 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1337 continue
1339 if cas.panic {
1340 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1341 continue
1344 if cases[i].Dir == SelectRecv {
1345 if !recv.IsValid() {
1346 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1348 if !cas.recv.IsValid() {
1349 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1351 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1352 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1353 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1355 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1357 } else {
1358 if recv.IsValid() || recvOK {
1359 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1365 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1366 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1367 // an error describing the select and panics the entire test binary.
1368 var selectWatch struct {
1369 sync.Mutex
1370 once sync.Once
1371 now time.Time
1372 info []caseInfo
1375 func selectWatcher() {
1376 for {
1377 time.Sleep(1 * time.Second)
1378 selectWatch.Lock()
1379 if selectWatch.info != nil && time.Since(selectWatch.now) > 1*time.Second {
1380 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1381 panic("select stuck")
1383 selectWatch.Unlock()
1387 // runSelect runs a single select test.
1388 // It returns the values returned by Select but also returns
1389 // a panic value if the Select panics.
1390 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1391 defer func() {
1392 panicErr = recover()
1394 selectWatch.Lock()
1395 selectWatch.info = nil
1396 selectWatch.Unlock()
1399 selectWatch.Lock()
1400 selectWatch.now = time.Now()
1401 selectWatch.info = info
1402 selectWatch.Unlock()
1404 chosen, recv, recvOK = Select(cases)
1405 return
1408 // fmtSelect formats the information about a single select test.
1409 func fmtSelect(info []caseInfo) string {
1410 var buf bytes.Buffer
1411 fmt.Fprintf(&buf, "\nselect {\n")
1412 for i, cas := range info {
1413 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1414 if cas.recv.IsValid() {
1415 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1417 if cas.canSelect {
1418 fmt.Fprintf(&buf, " canselect")
1420 if cas.panic {
1421 fmt.Fprintf(&buf, " panic")
1423 fmt.Fprintf(&buf, "\n")
1425 fmt.Fprintf(&buf, "}")
1426 return buf.String()
1429 type two [2]uintptr
1431 // Difficult test for function call because of
1432 // implicit padding between arguments.
1433 func dummy(b byte, c int, d byte, e two, f byte, g float32, h byte) (i byte, j int, k byte, l two, m byte, n float32, o byte) {
1434 return b, c, d, e, f, g, h
1437 func TestFunc(t *testing.T) {
1438 ret := ValueOf(dummy).Call([]Value{
1439 ValueOf(byte(10)),
1440 ValueOf(20),
1441 ValueOf(byte(30)),
1442 ValueOf(two{40, 50}),
1443 ValueOf(byte(60)),
1444 ValueOf(float32(70)),
1445 ValueOf(byte(80)),
1447 if len(ret) != 7 {
1448 t.Fatalf("Call returned %d values, want 7", len(ret))
1451 i := byte(ret[0].Uint())
1452 j := int(ret[1].Int())
1453 k := byte(ret[2].Uint())
1454 l := ret[3].Interface().(two)
1455 m := byte(ret[4].Uint())
1456 n := float32(ret[5].Float())
1457 o := byte(ret[6].Uint())
1459 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1460 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1464 type emptyStruct struct{}
1466 type nonEmptyStruct struct {
1467 member int
1470 func returnEmpty() emptyStruct {
1471 return emptyStruct{}
1474 func takesEmpty(e emptyStruct) {
1477 func returnNonEmpty(i int) nonEmptyStruct {
1478 return nonEmptyStruct{member: i}
1481 func takesNonEmpty(n nonEmptyStruct) int {
1482 return n.member
1485 func TestCallWithStruct(t *testing.T) {
1486 r := ValueOf(returnEmpty).Call(nil)
1487 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1488 t.Errorf("returning empty struct returned %#v instead", r)
1490 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1491 if len(r) != 0 {
1492 t.Errorf("takesEmpty returned values: %#v", r)
1494 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1495 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1496 t.Errorf("returnNonEmpty returned %#v", r)
1498 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1499 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1500 t.Errorf("takesNonEmpty returned %#v", r)
1504 func TestMakeFunc(t *testing.T) {
1505 f := dummy
1506 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1507 ValueOf(&f).Elem().Set(fv)
1509 // Call g with small arguments so that there is
1510 // something predictable (and different from the
1511 // correct results) in those positions on the stack.
1512 g := dummy
1513 g(1, 2, 3, two{4, 5}, 6, 7, 8)
1515 // Call constructed function f.
1516 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
1517 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1518 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1522 func TestMakeFuncInterface(t *testing.T) {
1523 fn := func(i int) int { return i }
1524 incr := func(in []Value) []Value {
1525 return []Value{ValueOf(int(in[0].Int() + 1))}
1527 fv := MakeFunc(TypeOf(fn), incr)
1528 ValueOf(&fn).Elem().Set(fv)
1529 if r := fn(2); r != 3 {
1530 t.Errorf("Call returned %d, want 3", r)
1532 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
1533 t.Errorf("Call returned %d, want 15", r)
1535 if r := fv.Interface().(func(int) int)(26); r != 27 {
1536 t.Errorf("Call returned %d, want 27", r)
1540 func TestMakeFuncVariadic(t *testing.T) {
1541 // Test that variadic arguments are packed into a slice and passed as last arg
1542 fn := func(_ int, is ...int) []int { return nil }
1543 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
1544 ValueOf(&fn).Elem().Set(fv)
1546 r := fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
1547 if r[0] != 2 || r[1] != 3 {
1548 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1551 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1552 if r[0] != 2 || r[1] != 3 {
1553 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1557 type Point struct {
1558 x, y int
1561 // This will be index 0.
1562 func (p Point) AnotherMethod(scale int) int {
1563 return -1
1566 // This will be index 1.
1567 func (p Point) Dist(scale int) int {
1568 //println("Point.Dist", p.x, p.y, scale)
1569 return p.x*p.x*scale + p.y*p.y*scale
1572 func TestMethod(t *testing.T) {
1573 // Non-curried method of type.
1574 p := Point{3, 4}
1575 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1576 if i != 250 {
1577 t.Errorf("Type Method returned %d; want 250", i)
1580 m, ok := TypeOf(p).MethodByName("Dist")
1581 if !ok {
1582 t.Fatalf("method by name failed")
1584 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
1585 if i != 275 {
1586 t.Errorf("Type MethodByName returned %d; want 275", i)
1589 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
1590 if i != 300 {
1591 t.Errorf("Pointer Type Method returned %d; want 300", i)
1594 m, ok = TypeOf(&p).MethodByName("Dist")
1595 if !ok {
1596 t.Fatalf("ptr method by name failed")
1598 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
1599 if i != 325 {
1600 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
1603 // Curried method of value.
1604 tfunc := TypeOf((func(int) int)(nil))
1605 v := ValueOf(p).Method(1)
1606 if tt := v.Type(); tt != tfunc {
1607 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1609 i = v.Call([]Value{ValueOf(14)})[0].Int()
1610 if i != 350 {
1611 t.Errorf("Value Method returned %d; want 350", i)
1613 v = ValueOf(p).MethodByName("Dist")
1614 if tt := v.Type(); tt != tfunc {
1615 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1617 i = v.Call([]Value{ValueOf(15)})[0].Int()
1618 if i != 375 {
1619 t.Errorf("Value MethodByName returned %d; want 375", i)
1622 // Curried method of pointer.
1623 v = ValueOf(&p).Method(1)
1624 if tt := v.Type(); tt != tfunc {
1625 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1627 i = v.Call([]Value{ValueOf(16)})[0].Int()
1628 if i != 400 {
1629 t.Errorf("Pointer Value Method returned %d; want 400", i)
1631 v = ValueOf(&p).MethodByName("Dist")
1632 if tt := v.Type(); tt != tfunc {
1633 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1635 i = v.Call([]Value{ValueOf(17)})[0].Int()
1636 if i != 425 {
1637 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
1640 // Curried method of interface value.
1641 // Have to wrap interface value in a struct to get at it.
1642 // Passing it to ValueOf directly would
1643 // access the underlying Point, not the interface.
1644 var x interface {
1645 Dist(int) int
1646 } = p
1647 pv := ValueOf(&x).Elem()
1648 v = pv.Method(0)
1649 if tt := v.Type(); tt != tfunc {
1650 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1652 i = v.Call([]Value{ValueOf(18)})[0].Int()
1653 if i != 450 {
1654 t.Errorf("Interface Method returned %d; want 450", i)
1656 v = pv.MethodByName("Dist")
1657 if tt := v.Type(); tt != tfunc {
1658 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1660 i = v.Call([]Value{ValueOf(19)})[0].Int()
1661 if i != 475 {
1662 t.Errorf("Interface MethodByName returned %d; want 475", i)
1666 func TestMethodValue(t *testing.T) {
1667 p := Point{3, 4}
1668 var i int64
1670 // Curried method of value.
1671 tfunc := TypeOf((func(int) int)(nil))
1672 v := ValueOf(p).Method(1)
1673 if tt := v.Type(); tt != tfunc {
1674 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1676 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
1677 if i != 250 {
1678 t.Errorf("Value Method returned %d; want 250", i)
1680 v = ValueOf(p).MethodByName("Dist")
1681 if tt := v.Type(); tt != tfunc {
1682 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1684 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
1685 if i != 275 {
1686 t.Errorf("Value MethodByName returned %d; want 275", i)
1689 // Curried method of pointer.
1690 v = ValueOf(&p).Method(1)
1691 if tt := v.Type(); tt != tfunc {
1692 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1694 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
1695 if i != 300 {
1696 t.Errorf("Pointer Value Method returned %d; want 300", i)
1698 v = ValueOf(&p).MethodByName("Dist")
1699 if tt := v.Type(); tt != tfunc {
1700 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1702 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
1703 if i != 325 {
1704 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
1707 // Curried method of pointer to pointer.
1708 pp := &p
1709 v = ValueOf(&pp).Elem().Method(1)
1710 if tt := v.Type(); tt != tfunc {
1711 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
1713 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
1714 if i != 350 {
1715 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
1717 v = ValueOf(&pp).Elem().MethodByName("Dist")
1718 if tt := v.Type(); tt != tfunc {
1719 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1721 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
1722 if i != 375 {
1723 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
1726 // Curried method of interface value.
1727 // Have to wrap interface value in a struct to get at it.
1728 // Passing it to ValueOf directly would
1729 // access the underlying Point, not the interface.
1730 var s = struct {
1731 X interface {
1732 Dist(int) int
1734 }{p}
1735 pv := ValueOf(s).Field(0)
1736 v = pv.Method(0)
1737 if tt := v.Type(); tt != tfunc {
1738 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1740 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
1741 if i != 400 {
1742 t.Errorf("Interface Method returned %d; want 400", i)
1744 v = pv.MethodByName("Dist")
1745 if tt := v.Type(); tt != tfunc {
1746 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1748 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
1749 if i != 425 {
1750 t.Errorf("Interface MethodByName returned %d; want 425", i)
1754 // Reflect version of $GOROOT/test/method5.go
1756 // Concrete types implementing M method.
1757 // Smaller than a word, word-sized, larger than a word.
1758 // Value and pointer receivers.
1760 type Tinter interface {
1761 M(int, byte) (byte, int)
1764 type Tsmallv byte
1766 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1768 type Tsmallp byte
1770 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1772 type Twordv uintptr
1774 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1776 type Twordp uintptr
1778 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1780 type Tbigv [2]uintptr
1782 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1784 type Tbigp [2]uintptr
1786 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1788 // Again, with an unexported method.
1790 type tsmallv byte
1792 func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1794 type tsmallp byte
1796 func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1798 type twordv uintptr
1800 func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1802 type twordp uintptr
1804 func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1806 type tbigv [2]uintptr
1808 func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1810 type tbigp [2]uintptr
1812 func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1814 type tinter interface {
1815 m(int, byte) (byte, int)
1818 // Embedding via pointer.
1820 type Tm1 struct {
1824 type Tm2 struct {
1825 *Tm3
1828 type Tm3 struct {
1829 *Tm4
1832 type Tm4 struct {
1835 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
1837 func TestMethod5(t *testing.T) {
1838 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
1839 b, x := f(1000, 99)
1840 if b != 99 || x != 1000+inc {
1841 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1845 CheckV := func(name string, i Value, inc int) {
1846 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
1847 b := bx[0].Interface()
1848 x := bx[1].Interface()
1849 if b != byte(99) || x != 1000+inc {
1850 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1853 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
1856 var TinterType = TypeOf(new(Tinter)).Elem()
1857 var tinterType = TypeOf(new(tinter)).Elem()
1859 CheckI := func(name string, i interface{}, inc int) {
1860 v := ValueOf(i)
1861 CheckV(name, v, inc)
1862 CheckV("(i="+name+")", v.Convert(TinterType), inc)
1865 sv := Tsmallv(1)
1866 CheckI("sv", sv, 1)
1867 CheckI("&sv", &sv, 1)
1869 sp := Tsmallp(2)
1870 CheckI("&sp", &sp, 2)
1872 wv := Twordv(3)
1873 CheckI("wv", wv, 3)
1874 CheckI("&wv", &wv, 3)
1876 wp := Twordp(4)
1877 CheckI("&wp", &wp, 4)
1879 bv := Tbigv([2]uintptr{5, 6})
1880 CheckI("bv", bv, 11)
1881 CheckI("&bv", &bv, 11)
1883 bp := Tbigp([2]uintptr{7, 8})
1884 CheckI("&bp", &bp, 15)
1886 t4 := Tm4{}
1887 t3 := Tm3{&t4}
1888 t2 := Tm2{&t3}
1889 t1 := Tm1{t2}
1890 CheckI("t4", t4, 40)
1891 CheckI("&t4", &t4, 40)
1892 CheckI("t3", t3, 40)
1893 CheckI("&t3", &t3, 40)
1894 CheckI("t2", t2, 40)
1895 CheckI("&t2", &t2, 40)
1896 CheckI("t1", t1, 40)
1897 CheckI("&t1", &t1, 40)
1899 methodShouldPanic := func(name string, i interface{}) {
1900 v := ValueOf(i)
1901 m := v.Method(0)
1902 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1903 shouldPanic(func() { m.Interface() })
1905 v = v.Convert(tinterType)
1906 m = v.Method(0)
1907 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1908 shouldPanic(func() { m.Interface() })
1911 _sv := tsmallv(1)
1912 methodShouldPanic("_sv", _sv)
1913 methodShouldPanic("&_sv", &_sv)
1915 _sp := tsmallp(2)
1916 methodShouldPanic("&_sp", &_sp)
1918 _wv := twordv(3)
1919 methodShouldPanic("_wv", _wv)
1920 methodShouldPanic("&_wv", &_wv)
1922 _wp := twordp(4)
1923 methodShouldPanic("&_wp", &_wp)
1925 _bv := tbigv([2]uintptr{5, 6})
1926 methodShouldPanic("_bv", _bv)
1927 methodShouldPanic("&_bv", &_bv)
1929 _bp := tbigp([2]uintptr{7, 8})
1930 methodShouldPanic("&_bp", &_bp)
1932 var tnil Tinter
1933 vnil := ValueOf(&tnil).Elem()
1934 shouldPanic(func() { vnil.Method(0) })
1937 func TestInterfaceSet(t *testing.T) {
1938 p := &Point{3, 4}
1940 var s struct {
1941 I interface{}
1942 P interface {
1943 Dist(int) int
1946 sv := ValueOf(&s).Elem()
1947 sv.Field(0).Set(ValueOf(p))
1948 if q := s.I.(*Point); q != p {
1949 t.Errorf("i: have %p want %p", q, p)
1952 pv := sv.Field(1)
1953 pv.Set(ValueOf(p))
1954 if q := s.P.(*Point); q != p {
1955 t.Errorf("i: have %p want %p", q, p)
1958 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1959 if i != 250 {
1960 t.Errorf("Interface Method returned %d; want 250", i)
1964 type T1 struct {
1965 a string
1969 func TestAnonymousFields(t *testing.T) {
1970 var field StructField
1971 var ok bool
1972 var t1 T1
1973 type1 := TypeOf(t1)
1974 if field, ok = type1.FieldByName("int"); !ok {
1975 t.Fatal("no field 'int'")
1977 if field.Index[0] != 1 {
1978 t.Error("field index should be 1; is", field.Index)
1982 type FTest struct {
1983 s interface{}
1984 name string
1985 index []int
1986 value int
1989 type D1 struct {
1990 d int
1992 type D2 struct {
1993 d int
1996 type S0 struct {
1997 A, B, C int
2002 type S1 struct {
2003 B int
2007 type S2 struct {
2008 A int
2012 type S1x struct {
2016 type S1y struct {
2020 type S3 struct {
2023 D, E int
2024 *S1y
2027 type S4 struct {
2029 A int
2032 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2033 type S5 struct {
2039 type S6 struct {
2040 X int
2043 type S7 S6
2045 type S8 struct {
2049 type S9 struct {
2050 X int
2051 Y int
2054 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2055 type S10 struct {
2061 type S11 struct {
2065 type S12 struct {
2069 type S13 struct {
2073 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2074 type S14 struct {
2079 type S15 struct {
2083 type S16 struct {
2087 var fieldTests = []FTest{
2088 {struct{}{}, "", nil, 0},
2089 {struct{}{}, "Foo", nil, 0},
2090 {S0{A: 'a'}, "A", []int{0}, 'a'},
2091 {S0{}, "D", nil, 0},
2092 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2093 {S1{B: 'b'}, "B", []int{0}, 'b'},
2094 {S1{}, "S0", []int{1}, 0},
2095 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2096 {S2{A: 'a'}, "A", []int{0}, 'a'},
2097 {S2{}, "S1", []int{1}, 0},
2098 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2099 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2100 {S2{}, "D", nil, 0},
2101 {S3{}, "S1", nil, 0},
2102 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2103 {S3{}, "B", nil, 0},
2104 {S3{D: 'd'}, "D", []int{2}, 0},
2105 {S3{E: 'e'}, "E", []int{3}, 'e'},
2106 {S4{A: 'a'}, "A", []int{1}, 'a'},
2107 {S4{}, "B", nil, 0},
2108 {S5{}, "X", nil, 0},
2109 {S5{}, "Y", []int{2, 0, 1}, 0},
2110 {S10{}, "X", nil, 0},
2111 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2112 {S14{}, "X", nil, 0},
2115 func TestFieldByIndex(t *testing.T) {
2116 for _, test := range fieldTests {
2117 s := TypeOf(test.s)
2118 f := s.FieldByIndex(test.index)
2119 if f.Name != "" {
2120 if test.index != nil {
2121 if f.Name != test.name {
2122 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2124 } else {
2125 t.Errorf("%s.%s found", s.Name(), f.Name)
2127 } else if len(test.index) > 0 {
2128 t.Errorf("%s.%s not found", s.Name(), test.name)
2131 if test.value != 0 {
2132 v := ValueOf(test.s).FieldByIndex(test.index)
2133 if v.IsValid() {
2134 if x, ok := v.Interface().(int); ok {
2135 if x != test.value {
2136 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2138 } else {
2139 t.Errorf("%s%v value not an int", s.Name(), test.index)
2141 } else {
2142 t.Errorf("%s%v value not found", s.Name(), test.index)
2148 func TestFieldByName(t *testing.T) {
2149 for _, test := range fieldTests {
2150 s := TypeOf(test.s)
2151 f, found := s.FieldByName(test.name)
2152 if found {
2153 if test.index != nil {
2154 // Verify field depth and index.
2155 if len(f.Index) != len(test.index) {
2156 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)
2157 } else {
2158 for i, x := range f.Index {
2159 if x != test.index[i] {
2160 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2164 } else {
2165 t.Errorf("%s.%s found", s.Name(), f.Name)
2167 } else if len(test.index) > 0 {
2168 t.Errorf("%s.%s not found", s.Name(), test.name)
2171 if test.value != 0 {
2172 v := ValueOf(test.s).FieldByName(test.name)
2173 if v.IsValid() {
2174 if x, ok := v.Interface().(int); ok {
2175 if x != test.value {
2176 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2178 } else {
2179 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2181 } else {
2182 t.Errorf("%s.%s value not found", s.Name(), test.name)
2188 func TestImportPath(t *testing.T) {
2189 tests := []struct {
2190 t Type
2191 path string
2193 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2194 {TypeOf(int(0)), ""},
2195 {TypeOf(int8(0)), ""},
2196 {TypeOf(int16(0)), ""},
2197 {TypeOf(int32(0)), ""},
2198 {TypeOf(int64(0)), ""},
2199 {TypeOf(uint(0)), ""},
2200 {TypeOf(uint8(0)), ""},
2201 {TypeOf(uint16(0)), ""},
2202 {TypeOf(uint32(0)), ""},
2203 {TypeOf(uint64(0)), ""},
2204 {TypeOf(uintptr(0)), ""},
2205 {TypeOf(float32(0)), ""},
2206 {TypeOf(float64(0)), ""},
2207 {TypeOf(complex64(0)), ""},
2208 {TypeOf(complex128(0)), ""},
2209 {TypeOf(byte(0)), ""},
2210 {TypeOf(rune(0)), ""},
2211 {TypeOf([]byte(nil)), ""},
2212 {TypeOf([]rune(nil)), ""},
2213 {TypeOf(string("")), ""},
2214 {TypeOf((*interface{})(nil)).Elem(), ""},
2215 {TypeOf((*byte)(nil)), ""},
2216 {TypeOf((*rune)(nil)), ""},
2217 {TypeOf((*int64)(nil)), ""},
2218 {TypeOf(map[string]int{}), ""},
2219 {TypeOf((*error)(nil)).Elem(), ""},
2221 for _, test := range tests {
2222 if path := test.t.PkgPath(); path != test.path {
2223 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2228 func TestVariadicType(t *testing.T) {
2229 // Test example from Type documentation.
2230 var f func(x int, y ...float64)
2231 typ := TypeOf(f)
2232 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2233 sl := typ.In(1)
2234 if sl.Kind() == Slice {
2235 if sl.Elem() == TypeOf(0.0) {
2236 // ok
2237 return
2242 // Failed
2243 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2244 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
2245 for i := 0; i < typ.NumIn(); i++ {
2246 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
2248 t.Error(s)
2251 type inner struct {
2252 x int
2255 type outer struct {
2256 y int
2257 inner
2260 func (*inner) m() {}
2261 func (*outer) m() {}
2263 func TestNestedMethods(t *testing.T) {
2264 t.Skip("fails on gccgo due to function wrappers")
2265 typ := TypeOf((*outer)(nil))
2266 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
2267 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
2268 for i := 0; i < typ.NumMethod(); i++ {
2269 m := typ.Method(i)
2270 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2275 type InnerInt struct {
2276 X int
2279 type OuterInt struct {
2280 Y int
2281 InnerInt
2284 func (i *InnerInt) M() int {
2285 return i.X
2288 func TestEmbeddedMethods(t *testing.T) {
2289 /* This part of the test fails on gccgo due to function wrappers.
2290 typ := TypeOf((*OuterInt)(nil))
2291 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2292 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2293 for i := 0; i < typ.NumMethod(); i++ {
2294 m := typ.Method(i)
2295 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2300 i := &InnerInt{3}
2301 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
2302 t.Errorf("i.M() = %d, want 3", v)
2305 o := &OuterInt{1, InnerInt{2}}
2306 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
2307 t.Errorf("i.M() = %d, want 2", v)
2310 f := (*OuterInt).M
2311 if v := f(o); v != 2 {
2312 t.Errorf("f(o) = %d, want 2", v)
2316 func TestPtrTo(t *testing.T) {
2317 var i int
2319 typ := TypeOf(i)
2320 for i = 0; i < 100; i++ {
2321 typ = PtrTo(typ)
2323 for i = 0; i < 100; i++ {
2324 typ = typ.Elem()
2326 if typ != TypeOf(i) {
2327 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
2331 func TestPtrToGC(t *testing.T) {
2332 type T *uintptr
2333 tt := TypeOf(T(nil))
2334 pt := PtrTo(tt)
2335 const n = 100
2336 var x []interface{}
2337 for i := 0; i < n; i++ {
2338 v := New(pt)
2339 p := new(*uintptr)
2340 *p = new(uintptr)
2341 **p = uintptr(i)
2342 v.Elem().Set(ValueOf(p).Convert(pt))
2343 x = append(x, v.Interface())
2345 runtime.GC()
2347 for i, xi := range x {
2348 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
2349 if k != uintptr(i) {
2350 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
2355 func TestAddr(t *testing.T) {
2356 var p struct {
2357 X, Y int
2360 v := ValueOf(&p)
2361 v = v.Elem()
2362 v = v.Addr()
2363 v = v.Elem()
2364 v = v.Field(0)
2365 v.SetInt(2)
2366 if p.X != 2 {
2367 t.Errorf("Addr.Elem.Set failed to set value")
2370 // Again but take address of the ValueOf value.
2371 // Exercises generation of PtrTypes not present in the binary.
2372 q := &p
2373 v = ValueOf(&q).Elem()
2374 v = v.Addr()
2375 v = v.Elem()
2376 v = v.Elem()
2377 v = v.Addr()
2378 v = v.Elem()
2379 v = v.Field(0)
2380 v.SetInt(3)
2381 if p.X != 3 {
2382 t.Errorf("Addr.Elem.Set failed to set value")
2385 // Starting without pointer we should get changed value
2386 // in interface.
2387 qq := p
2388 v = ValueOf(&qq).Elem()
2389 v0 := v
2390 v = v.Addr()
2391 v = v.Elem()
2392 v = v.Field(0)
2393 v.SetInt(4)
2394 if p.X != 3 { // should be unchanged from last time
2395 t.Errorf("somehow value Set changed original p")
2397 p = v0.Interface().(struct {
2398 X, Y int
2400 if p.X != 4 {
2401 t.Errorf("Addr.Elem.Set valued to set value in top value")
2404 // Verify that taking the address of a type gives us a pointer
2405 // which we can convert back using the usual interface
2406 // notation.
2407 var s struct {
2408 B *bool
2410 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
2411 *(ps.(**bool)) = new(bool)
2412 if s.B == nil {
2413 t.Errorf("Addr.Interface direct assignment failed")
2417 /* gccgo does do allocations here.
2419 func noAlloc(t *testing.T, n int, f func(int)) {
2420 if testing.Short() {
2421 t.Skip("skipping malloc count in short mode")
2423 if runtime.GOMAXPROCS(0) > 1 {
2424 t.Skip("skipping; GOMAXPROCS>1")
2426 i := -1
2427 allocs := testing.AllocsPerRun(n, func() {
2428 f(i)
2431 if allocs > 0 {
2432 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2436 func TestAllocations(t *testing.T) {
2437 noAlloc(t, 100, func(j int) {
2438 var i interface{}
2439 var v Value
2440 i = 42 + j
2441 v = ValueOf(i)
2442 if int(v.Int()) != 42+j {
2443 panic("wrong int")
2450 func TestSmallNegativeInt(t *testing.T) {
2451 i := int16(-1)
2452 v := ValueOf(i)
2453 if v.Int() != -1 {
2454 t.Errorf("int16(-1).Int() returned %v", v.Int())
2458 func TestIndex(t *testing.T) {
2459 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
2460 v := ValueOf(xs).Index(3).Interface().(byte)
2461 if v != xs[3] {
2462 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
2464 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2465 v = ValueOf(xa).Index(2).Interface().(byte)
2466 if v != xa[2] {
2467 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
2469 s := "0123456789"
2470 v = ValueOf(s).Index(3).Interface().(byte)
2471 if v != s[3] {
2472 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
2476 func TestSlice(t *testing.T) {
2477 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2478 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
2479 if len(v) != 2 {
2480 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
2482 if cap(v) != 5 {
2483 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
2485 if !DeepEqual(v[0:5], xs[3:]) {
2486 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
2488 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2489 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
2490 if len(v) != 3 {
2491 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
2493 if cap(v) != 6 {
2494 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
2496 if !DeepEqual(v[0:6], xa[2:]) {
2497 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
2499 s := "0123456789"
2500 vs := ValueOf(s).Slice(3, 5).Interface().(string)
2501 if vs != s[3:5] {
2502 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
2506 func TestSlice3(t *testing.T) {
2507 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2508 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
2509 if len(v) != 2 {
2510 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
2512 if cap(v) != 4 {
2513 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
2515 if !DeepEqual(v[0:4], xs[3:7:7]) {
2516 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
2518 rv := ValueOf(&xs).Elem()
2519 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2520 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2521 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2523 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2524 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
2525 if len(v) != 3 {
2526 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
2528 if cap(v) != 4 {
2529 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
2531 if !DeepEqual(v[0:4], xa[2:6:6]) {
2532 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
2534 rv = ValueOf(&xa).Elem()
2535 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2536 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2537 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2539 s := "hello world"
2540 rv = ValueOf(&s).Elem()
2541 shouldPanic(func() { rv.Slice3(1, 2, 3) })
2544 func TestSetLenCap(t *testing.T) {
2545 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2546 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2548 vs := ValueOf(&xs).Elem()
2549 shouldPanic(func() { vs.SetLen(10) })
2550 shouldPanic(func() { vs.SetCap(10) })
2551 shouldPanic(func() { vs.SetLen(-1) })
2552 shouldPanic(func() { vs.SetCap(-1) })
2553 shouldPanic(func() { vs.SetCap(6) }) // smaller than len
2554 vs.SetLen(5)
2555 if len(xs) != 5 || cap(xs) != 8 {
2556 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
2558 vs.SetCap(6)
2559 if len(xs) != 5 || cap(xs) != 6 {
2560 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
2562 vs.SetCap(5)
2563 if len(xs) != 5 || cap(xs) != 5 {
2564 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
2566 shouldPanic(func() { vs.SetCap(4) }) // smaller than len
2567 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
2569 va := ValueOf(&xa).Elem()
2570 shouldPanic(func() { va.SetLen(8) })
2571 shouldPanic(func() { va.SetCap(8) })
2574 func TestVariadic(t *testing.T) {
2575 var b bytes.Buffer
2576 V := ValueOf
2578 b.Reset()
2579 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
2580 if b.String() != "hello, 42 world" {
2581 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
2584 b.Reset()
2585 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
2586 if b.String() != "hello, 42 world" {
2587 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
2591 func TestFuncArg(t *testing.T) {
2592 f1 := func(i int, f func(int) int) int { return f(i) }
2593 f2 := func(i int) int { return i + 1 }
2594 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
2595 if r[0].Int() != 101 {
2596 t.Errorf("function returned %d, want 101", r[0].Int())
2600 var tagGetTests = []struct {
2601 Tag StructTag
2602 Key string
2603 Value string
2605 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2606 {`protobuf:"PB(1,2)"`, `foo`, ``},
2607 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2608 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2609 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2612 func TestTagGet(t *testing.T) {
2613 for _, tt := range tagGetTests {
2614 if v := tt.Tag.Get(tt.Key); v != tt.Value {
2615 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
2620 func TestBytes(t *testing.T) {
2621 type B []byte
2622 x := B{1, 2, 3, 4}
2623 y := ValueOf(x).Bytes()
2624 if !bytes.Equal(x, y) {
2625 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2627 if &x[0] != &y[0] {
2628 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2632 func TestSetBytes(t *testing.T) {
2633 type B []byte
2634 var x B
2635 y := []byte{1, 2, 3, 4}
2636 ValueOf(&x).Elem().SetBytes(y)
2637 if !bytes.Equal(x, y) {
2638 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2640 if &x[0] != &y[0] {
2641 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2645 type Private struct {
2646 x int
2647 y **int
2650 func (p *Private) m() {
2653 type Public struct {
2654 X int
2655 Y **int
2658 func (p *Public) M() {
2661 func TestUnexported(t *testing.T) {
2662 var pub Public
2663 v := ValueOf(&pub)
2664 isValid(v.Elem().Field(0))
2665 isValid(v.Elem().Field(1))
2666 isValid(v.Elem().FieldByName("X"))
2667 isValid(v.Elem().FieldByName("Y"))
2668 isValid(v.Type().Method(0).Func)
2669 isNonNil(v.Elem().Field(0).Interface())
2670 isNonNil(v.Elem().Field(1).Interface())
2671 isNonNil(v.Elem().FieldByName("X").Interface())
2672 isNonNil(v.Elem().FieldByName("Y").Interface())
2673 isNonNil(v.Type().Method(0).Func.Interface())
2675 var priv Private
2676 v = ValueOf(&priv)
2677 isValid(v.Elem().Field(0))
2678 isValid(v.Elem().Field(1))
2679 isValid(v.Elem().FieldByName("x"))
2680 isValid(v.Elem().FieldByName("y"))
2681 isValid(v.Type().Method(0).Func)
2682 shouldPanic(func() { v.Elem().Field(0).Interface() })
2683 shouldPanic(func() { v.Elem().Field(1).Interface() })
2684 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
2685 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
2686 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
2689 func shouldPanic(f func()) {
2690 defer func() {
2691 if recover() == nil {
2692 panic("did not panic")
2698 func isNonNil(x interface{}) {
2699 if x == nil {
2700 panic("nil interface")
2704 func isValid(v Value) {
2705 if !v.IsValid() {
2706 panic("zero Value")
2710 func TestAlias(t *testing.T) {
2711 x := string("hello")
2712 v := ValueOf(&x).Elem()
2713 oldvalue := v.Interface()
2714 v.SetString("world")
2715 newvalue := v.Interface()
2717 if oldvalue != "hello" || newvalue != "world" {
2718 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
2722 var V = ValueOf
2724 func EmptyInterfaceV(x interface{}) Value {
2725 return ValueOf(&x).Elem()
2728 func ReaderV(x io.Reader) Value {
2729 return ValueOf(&x).Elem()
2732 func ReadWriterV(x io.ReadWriter) Value {
2733 return ValueOf(&x).Elem()
2736 type Empty struct{}
2737 type MyString string
2738 type MyBytes []byte
2739 type MyRunes []int32
2740 type MyFunc func()
2741 type MyByte byte
2743 var convertTests = []struct {
2744 in Value
2745 out Value
2747 // numbers
2749 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
2751 package main
2753 import "fmt"
2755 var numbers = []string{
2756 "int8", "uint8", "int16", "uint16",
2757 "int32", "uint32", "int64", "uint64",
2758 "int", "uint", "uintptr",
2759 "float32", "float64",
2762 func main() {
2763 // all pairs but in an unusual order,
2764 // to emit all the int8, uint8 cases
2765 // before n grows too big.
2766 n := 1
2767 for i, f := range numbers {
2768 for _, g := range numbers[i:] {
2769 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
2771 if f != g {
2772 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
2779 {V(int8(1)), V(int8(1))},
2780 {V(int8(2)), V(uint8(2))},
2781 {V(uint8(3)), V(int8(3))},
2782 {V(int8(4)), V(int16(4))},
2783 {V(int16(5)), V(int8(5))},
2784 {V(int8(6)), V(uint16(6))},
2785 {V(uint16(7)), V(int8(7))},
2786 {V(int8(8)), V(int32(8))},
2787 {V(int32(9)), V(int8(9))},
2788 {V(int8(10)), V(uint32(10))},
2789 {V(uint32(11)), V(int8(11))},
2790 {V(int8(12)), V(int64(12))},
2791 {V(int64(13)), V(int8(13))},
2792 {V(int8(14)), V(uint64(14))},
2793 {V(uint64(15)), V(int8(15))},
2794 {V(int8(16)), V(int(16))},
2795 {V(int(17)), V(int8(17))},
2796 {V(int8(18)), V(uint(18))},
2797 {V(uint(19)), V(int8(19))},
2798 {V(int8(20)), V(uintptr(20))},
2799 {V(uintptr(21)), V(int8(21))},
2800 {V(int8(22)), V(float32(22))},
2801 {V(float32(23)), V(int8(23))},
2802 {V(int8(24)), V(float64(24))},
2803 {V(float64(25)), V(int8(25))},
2804 {V(uint8(26)), V(uint8(26))},
2805 {V(uint8(27)), V(int16(27))},
2806 {V(int16(28)), V(uint8(28))},
2807 {V(uint8(29)), V(uint16(29))},
2808 {V(uint16(30)), V(uint8(30))},
2809 {V(uint8(31)), V(int32(31))},
2810 {V(int32(32)), V(uint8(32))},
2811 {V(uint8(33)), V(uint32(33))},
2812 {V(uint32(34)), V(uint8(34))},
2813 {V(uint8(35)), V(int64(35))},
2814 {V(int64(36)), V(uint8(36))},
2815 {V(uint8(37)), V(uint64(37))},
2816 {V(uint64(38)), V(uint8(38))},
2817 {V(uint8(39)), V(int(39))},
2818 {V(int(40)), V(uint8(40))},
2819 {V(uint8(41)), V(uint(41))},
2820 {V(uint(42)), V(uint8(42))},
2821 {V(uint8(43)), V(uintptr(43))},
2822 {V(uintptr(44)), V(uint8(44))},
2823 {V(uint8(45)), V(float32(45))},
2824 {V(float32(46)), V(uint8(46))},
2825 {V(uint8(47)), V(float64(47))},
2826 {V(float64(48)), V(uint8(48))},
2827 {V(int16(49)), V(int16(49))},
2828 {V(int16(50)), V(uint16(50))},
2829 {V(uint16(51)), V(int16(51))},
2830 {V(int16(52)), V(int32(52))},
2831 {V(int32(53)), V(int16(53))},
2832 {V(int16(54)), V(uint32(54))},
2833 {V(uint32(55)), V(int16(55))},
2834 {V(int16(56)), V(int64(56))},
2835 {V(int64(57)), V(int16(57))},
2836 {V(int16(58)), V(uint64(58))},
2837 {V(uint64(59)), V(int16(59))},
2838 {V(int16(60)), V(int(60))},
2839 {V(int(61)), V(int16(61))},
2840 {V(int16(62)), V(uint(62))},
2841 {V(uint(63)), V(int16(63))},
2842 {V(int16(64)), V(uintptr(64))},
2843 {V(uintptr(65)), V(int16(65))},
2844 {V(int16(66)), V(float32(66))},
2845 {V(float32(67)), V(int16(67))},
2846 {V(int16(68)), V(float64(68))},
2847 {V(float64(69)), V(int16(69))},
2848 {V(uint16(70)), V(uint16(70))},
2849 {V(uint16(71)), V(int32(71))},
2850 {V(int32(72)), V(uint16(72))},
2851 {V(uint16(73)), V(uint32(73))},
2852 {V(uint32(74)), V(uint16(74))},
2853 {V(uint16(75)), V(int64(75))},
2854 {V(int64(76)), V(uint16(76))},
2855 {V(uint16(77)), V(uint64(77))},
2856 {V(uint64(78)), V(uint16(78))},
2857 {V(uint16(79)), V(int(79))},
2858 {V(int(80)), V(uint16(80))},
2859 {V(uint16(81)), V(uint(81))},
2860 {V(uint(82)), V(uint16(82))},
2861 {V(uint16(83)), V(uintptr(83))},
2862 {V(uintptr(84)), V(uint16(84))},
2863 {V(uint16(85)), V(float32(85))},
2864 {V(float32(86)), V(uint16(86))},
2865 {V(uint16(87)), V(float64(87))},
2866 {V(float64(88)), V(uint16(88))},
2867 {V(int32(89)), V(int32(89))},
2868 {V(int32(90)), V(uint32(90))},
2869 {V(uint32(91)), V(int32(91))},
2870 {V(int32(92)), V(int64(92))},
2871 {V(int64(93)), V(int32(93))},
2872 {V(int32(94)), V(uint64(94))},
2873 {V(uint64(95)), V(int32(95))},
2874 {V(int32(96)), V(int(96))},
2875 {V(int(97)), V(int32(97))},
2876 {V(int32(98)), V(uint(98))},
2877 {V(uint(99)), V(int32(99))},
2878 {V(int32(100)), V(uintptr(100))},
2879 {V(uintptr(101)), V(int32(101))},
2880 {V(int32(102)), V(float32(102))},
2881 {V(float32(103)), V(int32(103))},
2882 {V(int32(104)), V(float64(104))},
2883 {V(float64(105)), V(int32(105))},
2884 {V(uint32(106)), V(uint32(106))},
2885 {V(uint32(107)), V(int64(107))},
2886 {V(int64(108)), V(uint32(108))},
2887 {V(uint32(109)), V(uint64(109))},
2888 {V(uint64(110)), V(uint32(110))},
2889 {V(uint32(111)), V(int(111))},
2890 {V(int(112)), V(uint32(112))},
2891 {V(uint32(113)), V(uint(113))},
2892 {V(uint(114)), V(uint32(114))},
2893 {V(uint32(115)), V(uintptr(115))},
2894 {V(uintptr(116)), V(uint32(116))},
2895 {V(uint32(117)), V(float32(117))},
2896 {V(float32(118)), V(uint32(118))},
2897 {V(uint32(119)), V(float64(119))},
2898 {V(float64(120)), V(uint32(120))},
2899 {V(int64(121)), V(int64(121))},
2900 {V(int64(122)), V(uint64(122))},
2901 {V(uint64(123)), V(int64(123))},
2902 {V(int64(124)), V(int(124))},
2903 {V(int(125)), V(int64(125))},
2904 {V(int64(126)), V(uint(126))},
2905 {V(uint(127)), V(int64(127))},
2906 {V(int64(128)), V(uintptr(128))},
2907 {V(uintptr(129)), V(int64(129))},
2908 {V(int64(130)), V(float32(130))},
2909 {V(float32(131)), V(int64(131))},
2910 {V(int64(132)), V(float64(132))},
2911 {V(float64(133)), V(int64(133))},
2912 {V(uint64(134)), V(uint64(134))},
2913 {V(uint64(135)), V(int(135))},
2914 {V(int(136)), V(uint64(136))},
2915 {V(uint64(137)), V(uint(137))},
2916 {V(uint(138)), V(uint64(138))},
2917 {V(uint64(139)), V(uintptr(139))},
2918 {V(uintptr(140)), V(uint64(140))},
2919 {V(uint64(141)), V(float32(141))},
2920 {V(float32(142)), V(uint64(142))},
2921 {V(uint64(143)), V(float64(143))},
2922 {V(float64(144)), V(uint64(144))},
2923 {V(int(145)), V(int(145))},
2924 {V(int(146)), V(uint(146))},
2925 {V(uint(147)), V(int(147))},
2926 {V(int(148)), V(uintptr(148))},
2927 {V(uintptr(149)), V(int(149))},
2928 {V(int(150)), V(float32(150))},
2929 {V(float32(151)), V(int(151))},
2930 {V(int(152)), V(float64(152))},
2931 {V(float64(153)), V(int(153))},
2932 {V(uint(154)), V(uint(154))},
2933 {V(uint(155)), V(uintptr(155))},
2934 {V(uintptr(156)), V(uint(156))},
2935 {V(uint(157)), V(float32(157))},
2936 {V(float32(158)), V(uint(158))},
2937 {V(uint(159)), V(float64(159))},
2938 {V(float64(160)), V(uint(160))},
2939 {V(uintptr(161)), V(uintptr(161))},
2940 {V(uintptr(162)), V(float32(162))},
2941 {V(float32(163)), V(uintptr(163))},
2942 {V(uintptr(164)), V(float64(164))},
2943 {V(float64(165)), V(uintptr(165))},
2944 {V(float32(166)), V(float32(166))},
2945 {V(float32(167)), V(float64(167))},
2946 {V(float64(168)), V(float32(168))},
2947 {V(float64(169)), V(float64(169))},
2949 // truncation
2950 {V(float64(1.5)), V(int(1))},
2952 // complex
2953 {V(complex64(1i)), V(complex64(1i))},
2954 {V(complex64(2i)), V(complex128(2i))},
2955 {V(complex128(3i)), V(complex64(3i))},
2956 {V(complex128(4i)), V(complex128(4i))},
2958 // string
2959 {V(string("hello")), V(string("hello"))},
2960 {V(string("bytes1")), V([]byte("bytes1"))},
2961 {V([]byte("bytes2")), V(string("bytes2"))},
2962 {V([]byte("bytes3")), V([]byte("bytes3"))},
2963 {V(string("runes♝")), V([]rune("runes♝"))},
2964 {V([]rune("runes♕")), V(string("runes♕"))},
2965 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2966 {V(int('a')), V(string("a"))},
2967 {V(int8('a')), V(string("a"))},
2968 {V(int16('a')), V(string("a"))},
2969 {V(int32('a')), V(string("a"))},
2970 {V(int64('a')), V(string("a"))},
2971 {V(uint('a')), V(string("a"))},
2972 {V(uint8('a')), V(string("a"))},
2973 {V(uint16('a')), V(string("a"))},
2974 {V(uint32('a')), V(string("a"))},
2975 {V(uint64('a')), V(string("a"))},
2976 {V(uintptr('a')), V(string("a"))},
2977 {V(int(-1)), V(string("\uFFFD"))},
2978 {V(int8(-2)), V(string("\uFFFD"))},
2979 {V(int16(-3)), V(string("\uFFFD"))},
2980 {V(int32(-4)), V(string("\uFFFD"))},
2981 {V(int64(-5)), V(string("\uFFFD"))},
2982 {V(uint(0x110001)), V(string("\uFFFD"))},
2983 {V(uint32(0x110002)), V(string("\uFFFD"))},
2984 {V(uint64(0x110003)), V(string("\uFFFD"))},
2985 {V(uintptr(0x110004)), V(string("\uFFFD"))},
2987 // named string
2988 {V(MyString("hello")), V(string("hello"))},
2989 {V(string("hello")), V(MyString("hello"))},
2990 {V(string("hello")), V(string("hello"))},
2991 {V(MyString("hello")), V(MyString("hello"))},
2992 {V(MyString("bytes1")), V([]byte("bytes1"))},
2993 {V([]byte("bytes2")), V(MyString("bytes2"))},
2994 {V([]byte("bytes3")), V([]byte("bytes3"))},
2995 {V(MyString("runes♝")), V([]rune("runes♝"))},
2996 {V([]rune("runes♕")), V(MyString("runes♕"))},
2997 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2998 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
2999 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3000 {V(int('a')), V(MyString("a"))},
3001 {V(int8('a')), V(MyString("a"))},
3002 {V(int16('a')), V(MyString("a"))},
3003 {V(int32('a')), V(MyString("a"))},
3004 {V(int64('a')), V(MyString("a"))},
3005 {V(uint('a')), V(MyString("a"))},
3006 {V(uint8('a')), V(MyString("a"))},
3007 {V(uint16('a')), V(MyString("a"))},
3008 {V(uint32('a')), V(MyString("a"))},
3009 {V(uint64('a')), V(MyString("a"))},
3010 {V(uintptr('a')), V(MyString("a"))},
3011 {V(int(-1)), V(MyString("\uFFFD"))},
3012 {V(int8(-2)), V(MyString("\uFFFD"))},
3013 {V(int16(-3)), V(MyString("\uFFFD"))},
3014 {V(int32(-4)), V(MyString("\uFFFD"))},
3015 {V(int64(-5)), V(MyString("\uFFFD"))},
3016 {V(uint(0x110001)), V(MyString("\uFFFD"))},
3017 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
3018 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3019 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3021 // named []byte
3022 {V(string("bytes1")), V(MyBytes("bytes1"))},
3023 {V(MyBytes("bytes2")), V(string("bytes2"))},
3024 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3025 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3026 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3028 // named []rune
3029 {V(string("runes♝")), V(MyRunes("runes♝"))},
3030 {V(MyRunes("runes♕")), V(string("runes♕"))},
3031 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3032 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3033 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3035 // named types and equal underlying types
3036 {V(new(int)), V(new(integer))},
3037 {V(new(integer)), V(new(int))},
3038 {V(Empty{}), V(struct{}{})},
3039 {V(new(Empty)), V(new(struct{}))},
3040 {V(struct{}{}), V(Empty{})},
3041 {V(new(struct{})), V(new(Empty))},
3042 {V(Empty{}), V(Empty{})},
3043 {V(MyBytes{}), V([]byte{})},
3044 {V([]byte{}), V(MyBytes{})},
3045 {V((func())(nil)), V(MyFunc(nil))},
3046 {V((MyFunc)(nil)), V((func())(nil))},
3048 // can convert *byte and *MyByte
3049 {V((*byte)(nil)), V((*MyByte)(nil))},
3050 {V((*MyByte)(nil)), V((*byte)(nil))},
3052 // cannot convert mismatched array sizes
3053 {V([2]byte{}), V([2]byte{})},
3054 {V([3]byte{}), V([3]byte{})},
3056 // cannot convert other instances
3057 {V((**byte)(nil)), V((**byte)(nil))},
3058 {V((**MyByte)(nil)), V((**MyByte)(nil))},
3059 {V((chan byte)(nil)), V((chan byte)(nil))},
3060 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3061 {V(([]byte)(nil)), V(([]byte)(nil))},
3062 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
3063 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3064 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
3065 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3066 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
3067 {V([2]byte{}), V([2]byte{})},
3068 {V([2]MyByte{}), V([2]MyByte{})},
3070 // other
3071 {V((***int)(nil)), V((***int)(nil))},
3072 {V((***byte)(nil)), V((***byte)(nil))},
3073 {V((***int32)(nil)), V((***int32)(nil))},
3074 {V((***int64)(nil)), V((***int64)(nil))},
3075 {V((chan int)(nil)), V((<-chan int)(nil))},
3076 {V((chan int)(nil)), V((chan<- int)(nil))},
3077 {V((chan string)(nil)), V((<-chan string)(nil))},
3078 {V((chan string)(nil)), V((chan<- string)(nil))},
3079 {V((chan byte)(nil)), V((chan byte)(nil))},
3080 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3081 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3082 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3083 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3084 {V([]uint(nil)), V([]uint(nil))},
3085 {V([]int(nil)), V([]int(nil))},
3086 {V(new(interface{})), V(new(interface{}))},
3087 {V(new(io.Reader)), V(new(io.Reader))},
3088 {V(new(io.Writer)), V(new(io.Writer))},
3090 // interfaces
3091 {V(int(1)), EmptyInterfaceV(int(1))},
3092 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3093 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3094 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3095 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
3098 func TestConvert(t *testing.T) {
3099 canConvert := map[[2]Type]bool{}
3100 all := map[Type]bool{}
3102 for _, tt := range convertTests {
3103 t1 := tt.in.Type()
3104 if !t1.ConvertibleTo(t1) {
3105 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
3106 continue
3109 t2 := tt.out.Type()
3110 if !t1.ConvertibleTo(t2) {
3111 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
3112 continue
3115 all[t1] = true
3116 all[t2] = true
3117 canConvert[[2]Type{t1, t2}] = true
3119 // vout1 represents the in value converted to the in type.
3120 v1 := tt.in
3121 vout1 := v1.Convert(t1)
3122 out1 := vout1.Interface()
3123 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
3124 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
3127 // vout2 represents the in value converted to the out type.
3128 vout2 := v1.Convert(t2)
3129 out2 := vout2.Interface()
3130 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
3131 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
3134 // vout3 represents a new value of the out type, set to vout2. This makes
3135 // sure the converted value vout2 is really usable as a regular value.
3136 vout3 := New(t2).Elem()
3137 vout3.Set(vout2)
3138 out3 := vout3.Interface()
3139 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
3140 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
3143 if IsRO(v1) {
3144 t.Errorf("table entry %v is RO, should not be", v1)
3146 if IsRO(vout1) {
3147 t.Errorf("self-conversion output %v is RO, should not be", vout1)
3149 if IsRO(vout2) {
3150 t.Errorf("conversion output %v is RO, should not be", vout2)
3152 if IsRO(vout3) {
3153 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
3155 if !IsRO(MakeRO(v1).Convert(t1)) {
3156 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
3158 if !IsRO(MakeRO(v1).Convert(t2)) {
3159 t.Errorf("RO conversion output %v is not RO, should be", v1)
3163 // Assume that of all the types we saw during the tests,
3164 // if there wasn't an explicit entry for a conversion between
3165 // a pair of types, then it's not to be allowed. This checks for
3166 // things like 'int64' converting to '*int'.
3167 for t1 := range all {
3168 for t2 := range all {
3169 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
3170 if ok := t1.ConvertibleTo(t2); ok != expectOK {
3171 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
3177 func TestOverflow(t *testing.T) {
3178 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
3179 t.Errorf("%v wrongly overflows float64", 1e300)
3182 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
3183 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
3184 t.Errorf("%v wrongly overflows float32", maxFloat32)
3186 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
3187 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
3188 t.Errorf("%v should overflow float32", ovfFloat32)
3190 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
3191 t.Errorf("%v should overflow float32", -ovfFloat32)
3194 maxInt32 := int64(0x7fffffff)
3195 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
3196 t.Errorf("%v wrongly overflows int32", maxInt32)
3198 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
3199 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3201 ovfInt32 := int64(1 << 31)
3202 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
3203 t.Errorf("%v should overflow int32", ovfInt32)
3206 maxUint32 := uint64(0xffffffff)
3207 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
3208 t.Errorf("%v wrongly overflows uint32", maxUint32)
3210 ovfUint32 := uint64(1 << 32)
3211 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
3212 t.Errorf("%v should overflow uint32", ovfUint32)
3216 func checkSameType(t *testing.T, x, y interface{}) {
3217 if TypeOf(x) != TypeOf(y) {
3218 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
3222 func TestArrayOf(t *testing.T) {
3223 // check construction and use of type not in binary
3224 type T int
3225 at := ArrayOf(10, TypeOf(T(1)))
3226 v := New(at).Elem()
3227 for i := 0; i < v.Len(); i++ {
3228 v.Index(i).Set(ValueOf(T(i)))
3230 s := fmt.Sprint(v.Interface())
3231 want := "[0 1 2 3 4 5 6 7 8 9]"
3232 if s != want {
3233 t.Errorf("constructed array = %s, want %s", s, want)
3236 // check that type already in binary is found
3237 checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
3240 func TestSliceOf(t *testing.T) {
3241 // check construction and use of type not in binary
3242 type T int
3243 st := SliceOf(TypeOf(T(1)))
3244 v := MakeSlice(st, 10, 10)
3245 runtime.GC()
3246 for i := 0; i < v.Len(); i++ {
3247 v.Index(i).Set(ValueOf(T(i)))
3248 runtime.GC()
3250 s := fmt.Sprint(v.Interface())
3251 want := "[0 1 2 3 4 5 6 7 8 9]"
3252 if s != want {
3253 t.Errorf("constructed slice = %s, want %s", s, want)
3256 // check that type already in binary is found
3257 type T1 int
3258 checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
3261 func TestSliceOverflow(t *testing.T) {
3262 // check that MakeSlice panics when size of slice overflows uint
3263 const S = 1e6
3264 s := uint(S)
3265 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
3266 if l*s >= s {
3267 t.Fatal("slice size does not overflow")
3269 var x [S]byte
3270 st := SliceOf(TypeOf(x))
3271 defer func() {
3272 err := recover()
3273 if err == nil {
3274 t.Fatal("slice overflow does not panic")
3277 MakeSlice(st, int(l), int(l))
3280 func TestSliceOfGC(t *testing.T) {
3281 type T *uintptr
3282 tt := TypeOf(T(nil))
3283 st := SliceOf(tt)
3284 const n = 100
3285 var x []interface{}
3286 for i := 0; i < n; i++ {
3287 v := MakeSlice(st, n, n)
3288 for j := 0; j < v.Len(); j++ {
3289 p := new(uintptr)
3290 *p = uintptr(i*n + j)
3291 v.Index(j).Set(ValueOf(p).Convert(tt))
3293 x = append(x, v.Interface())
3295 runtime.GC()
3297 for i, xi := range x {
3298 v := ValueOf(xi)
3299 for j := 0; j < v.Len(); j++ {
3300 k := v.Index(j).Elem().Interface()
3301 if k != uintptr(i*n+j) {
3302 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3308 func TestChanOf(t *testing.T) {
3309 // check construction and use of type not in binary
3310 type T string
3311 ct := ChanOf(BothDir, TypeOf(T("")))
3312 v := MakeChan(ct, 2)
3313 runtime.GC()
3314 v.Send(ValueOf(T("hello")))
3315 runtime.GC()
3316 v.Send(ValueOf(T("world")))
3317 runtime.GC()
3319 sv1, _ := v.Recv()
3320 sv2, _ := v.Recv()
3321 s1 := sv1.String()
3322 s2 := sv2.String()
3323 if s1 != "hello" || s2 != "world" {
3324 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
3327 // check that type already in binary is found
3328 type T1 int
3329 checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
3332 func TestChanOfGC(t *testing.T) {
3333 done := make(chan bool, 1)
3334 go func() {
3335 select {
3336 case <-done:
3337 case <-time.After(5 * time.Second):
3338 panic("deadlock in TestChanOfGC")
3342 defer func() {
3343 done <- true
3346 type T *uintptr
3347 tt := TypeOf(T(nil))
3348 ct := ChanOf(BothDir, tt)
3350 // NOTE: The garbage collector handles allocated channels specially,
3351 // so we have to save pointers to channels in x; the pointer code will
3352 // use the gc info in the newly constructed chan type.
3353 const n = 100
3354 var x []interface{}
3355 for i := 0; i < n; i++ {
3356 v := MakeChan(ct, n)
3357 for j := 0; j < n; j++ {
3358 p := new(uintptr)
3359 *p = uintptr(i*n + j)
3360 v.Send(ValueOf(p).Convert(tt))
3362 pv := New(ct)
3363 pv.Elem().Set(v)
3364 x = append(x, pv.Interface())
3366 runtime.GC()
3368 for i, xi := range x {
3369 v := ValueOf(xi).Elem()
3370 for j := 0; j < n; j++ {
3371 pv, _ := v.Recv()
3372 k := pv.Elem().Interface()
3373 if k != uintptr(i*n+j) {
3374 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3380 func TestMapOf(t *testing.T) {
3381 // check construction and use of type not in binary
3382 type K string
3383 type V float64
3385 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
3386 runtime.GC()
3387 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
3388 runtime.GC()
3390 s := fmt.Sprint(v.Interface())
3391 want := "map[a:1]"
3392 if s != want {
3393 t.Errorf("constructed map = %s, want %s", s, want)
3396 // check that type already in binary is found
3397 checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
3399 // check that invalid key type panics
3400 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
3403 func TestMapOfGCKeys(t *testing.T) {
3404 type T *uintptr
3405 tt := TypeOf(T(nil))
3406 mt := MapOf(tt, TypeOf(false))
3408 // NOTE: The garbage collector handles allocated maps specially,
3409 // so we have to save pointers to maps in x; the pointer code will
3410 // use the gc info in the newly constructed map type.
3411 const n = 100
3412 var x []interface{}
3413 for i := 0; i < n; i++ {
3414 v := MakeMap(mt)
3415 for j := 0; j < n; j++ {
3416 p := new(uintptr)
3417 *p = uintptr(i*n + j)
3418 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
3420 pv := New(mt)
3421 pv.Elem().Set(v)
3422 x = append(x, pv.Interface())
3424 runtime.GC()
3426 for i, xi := range x {
3427 v := ValueOf(xi).Elem()
3428 var out []int
3429 for _, kv := range v.MapKeys() {
3430 out = append(out, int(kv.Elem().Interface().(uintptr)))
3432 sort.Ints(out)
3433 for j, k := range out {
3434 if k != i*n+j {
3435 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3441 func TestMapOfGCValues(t *testing.T) {
3442 type T *uintptr
3443 tt := TypeOf(T(nil))
3444 mt := MapOf(TypeOf(1), tt)
3446 // NOTE: The garbage collector handles allocated maps specially,
3447 // so we have to save pointers to maps in x; the pointer code will
3448 // use the gc info in the newly constructed map type.
3449 const n = 100
3450 var x []interface{}
3451 for i := 0; i < n; i++ {
3452 v := MakeMap(mt)
3453 for j := 0; j < n; j++ {
3454 p := new(uintptr)
3455 *p = uintptr(i*n + j)
3456 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
3458 pv := New(mt)
3459 pv.Elem().Set(v)
3460 x = append(x, pv.Interface())
3462 runtime.GC()
3464 for i, xi := range x {
3465 v := ValueOf(xi).Elem()
3466 for j := 0; j < n; j++ {
3467 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
3468 if k != uintptr(i*n+j) {
3469 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3475 type B1 struct {
3476 X int
3477 Y int
3478 Z int
3481 func BenchmarkFieldByName1(b *testing.B) {
3482 t := TypeOf(B1{})
3483 for i := 0; i < b.N; i++ {
3484 t.FieldByName("Z")
3488 func BenchmarkFieldByName2(b *testing.B) {
3489 t := TypeOf(S3{})
3490 for i := 0; i < b.N; i++ {
3491 t.FieldByName("B")
3495 type R0 struct {
3502 type R1 struct {
3509 type R2 R1
3510 type R3 R1
3511 type R4 R1
3513 type R5 struct {
3515 *R10
3516 *R11
3517 *R12
3520 type R6 R5
3521 type R7 R5
3522 type R8 R5
3524 type R9 struct {
3525 *R13
3526 *R14
3527 *R15
3528 *R16
3531 type R10 R9
3532 type R11 R9
3533 type R12 R9
3535 type R13 struct {
3536 *R17
3537 *R18
3538 *R19
3539 *R20
3542 type R14 R13
3543 type R15 R13
3544 type R16 R13
3546 type R17 struct {
3547 *R21
3548 *R22
3549 *R23
3550 *R24
3553 type R18 R17
3554 type R19 R17
3555 type R20 R17
3557 type R21 struct {
3558 X int
3561 type R22 R21
3562 type R23 R21
3563 type R24 R21
3565 func TestEmbed(t *testing.T) {
3566 typ := TypeOf(R0{})
3567 f, ok := typ.FieldByName("X")
3568 if ok {
3569 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
3573 func BenchmarkFieldByName3(b *testing.B) {
3574 t := TypeOf(R0{})
3575 for i := 0; i < b.N; i++ {
3576 t.FieldByName("X")
3580 type S struct {
3581 i1 int64
3582 i2 int64
3585 func BenchmarkInterfaceBig(b *testing.B) {
3586 v := ValueOf(S{})
3587 for i := 0; i < b.N; i++ {
3588 v.Interface()
3590 b.StopTimer()
3593 func TestAllocsInterfaceBig(t *testing.T) {
3594 if testing.Short() {
3595 t.Skip("skipping malloc count in short mode")
3597 v := ValueOf(S{})
3598 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
3599 t.Error("allocs:", allocs)
3603 func BenchmarkInterfaceSmall(b *testing.B) {
3604 v := ValueOf(int64(0))
3605 for i := 0; i < b.N; i++ {
3606 v.Interface()
3610 func TestAllocsInterfaceSmall(t *testing.T) {
3611 if testing.Short() {
3612 t.Skip("skipping malloc count in short mode")
3614 v := ValueOf(int64(0))
3615 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
3616 t.Error("allocs:", allocs)
3620 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
3621 // The basic usage is:
3623 // for x.Next() {
3624 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
3625 // }
3627 // Each iteration of the loop returns a different set of results, until all
3628 // possible result sets have been explored. It is okay for different code paths
3629 // to make different method call sequences on x, but there must be no
3630 // other source of non-determinism in the call sequences.
3632 // When faced with a new decision, x chooses randomly. Future explorations
3633 // of that path will choose successive values for the result. Thus, stopping
3634 // the loop after a fixed number of iterations gives somewhat stochastic
3635 // testing.
3637 // Example:
3639 // for x.Next() {
3640 // v := make([]bool, x.Choose(4))
3641 // for i := range v {
3642 // v[i] = x.Maybe()
3643 // }
3644 // fmt.Println(v)
3645 // }
3647 // prints (in some order):
3649 // []
3650 // [false]
3651 // [true]
3652 // [false false]
3653 // [false true]
3654 // ...
3655 // [true true]
3656 // [false false false]
3657 // ...
3658 // [true true true]
3659 // [false false false false]
3660 // ...
3661 // [true true true true]
3663 type exhaustive struct {
3664 r *rand.Rand
3665 pos int
3666 last []choice
3669 type choice struct {
3670 off int
3671 n int
3672 max int
3675 func (x *exhaustive) Next() bool {
3676 if x.r == nil {
3677 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
3679 x.pos = 0
3680 if x.last == nil {
3681 x.last = []choice{}
3682 return true
3684 for i := len(x.last) - 1; i >= 0; i-- {
3685 c := &x.last[i]
3686 if c.n+1 < c.max {
3687 c.n++
3688 x.last = x.last[:i+1]
3689 return true
3692 return false
3695 func (x *exhaustive) Choose(max int) int {
3696 if x.pos >= len(x.last) {
3697 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
3699 c := &x.last[x.pos]
3700 x.pos++
3701 if c.max != max {
3702 panic("inconsistent use of exhaustive tester")
3704 return (c.n + c.off) % max
3707 func (x *exhaustive) Maybe() bool {
3708 return x.Choose(2) == 1
3711 func GCFunc(args []Value) []Value {
3712 runtime.GC()
3713 return []Value{}
3716 func TestReflectFuncTraceback(t *testing.T) {
3717 f := MakeFunc(TypeOf(func() {}), GCFunc)
3718 f.Call([]Value{})
3721 func (p Point) GCMethod(k int) int {
3722 runtime.GC()
3723 return k + p.x
3726 func TestReflectMethodTraceback(t *testing.T) {
3727 p := Point{3, 4}
3728 m := ValueOf(p).MethodByName("GCMethod")
3729 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
3730 if i != 8 {
3731 t.Errorf("Call returned %d; want 8", i)
3735 func TestBigZero(t *testing.T) {
3736 const size = 1 << 10
3737 var v [size]byte
3738 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
3739 for i := 0; i < size; i++ {
3740 if z[i] != 0 {
3741 t.Fatalf("Zero object not all zero, index %d", i)
3746 func TestFieldByIndexNil(t *testing.T) {
3747 type P struct {
3748 F int
3750 type T struct {
3753 v := ValueOf(T{})
3755 v.FieldByName("P") // should be fine
3757 defer func() {
3758 if err := recover(); err == nil {
3759 t.Fatalf("no error")
3760 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
3761 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
3764 v.FieldByName("F") // should panic
3766 t.Fatalf("did not panic")
3769 // Given
3770 // type Outer struct {
3771 // *Inner
3772 // ...
3773 // }
3774 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
3775 // The implementation is logically:
3776 // func (p *Outer) M() {
3777 // (p.Inner).M()
3778 // }
3779 // but since the only change here is the replacement of one pointer receiver with another,
3780 // the actual generated code overwrites the original receiver with the p.Inner pointer and
3781 // then jumps to the M method expecting the *Inner receiver.
3783 // During reflect.Value.Call, we create an argument frame and the associated data structures
3784 // to describe it to the garbage collector, populate the frame, call reflect.call to
3785 // run a function call using that frame, and then copy the results back out of the frame.
3786 // The reflect.call function does a memmove of the frame structure onto the
3787 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
3788 // the frame structure (to preserve the outputs).
3790 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
3791 // were for the full stack frame. However, in the case where the called function was
3792 // one of these wrappers, the rewritten receiver is almost certainly a different type
3793 // than the original receiver. This is not a problem on the stack, where we use the
3794 // program counter to determine the type information and understand that
3795 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
3796 // memory word is now an *Inner. But in the statically typed argument frame created
3797 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
3798 // off the stack into the frame will store an *Inner there, and then if a garbage collection
3799 // happens to scan that argument frame before it is discarded, it will scan the *Inner
3800 // memory as if it were an *Outer. If the two have different memory layouts, the
3801 // collection will intepret the memory incorrectly.
3803 // One such possible incorrect interpretation is to treat two arbitrary memory words
3804 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
3805 // an interface requires dereferencing the itab word, the misinterpretation will try to
3806 // deference Inner.P1, causing a crash during garbage collection.
3808 // This came up in a real program in issue 7725.
3810 type Outer struct {
3811 *Inner
3812 R io.Reader
3815 type Inner struct {
3816 X *Outer
3817 P1 uintptr
3818 P2 uintptr
3821 func (pi *Inner) M() {
3822 // Clear references to pi so that the only way the
3823 // garbage collection will find the pointer is in the
3824 // argument frame, typed as a *Outer.
3825 pi.X.Inner = nil
3827 // Set up an interface value that will cause a crash.
3828 // P1 = 1 is a non-zero, so the interface looks non-nil.
3829 // P2 = pi ensures that the data word points into the
3830 // allocated heap; if not the collection skips the interface
3831 // value as irrelevant, without dereferencing P1.
3832 pi.P1 = 1
3833 pi.P2 = uintptr(unsafe.Pointer(pi))
3836 func TestCallMethodJump(t *testing.T) {
3837 // In reflect.Value.Call, trigger a garbage collection after reflect.call
3838 // returns but before the args frame has been discarded.
3839 // This is a little clumsy but makes the failure repeatable.
3840 *CallGC = true
3842 p := &Outer{Inner: new(Inner)}
3843 p.Inner.X = p
3844 ValueOf(p).Method(0).Call(nil)
3846 // Stop garbage collecting during reflect.call.
3847 *CallGC = false