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.
27 func TestBool(t
*testing
.T
) {
30 t
.Fatal("ValueOf(true).Bool() = false")
47 func isDigit(c
uint8) bool { return '0' <= c
&& c
<= '9' }
49 func assert(t
*testing
.T
, s
, want
string) {
51 t
.Errorf("have %#q want %#q", s
, want
)
55 func typestring(i
interface{}) string { return TypeOf(i
).String() }
57 var typeTests
= []pair
{
58 {struct{ x
int }{}, "int"},
59 {struct{ x
int8 }{}, "int8"},
60 {struct{ x
int16 }{}, "int16"},
61 {struct{ x
int32 }{}, "int32"},
62 {struct{ x
int64 }{}, "int64"},
63 {struct{ x
uint }{}, "uint"},
64 {struct{ x
uint8 }{}, "uint8"},
65 {struct{ x
uint16 }{}, "uint16"},
66 {struct{ x
uint32 }{}, "uint32"},
67 {struct{ x
uint64 }{}, "uint64"},
68 {struct{ x
float32 }{}, "float32"},
69 {struct{ x
float64 }{}, "float64"},
70 {struct{ x
int8 }{}, "int8"},
71 {struct{ x (**int8) }{}, "**int8"},
72 {struct{ x (**integer
) }{}, "**reflect_test.integer"},
73 {struct{ x ([32]int32) }{}, "[32]int32"},
74 {struct{ x ([]int8) }{}, "[]int8"},
75 {struct{ x (map[string]int32) }{}, "map[string]int32"},
76 {struct{ x (chan<- string) }{}, "chan<- string"},
83 "struct { c chan *int32; d float32 }",
85 {struct{ x (func(a
int8, b
int32)) }{}, "func(int8, int32)"},
88 c
func(chan *integer
, *int8)
91 "struct { c func(chan *reflect_test.integer, *int8) }",
99 "struct { a int8; b int32 }",
108 "struct { a int8; b int8; c int32 }",
118 "struct { a int8; b int8; c int8; d int32 }",
129 "struct { a int8; b int8; c int8; d int8; e int32 }",
141 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
145 a
int8 `reflect:"hi there"`
148 `struct { a int8 "reflect:\"hi there\"" }`,
152 a
int8 `reflect:"hi \x00there\t\n\"\\"`
155 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
162 "struct { f func(...int) }",
166 a(func(func(int) int) func(func(int)) int)
170 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
174 var valueTests
= []pair
{
185 {new(float32), "256.25"},
186 {new(float64), "512.125"},
187 {new(complex64
), "532.125+10i"},
188 {new(complex128
), "564.25+1i"},
189 {new(string), "stringy cheese"},
191 {new(*int8), "*int8(0)"},
192 {new(**int8), "**int8(0)"},
193 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
194 {new(**integer
), "**reflect_test.integer(0)"},
195 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
196 {new(chan<- string), "chan<- string"},
197 {new(func(a
int8, b
int32)), "func(int8, int32)(0)"},
202 "struct { c chan *int32; d float32 }{chan *int32, 0}",
204 {new(struct{ c
func(chan *integer
, *int8) }),
205 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
211 "struct { a int8; b int32 }{0, 0}",
218 "struct { a int8; b int8; c int32 }{0, 0, 0}",
222 func testType(t
*testing
.T
, i
int, typ Type
, want
string) {
225 t
.Errorf("#%d: have %#q, want %#q", i
, s
, want
)
229 func TestTypes(t
*testing
.T
) {
230 for i
, tt
:= range typeTests
{
231 testType(t
, i
, ValueOf(tt
.i
).Field(0).Type(), tt
.s
)
235 func TestSet(t
*testing
.T
) {
236 for i
, tt
:= range valueTests
{
265 v
.SetComplex(532.125 + 10i
)
267 v
.SetComplex(564.25 + 1i
)
269 v
.SetString("stringy cheese")
273 s
:= valueToString(v
)
275 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
280 func TestSetValue(t
*testing
.T
) {
281 for i
, tt
:= range valueTests
{
282 v
:= ValueOf(tt
.i
).Elem()
285 v
.Set(ValueOf(int(132)))
287 v
.Set(ValueOf(int8(8)))
289 v
.Set(ValueOf(int16(16)))
291 v
.Set(ValueOf(int32(32)))
293 v
.Set(ValueOf(int64(64)))
295 v
.Set(ValueOf(uint(132)))
297 v
.Set(ValueOf(uint8(8)))
299 v
.Set(ValueOf(uint16(16)))
301 v
.Set(ValueOf(uint32(32)))
303 v
.Set(ValueOf(uint64(64)))
305 v
.Set(ValueOf(float32(256.25)))
307 v
.Set(ValueOf(512.125))
309 v
.Set(ValueOf(complex64(532.125 + 10i
)))
311 v
.Set(ValueOf(complex128(564.25 + 1i
)))
313 v
.Set(ValueOf("stringy cheese"))
317 s
:= valueToString(v
)
319 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
326 var valueToStringTests
= []pair
{
331 {T
{123, 456.75, "hello", &_i
}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
332 {new(chan *T
), "*chan *reflect_test.T(&chan *reflect_test.T)"},
333 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
334 {&[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})"},
335 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
336 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
339 func TestValueToString(t
*testing
.T
) {
340 for i
, test
:= range valueToStringTests
{
341 s
:= valueToString(ValueOf(test
.i
))
343 t
.Errorf("#%d: have %#q, want %#q", i
, s
, test
.s
)
348 func TestArrayElemSet(t
*testing
.T
) {
349 v
:= ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
350 v
.Index(4).SetInt(123)
351 s
:= valueToString(v
)
352 const want
= "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
354 t
.Errorf("[10]int: have %#q want %#q", s
, want
)
357 v
= ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
358 v
.Index(4).SetInt(123)
360 const want1
= "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
362 t
.Errorf("[]int: have %#q want %#q", s
, want1
)
366 func TestPtrPointTo(t
*testing
.T
) {
370 vi
:= ValueOf(&i
).Elem()
371 vip
.Elem().Set(vi
.Addr())
373 t
.Errorf("got %d, want 1234", *ip
)
377 vp
:= ValueOf(&ip
).Elem()
378 vp
.Set(Zero(vp
.Type()))
380 t
.Errorf("got non-nil (%p), want nil", ip
)
384 func TestPtrSetNil(t
*testing
.T
) {
388 vip
.Elem().Set(Zero(vip
.Elem().Type()))
390 t
.Errorf("got non-nil (%d), want nil", *ip
)
394 func TestMapSetNil(t
*testing
.T
) {
395 m
:= make(map[string]int)
397 vm
.Elem().Set(Zero(vm
.Elem().Type()))
399 t
.Errorf("got non-nil (%p), want nil", m
)
403 func TestAll(t
*testing
.T
) {
404 testType(t
, 1, TypeOf((int8)(0)), "int8")
405 testType(t
, 2, TypeOf((*int8)(nil)).Elem(), "int8")
407 typ
:= TypeOf((*struct {
411 testType(t
, 3, typ
, "*struct { c chan *int32; d float32 }")
413 testType(t
, 4, etyp
, "struct { c chan *int32; d float32 }")
416 testType(t
, 5, f
.Type
, "chan *int32")
418 f
, present
:= styp
.FieldByName("d")
420 t
.Errorf("FieldByName says present field is absent")
422 testType(t
, 6, f
.Type
, "float32")
424 f
, present
= styp
.FieldByName("absent")
426 t
.Errorf("FieldByName says absent field is present")
429 typ
= TypeOf([32]int32{})
430 testType(t
, 7, typ
, "[32]int32")
431 testType(t
, 8, typ
.Elem(), "int32")
433 typ
= TypeOf((map[string]*int32)(nil))
434 testType(t
, 9, typ
, "map[string]*int32")
436 testType(t
, 10, mtyp
.Key(), "string")
437 testType(t
, 11, mtyp
.Elem(), "*int32")
439 typ
= TypeOf((chan<- string)(nil))
440 testType(t
, 12, typ
, "chan<- string")
441 testType(t
, 13, typ
.Elem(), "string")
443 // make sure tag strings are not part of element type
444 typ
= TypeOf(struct {
445 d
[]uint32 `reflect:"TAG"`
447 testType(t
, 14, typ
, "[]uint32")
450 func TestInterfaceGet(t
*testing
.T
) {
455 v1
:= ValueOf(&inter
)
456 v2
:= v1
.Elem().Field(0)
457 assert(t
, v2
.Type().String(), "interface {}")
460 assert(t
, v3
.Type().String(), "float64")
463 func TestInterfaceValue(t
*testing
.T
) {
468 v1
:= ValueOf(&inter
)
469 v2
:= v1
.Elem().Field(0)
470 assert(t
, v2
.Type().String(), "interface {}")
472 assert(t
, v3
.Type().String(), "float64")
475 if _
, ok
:= i3
.(float64); !ok
{
476 t
.Error("v2.Interface() did not return float64, got ", TypeOf(i3
))
480 func TestFunctionValue(t
*testing
.T
) {
481 var x
interface{} = func() {}
483 if fmt
.Sprint(v
.Interface()) != fmt
.Sprint(x
) {
484 t
.Fatalf("TestFunction returned wrong pointer")
486 assert(t
, v
.Type().String(), "func()")
489 var appendTests
= []struct {
492 {make([]int, 2, 4), []int{22}},
493 {make([]int, 2, 4), []int{22, 33, 44}},
496 func sameInts(x
, y
[]int) bool {
497 if len(x
) != len(y
) {
500 for i
, xx
:= range x
{
508 func TestAppend(t
*testing
.T
) {
509 for i
, test
:= range appendTests
{
510 origLen
, extraLen
:= len(test
.orig
), len(test
.extra
)
511 want
:= append(test
.orig
, test
.extra
...)
512 // Convert extra from []int to []Value.
513 e0
:= make([]Value
, len(test
.extra
))
514 for j
, e
:= range test
.extra
{
517 // Convert extra from []int to *SliceValue.
518 e1
:= ValueOf(test
.extra
)
520 a0
:= ValueOf(test
.orig
)
521 have0
:= Append(a0
, e0
...).Interface().([]int)
522 if !sameInts(have0
, want
) {
523 t
.Errorf("Append #%d: have %v, want %v (%p %p)", i
, have0
, want
, test
.orig
, have0
)
525 // Check that the orig and extra slices were not modified.
526 if len(test
.orig
) != origLen
{
527 t
.Errorf("Append #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
529 if len(test
.extra
) != extraLen
{
530 t
.Errorf("Append #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
533 a1
:= ValueOf(test
.orig
)
534 have1
:= AppendSlice(a1
, e1
).Interface().([]int)
535 if !sameInts(have1
, want
) {
536 t
.Errorf("AppendSlice #%d: have %v, want %v", i
, have1
, want
)
538 // Check that the orig and extra slices were not modified.
539 if len(test
.orig
) != origLen
{
540 t
.Errorf("AppendSlice #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
542 if len(test
.extra
) != extraLen
{
543 t
.Errorf("AppendSlice #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
548 func TestCopy(t
*testing
.T
) {
549 a
:= []int{1, 2, 3, 4, 10, 9, 8, 7}
550 b
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
551 c
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
552 for i
:= 0; i
< len(b
); i
++ {
554 t
.Fatalf("b != c before test")
559 aa
:= ValueOf(&a1
).Elem()
560 ab
:= ValueOf(&b1
).Elem()
561 for tocopy
:= 1; tocopy
<= 7; tocopy
++ {
565 for i
:= 0; i
< tocopy
; i
++ {
567 t
.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
568 tocopy
, i
, a
[i
], i
, b
[i
])
571 for i
:= tocopy
; i
< len(b
); i
++ {
574 t
.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
575 tocopy
, i
, a
[i
], i
, b
[i
], i
, c
[i
])
577 t
.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
578 tocopy
, i
, b
[i
], i
, c
[i
])
581 t
.Logf("tocopy=%d elem %d is okay\n", tocopy
, i
)
587 func TestCopyArray(t
*testing
.T
) {
588 a
:= [8]int{1, 2, 3, 4, 10, 9, 8, 7}
589 b
:= [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
591 aa
:= ValueOf(&a
).Elem()
592 ab
:= ValueOf(&b
).Elem()
594 for i
:= 0; i
< len(a
); i
++ {
596 t
.Errorf("(i) a[%d]=%d, b[%d]=%d", i
, a
[i
], i
, b
[i
])
599 for i
:= len(a
); i
< len(b
); i
++ {
601 t
.Errorf("(ii) b[%d]=%d, c[%d]=%d", i
, b
[i
], i
, c
[i
])
603 t
.Logf("elem %d is okay\n", i
)
608 func TestBigUnnamedStruct(t
*testing
.T
) {
609 b
:= struct{ a
, b
, c
, d
int64 }{1, 2, 3, 4}
611 b1
:= v
.Interface().(struct {
614 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d
{
615 t
.Errorf("ValueOf(%v).Interface().(*Big) = %v", b
, b1
)
623 func TestBigStruct(t
*testing
.T
) {
624 b
:= big
{1, 2, 3, 4, 5}
626 b1
:= v
.Interface().(big
)
627 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d || b1
.e
!= b
.e
{
628 t
.Errorf("ValueOf(%v).Interface().(big) = %v", b
, b1
)
639 type DeepEqualTest
struct {
644 // Simple functions for DeepEqual tests.
648 fn3
= func() { fn1() } // Not nil.
653 var deepEqualTests
= []DeepEqualTest
{
657 {int32(1), int32(1), true},
659 {float32(0.5), float32(0.5), true},
660 {"hello", "hello", true},
661 {make([]int, 10), make([]int, 10), true},
662 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
663 {Basic
{1, 0.5}, Basic
{1, 0.5}, true},
664 {error(nil), error(nil), true},
665 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
670 {int32(1), int32(2), false},
672 {float32(0.5), float32(0.6), false},
673 {"hello", "hey", false},
674 {make([]int, 10), make([]int, 11), false},
675 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
676 {Basic
{1, 0.5}, Basic
{1, 0.6}, false},
677 {Basic
{1, 0}, Basic
{2, 0}, false},
678 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
679 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
680 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
681 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
686 {[][]int{{1}}, [][]int{{2}}, false},
687 {math
.NaN(), math
.NaN(), false},
688 {&[1]float64{math
.NaN()}, &[1]float64{math
.NaN()}, false},
689 {&[1]float64{math
.NaN()}, self
{}, true},
690 {[]float64{math
.NaN()}, []float64{math
.NaN()}, false},
691 {[]float64{math
.NaN()}, self
{}, true},
692 {map[float64]float64{math
.NaN(): 1}, map[float64]float64{1: 2}, false},
693 {map[float64]float64{math
.NaN(): 1}, self
{}, true},
695 // Nil vs empty: not the same.
696 {[]int{}, []int(nil), false},
697 {[]int{}, []int{}, true},
698 {[]int(nil), []int(nil), true},
699 {map[int]int{}, map[int]int(nil), false},
700 {map[int]int{}, map[int]int{}, true},
701 {map[int]int(nil), map[int]int(nil), true},
705 {int32(1), int64(1), false},
706 {0.5, "hello", false},
707 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
708 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
709 {Basic
{1, 0.5}, NotBasic
{1, 0.5}, false},
710 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
713 func TestDeepEqual(t
*testing
.T
) {
714 for _
, test
:= range deepEqualTests
{
715 if test
.b
== (self
{}) {
718 if r
:= DeepEqual(test
.a
, test
.b
); r
!= test
.eq
{
719 t
.Errorf("DeepEqual(%v, %v) = %v, want %v", test
.a
, test
.b
, r
, test
.eq
)
724 func TestTypeOf(t
*testing
.T
) {
725 // Special case for nil
726 if typ
:= TypeOf(nil); typ
!= nil {
727 t
.Errorf("expected nil type for nil value; got %v", typ
)
729 for _
, test
:= range deepEqualTests
{
734 typ
:= TypeOf(test
.a
)
736 t
.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test
.a
, typ
, test
.a
, v
.Type())
741 type Recursive
struct {
746 func TestDeepEqualRecursiveStruct(t
*testing
.T
) {
747 a
, b
:= new(Recursive
), new(Recursive
)
748 *a
= Recursive
{12, a
}
749 *b
= Recursive
{12, b
}
750 if !DeepEqual(a
, b
) {
751 t
.Error("DeepEqual(recursive same) = false, want true")
755 type _Complex
struct {
759 d
map[float64]float64
762 func TestDeepEqualComplexStruct(t
*testing
.T
) {
763 m
:= make(map[float64]float64)
764 stra
, strb
:= "hello", "hello"
765 a
, b
:= new(_Complex
), new(_Complex
)
766 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
767 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
768 if !DeepEqual(a
, b
) {
769 t
.Error("DeepEqual(complex same) = false, want true")
773 func TestDeepEqualComplexStructInequality(t
*testing
.T
) {
774 m
:= make(map[float64]float64)
775 stra
, strb
:= "hello", "helloo" // Difference is here
776 a
, b
:= new(_Complex
), new(_Complex
)
777 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
778 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
780 t
.Error("DeepEqual(complex different) = true, want false")
788 func TestDeepEqualUnexportedMap(t
*testing
.T
) {
789 // Check that DeepEqual can look at unexported fields.
790 x1
:= UnexpT
{map[int]int{1: 2}}
791 x2
:= UnexpT
{map[int]int{1: 2}}
792 if !DeepEqual(&x1
, &x2
) {
793 t
.Error("DeepEqual(x1, x2) = false, want true")
796 y1
:= UnexpT
{map[int]int{2: 3}}
797 if DeepEqual(&x1
, &y1
) {
798 t
.Error("DeepEqual(x1, y1) = true, want false")
802 func check2ndField(x
interface{}, offs
uintptr, t
*testing
.T
) {
804 f
:= s
.Type().Field(1)
805 if f
.Offset
!= offs
{
806 t
.Error("mismatched offsets in structure alignment:", f
.Offset
, offs
)
810 // Check that structure alignment & offsets viewed through reflect agree with those
811 // from the compiler itself.
812 func TestAlignment(t
*testing
.T
) {
813 type T1inner
struct {
820 type T2inner
struct {
828 x
:= T1
{T1inner
{2}, 17}
829 check2ndField(x
, uintptr(unsafe
.Pointer(&x
.f
))-uintptr(unsafe
.Pointer(&x
)), t
)
831 x1
:= T2
{T2inner
{2, 3}, 17}
832 check2ndField(x1
, uintptr(unsafe
.Pointer(&x1
.f
))-uintptr(unsafe
.Pointer(&x1
)), t
)
835 func Nil(a
interface{}, t
*testing
.T
) {
836 n
:= ValueOf(a
).Field(0)
838 t
.Errorf("%v should be nil", a
)
842 func NotNil(a
interface{}, t
*testing
.T
) {
843 n
:= ValueOf(a
).Field(0)
845 t
.Errorf("value of type %v should not be nil", ValueOf(a
).Type().String())
849 func TestIsNil(t
*testing
.T
) {
850 // These implement IsNil.
851 // Wrap in extra struct to hide interface type.
852 doNil
:= []interface{}{
854 struct{ x
interface{} }{},
855 struct{ x
map[string]int }{},
856 struct{ x
func() bool }{},
857 struct{ x
chan int }{},
858 struct{ x
[]string }{},
860 for _
, ts
:= range doNil
{
861 ty
:= TypeOf(ts
).Field(0).Type
863 v
.IsNil() // panics if not okay to call
866 // Check the implementations
878 si
.x
= make([]int, 10)
885 ci
.x
= make(chan int)
892 mi
.x
= make(map[int]int)
910 func TestInterfaceExtraction(t
*testing
.T
) {
916 v
:= Indirect(ValueOf(&s
)).Field(0).Interface()
917 if v
!= s
.W
.(interface{}) {
918 t
.Error("Interface() on interface: ", v
, s
.W
)
922 func TestNilPtrValueSub(t
*testing
.T
) {
924 if pv
:= ValueOf(pi
); pv
.Elem().IsValid() {
925 t
.Error("ValueOf((*int)(nil)).Elem().IsValid()")
929 func TestMap(t
*testing
.T
) {
930 m
:= map[string]int{"a": 1, "b": 2}
932 if n
:= mv
.Len(); n
!= len(m
) {
933 t
.Errorf("Len = %d, want %d", n
, len(m
))
936 newmap
:= MakeMap(mv
.Type())
937 for k
, v
:= range m
{
938 // Check that returned Keys match keys in range.
939 // These aren't required to be in the same order.
941 for _
, kv
:= range keys
{
942 if kv
.String() == k
{
948 t
.Errorf("Missing key %q", k
)
951 // Check that value lookup is correct.
952 vv
:= mv
.MapIndex(ValueOf(k
))
953 if vi
:= vv
.Int(); vi
!= int64(v
) {
954 t
.Errorf("Key %q: have value %d, want %d", k
, vi
, v
)
957 // Copy into new map.
958 newmap
.SetMapIndex(ValueOf(k
), ValueOf(v
))
960 vv
:= mv
.MapIndex(ValueOf("not-present"))
962 t
.Errorf("Invalid key: got non-nil value %s", valueToString(vv
))
965 newm
:= newmap
.Interface().(map[string]int)
966 if len(newm
) != len(m
) {
967 t
.Errorf("length after copy: newm=%d, m=%d", len(newm
), len(m
))
970 for k
, v
:= range newm
{
973 t
.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k
, v
, k
, mv
, ok
)
977 newmap
.SetMapIndex(ValueOf("a"), Value
{})
980 t
.Errorf("newm[\"a\"] = %d after delete", v
)
983 mv
= ValueOf(&m
).Elem()
984 mv
.Set(Zero(mv
.Type()))
986 t
.Errorf("mv.Set(nil) failed")
990 func TestNilMap(t
*testing
.T
) {
995 t
.Errorf(">0 keys for nil map: %v", keys
)
998 // Check that value for missing key is zero.
999 x
:= mv
.MapIndex(ValueOf("hello"))
1000 if x
.Kind() != Invalid
{
1001 t
.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x
)
1004 // Check big value too.
1005 var mbig
map[string][10 << 20]byte
1006 x
= ValueOf(mbig
).MapIndex(ValueOf("hello"))
1007 if x
.Kind() != Invalid
{
1008 t
.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x
)
1011 // Test that deletes from a nil map succeed.
1012 mv
.SetMapIndex(ValueOf("hi"), Value
{})
1015 func TestChan(t
*testing
.T
) {
1016 for loop
:= 0; loop
< 2; loop
++ {
1020 // check both ways to allocate channels
1023 c
= make(chan int, 1)
1026 cv
= MakeChan(TypeOf(c
), 1)
1027 c
= cv
.Interface().(chan int)
1032 if i
:= <-c
; i
!= 2 {
1033 t
.Errorf("reflect Send 2, native recv %d", i
)
1038 if i
, ok
:= cv
.Recv(); i
.Int() != 3 ||
!ok
{
1039 t
.Errorf("native send 3, reflect Recv %d, %t", i
.Int(), ok
)
1043 val
, ok
:= cv
.TryRecv()
1044 if val
.IsValid() || ok
{
1045 t
.Errorf("TryRecv on empty chan: %s, %t", valueToString(val
), ok
)
1050 val
, ok
= cv
.TryRecv()
1052 t
.Errorf("TryRecv on ready chan got nil")
1053 } else if i
:= val
.Int(); i
!= 4 ||
!ok
{
1054 t
.Errorf("native send 4, TryRecv %d, %t", i
, ok
)
1059 ok
= cv
.TrySend(ValueOf(5))
1062 t
.Errorf("TrySend on full chan succeeded: value %d", i
)
1066 ok
= cv
.TrySend(ValueOf(6))
1068 t
.Errorf("TrySend on empty chan failed")
1071 t
.Errorf("TrySend failed but it did send %d", x
)
1075 if i
= <-c
; i
!= 6 {
1076 t
.Errorf("TrySend 6, recv %d", i
)
1083 if i
, ok
:= cv
.Recv(); i
.Int() != 123 ||
!ok
{
1084 t
.Errorf("send 123 then close; Recv %d, %t", i
.Int(), ok
)
1086 if i
, ok
:= cv
.Recv(); i
.Int() != 0 || ok
{
1087 t
.Errorf("after close Recv %d, %t", i
.Int(), ok
)
1091 // check creation of unbuffered channel
1093 cv
:= MakeChan(TypeOf(c
), 0)
1094 c
= cv
.Interface().(chan int)
1095 if cv
.TrySend(ValueOf(7)) {
1096 t
.Errorf("TrySend on sync chan succeeded")
1098 if v
, ok
:= cv
.TryRecv(); v
.IsValid() || ok
{
1099 t
.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v
.IsValid(), ok
)
1103 cv
= MakeChan(TypeOf(c
), 10)
1104 c
= cv
.Interface().(chan int)
1105 for i
:= 0; i
< 3; i
++ {
1108 if l
, m
:= cv
.Len(), cv
.Cap(); l
!= len(c
) || m
!= cap(c
) {
1109 t
.Errorf("Len/Cap = %d/%d want %d/%d", l
, m
, len(c
), cap(c
))
1113 // caseInfo describes a single case in a select test.
1114 type caseInfo
struct {
1123 var allselect
= flag
.Bool("allselect", false, "exhaustive select test")
1125 func TestSelect(t
*testing
.T
) {
1126 selectWatch
.once
.Do(func() { go selectWatcher() })
1130 newop
:= func(n
int, cap int) (ch
, val Value
) {
1133 c
:= make(chan int, cap)
1137 c
:= make(chan string, cap)
1139 val
= ValueOf(fmt
.Sprint(n
))
1144 for n
:= 0; x
.Next(); n
++ {
1145 if testing
.Short() && n
>= 1000 {
1148 if n
>= 100000 && !*allselect
{
1151 if n%100000
== 0 && testing
.Verbose() {
1152 println("TestSelect", n
)
1154 var cases
[]SelectCase
1159 ch
, val
:= newop(len(cases
), 1)
1160 cases
= append(cases
, SelectCase
{
1165 info
= append(info
, caseInfo
{desc
: "ready send", canSelect
: true})
1170 ch
, val
:= newop(len(cases
), 1)
1172 cases
= append(cases
, SelectCase
{
1176 info
= append(info
, caseInfo
{desc
: "ready recv", canSelect
: true, recv
: val
})
1181 ch
, val
:= newop(len(cases
), 0)
1182 cases
= append(cases
, SelectCase
{
1189 f
:= func() { ch
.Recv() }
1190 info
= append(info
, caseInfo
{desc
: "blocking send", helper
: f
})
1192 info
= append(info
, caseInfo
{desc
: "blocking send"})
1198 ch
, val
:= newop(len(cases
), 0)
1199 cases
= append(cases
, SelectCase
{
1205 f
:= func() { ch
.Send(val
) }
1206 info
= append(info
, caseInfo
{desc
: "blocking recv", recv
: val
, helper
: f
})
1208 info
= append(info
, caseInfo
{desc
: "blocking recv"})
1214 // Maybe include value to send.
1219 cases
= append(cases
, SelectCase
{
1223 info
= append(info
, caseInfo
{desc
: "zero Chan send"})
1226 // Zero Chan receive.
1228 cases
= append(cases
, SelectCase
{
1231 info
= append(info
, caseInfo
{desc
: "zero Chan recv"})
1236 cases
= append(cases
, SelectCase
{
1238 Chan
: ValueOf((chan int)(nil)),
1241 info
= append(info
, caseInfo
{desc
: "nil Chan send"})
1246 cases
= append(cases
, SelectCase
{
1248 Chan
: ValueOf((chan int)(nil)),
1250 info
= append(info
, caseInfo
{desc
: "nil Chan recv"})
1253 // closed Chan send.
1255 ch
:= make(chan int)
1257 cases
= append(cases
, SelectCase
{
1262 info
= append(info
, caseInfo
{desc
: "closed Chan send", canSelect
: true, panic: true})
1265 // closed Chan recv.
1267 ch
, val
:= newop(len(cases
), 0)
1269 val
= Zero(val
.Type())
1270 cases
= append(cases
, SelectCase
{
1274 info
= append(info
, caseInfo
{desc
: "closed Chan recv", canSelect
: true, closed: true, recv
: val
})
1277 var helper
func() // goroutine to help the select complete
1279 // Add default? Must be last case here, but will permute.
1280 // Add the default if the select would otherwise
1281 // block forever, and maybe add it anyway.
1287 for i
, c
:= range info
{
1295 } else if c
.helper
!= nil {
1297 helpers
= append(helpers
, i
)
1300 if !canProceed || x
.Maybe() {
1301 cases
= append(cases
, SelectCase
{
1304 info
= append(info
, caseInfo
{desc
: "default", canSelect
: canBlock
})
1306 } else if canBlock
{
1307 // Select needs to communicate with another goroutine.
1308 cas
:= &info
[helpers
[x
.Choose(len(helpers
))]]
1310 cas
.canSelect
= true
1314 // Permute cases and case info.
1315 // Doing too much here makes the exhaustive loop
1316 // too exhausting, so just do two swaps.
1317 for loop
:= 0; loop
< 2; loop
++ {
1318 i
:= x
.Choose(len(cases
))
1319 j
:= x
.Choose(len(cases
))
1320 cases
[i
], cases
[j
] = cases
[j
], cases
[i
]
1321 info
[i
], info
[j
] = info
[j
], info
[i
]
1325 // We wait before kicking off a goroutine to satisfy a blocked select.
1326 // The pause needs to be big enough to let the select block before
1327 // we run the helper, but if we lose that race once in a while it's okay: the
1328 // select will just proceed immediately. Not a big deal.
1329 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1330 pause
:= 10 * time
.Microsecond
1331 if testing
.Short() {
1332 pause
= 100 * time
.Microsecond
1334 time
.AfterFunc(pause
, helper
)
1338 i
, recv
, recvOK
, panicErr
:= runSelect(cases
, info
)
1339 if panicErr
!= nil && !canPanic
{
1340 t
.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info
), panicErr
)
1342 if panicErr
== nil && canPanic
&& numCanSelect
== 1 {
1343 t
.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info
), i
)
1345 if panicErr
!= nil {
1353 recvStr
= fmt
.Sprintf(", received %v, %v", recv
.Interface(), recvOK
)
1355 t
.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info
), i
, recvStr
)
1359 t
.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info
), i
)
1363 if cases
[i
].Dir
== SelectRecv
{
1364 if !recv
.IsValid() {
1365 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, cas
.recv
.Interface(), !cas
.closed)
1367 if !cas
.recv
.IsValid() {
1368 t
.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info
), i
)
1370 if recv
.Interface() != cas
.recv
.Interface() || recvOK
!= !cas
.closed {
1371 if recv
.Interface() == cas
.recv
.Interface() && recvOK
== !cas
.closed {
1372 t
.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info
), i
, recv
.Interface(), recvOK
, recv
.Interface())
1374 t
.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info
), i
, recv
.Interface(), recvOK
, cas
.recv
.Interface(), !cas
.closed)
1377 if recv
.IsValid() || recvOK
{
1378 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, Value
{}, false)
1384 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1385 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1386 // an error describing the select and panics the entire test binary.
1387 var selectWatch
struct {
1394 func selectWatcher() {
1396 time
.Sleep(1 * time
.Second
)
1398 if selectWatch
.info
!= nil && time
.Since(selectWatch
.now
) > 10*time
.Second
{
1399 fmt
.Fprintf(os
.Stderr
, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch
.info
))
1400 panic("select stuck")
1402 selectWatch
.Unlock()
1406 // runSelect runs a single select test.
1407 // It returns the values returned by Select but also returns
1408 // a panic value if the Select panics.
1409 func runSelect(cases
[]SelectCase
, info
[]caseInfo
) (chosen
int, recv Value
, recvOK
bool, panicErr
interface{}) {
1411 panicErr
= recover()
1414 selectWatch
.info
= nil
1415 selectWatch
.Unlock()
1419 selectWatch
.now
= time
.Now()
1420 selectWatch
.info
= info
1421 selectWatch
.Unlock()
1423 chosen
, recv
, recvOK
= Select(cases
)
1427 // fmtSelect formats the information about a single select test.
1428 func fmtSelect(info
[]caseInfo
) string {
1429 var buf bytes
.Buffer
1430 fmt
.Fprintf(&buf
, "\nselect {\n")
1431 for i
, cas
:= range info
{
1432 fmt
.Fprintf(&buf
, "%d: %s", i
, cas
.desc
)
1433 if cas
.recv
.IsValid() {
1434 fmt
.Fprintf(&buf
, " val=%#v", cas
.recv
.Interface())
1437 fmt
.Fprintf(&buf
, " canselect")
1440 fmt
.Fprintf(&buf
, " panic")
1442 fmt
.Fprintf(&buf
, "\n")
1444 fmt
.Fprintf(&buf
, "}")
1450 // Difficult test for function call because of
1451 // implicit padding between arguments.
1452 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) {
1453 return b
, c
, d
, e
, f
, g
, h
1456 func TestFunc(t
*testing
.T
) {
1457 ret
:= ValueOf(dummy
).Call([]Value
{
1461 ValueOf(two
{40, 50}),
1463 ValueOf(float32(70)),
1467 t
.Fatalf("Call returned %d values, want 7", len(ret
))
1470 i
:= byte(ret
[0].Uint())
1471 j
:= int(ret
[1].Int())
1472 k
:= byte(ret
[2].Uint())
1473 l
:= ret
[3].Interface().(two
)
1474 m
:= byte(ret
[4].Uint())
1475 n
:= float32(ret
[5].Float())
1476 o
:= byte(ret
[6].Uint())
1478 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1479 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
)
1482 for i
, v
:= range ret
{
1484 t
.Errorf("result %d is addressable", i
)
1489 type emptyStruct
struct{}
1491 type nonEmptyStruct
struct {
1495 func returnEmpty() emptyStruct
{
1496 return emptyStruct
{}
1499 func takesEmpty(e emptyStruct
) {
1502 func returnNonEmpty(i
int) nonEmptyStruct
{
1503 return nonEmptyStruct
{member
: i
}
1506 func takesNonEmpty(n nonEmptyStruct
) int {
1510 func TestCallWithStruct(t
*testing
.T
) {
1511 r
:= ValueOf(returnEmpty
).Call(nil)
1512 if len(r
) != 1 || r
[0].Type() != TypeOf(emptyStruct
{}) {
1513 t
.Errorf("returning empty struct returned %#v instead", r
)
1515 r
= ValueOf(takesEmpty
).Call([]Value
{ValueOf(emptyStruct
{})})
1517 t
.Errorf("takesEmpty returned values: %#v", r
)
1519 r
= ValueOf(returnNonEmpty
).Call([]Value
{ValueOf(42)})
1520 if len(r
) != 1 || r
[0].Type() != TypeOf(nonEmptyStruct
{}) || r
[0].Field(0).Int() != 42 {
1521 t
.Errorf("returnNonEmpty returned %#v", r
)
1523 r
= ValueOf(takesNonEmpty
).Call([]Value
{ValueOf(nonEmptyStruct
{member
: 42})})
1524 if len(r
) != 1 || r
[0].Type() != TypeOf(1) || r
[0].Int() != 42 {
1525 t
.Errorf("takesNonEmpty returned %#v", r
)
1529 func BenchmarkCall(b
*testing
.B
) {
1530 fv
:= ValueOf(func(a
, b
string) {})
1532 b
.RunParallel(func(pb
*testing
.PB
) {
1533 args
:= []Value
{ValueOf("a"), ValueOf("b")}
1540 func TestMakeFunc(t
*testing
.T
) {
1542 fv
:= MakeFunc(TypeOf(f
), func(in
[]Value
) []Value
{ return in
})
1543 ValueOf(&f
).Elem().Set(fv
)
1545 // Call g with small arguments so that there is
1546 // something predictable (and different from the
1547 // correct results) in those positions on the stack.
1549 g(1, 2, 3, two
{4, 5}, 6, 7, 8)
1551 // Call constructed function f.
1552 i
, j
, k
, l
, m
, n
, o
:= f(10, 20, 30, two
{40, 50}, 60, 70, 80)
1553 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1554 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
)
1558 func TestMakeFuncInterface(t
*testing
.T
) {
1559 fn
:= func(i
int) int { return i
}
1560 incr
:= func(in
[]Value
) []Value
{
1561 return []Value
{ValueOf(int(in
[0].Int() + 1))}
1563 fv
:= MakeFunc(TypeOf(fn
), incr
)
1564 ValueOf(&fn
).Elem().Set(fv
)
1565 if r
:= fn(2); r
!= 3 {
1566 t
.Errorf("Call returned %d, want 3", r
)
1568 if r
:= fv
.Call([]Value
{ValueOf(14)})[0].Int(); r
!= 15 {
1569 t
.Errorf("Call returned %d, want 15", r
)
1571 if r
:= fv
.Interface().(func(int) int)(26); r
!= 27 {
1572 t
.Errorf("Call returned %d, want 27", r
)
1576 func TestMakeFuncVariadic(t
*testing
.T
) {
1577 // Test that variadic arguments are packed into a slice and passed as last arg
1578 fn
:= func(_
int, is
...int) []int { return nil }
1579 fv
:= MakeFunc(TypeOf(fn
), func(in
[]Value
) []Value
{ return in
[1:2] })
1580 ValueOf(&fn
).Elem().Set(fv
)
1583 if r
[0] != 2 || r
[1] != 3 {
1584 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1587 r
= fn(1, []int{2, 3}...)
1588 if r
[0] != 2 || r
[1] != 3 {
1589 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1592 r
= fv
.Call([]Value
{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
1593 if r
[0] != 2 || r
[1] != 3 {
1594 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1597 r
= fv
.CallSlice([]Value
{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1598 if r
[0] != 2 || r
[1] != 3 {
1599 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1602 f
:= fv
.Interface().(func(int, ...int) []int)
1605 if r
[0] != 2 || r
[1] != 3 {
1606 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1608 r
= f(1, []int{2, 3}...)
1609 if r
[0] != 2 || r
[1] != 3 {
1610 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1618 // This will be index 0.
1619 func (p Point
) AnotherMethod(scale
int) int {
1623 // This will be index 1.
1624 func (p Point
) Dist(scale
int) int {
1625 //println("Point.Dist", p.x, p.y, scale)
1626 return p
.x
*p
.x
*scale
+ p
.y
*p
.y
*scale
1629 // This will be index 2.
1630 func (p Point
) GCMethod(k
int) int {
1635 // This will be index 3.
1636 func (p Point
) TotalDist(points
...Point
) int {
1638 for _
, q
:= range points
{
1641 tot
+= dx
*dx
+ dy
*dy
// Should call Sqrt, but it's just a test.
1647 func TestMethod(t
*testing
.T
) {
1648 // Non-curried method of type.
1650 i
:= TypeOf(p
).Method(1).Func
.Call([]Value
{ValueOf(p
), ValueOf(10)})[0].Int()
1652 t
.Errorf("Type Method returned %d; want 250", i
)
1655 m
, ok
:= TypeOf(p
).MethodByName("Dist")
1657 t
.Fatalf("method by name failed")
1659 i
= m
.Func
.Call([]Value
{ValueOf(p
), ValueOf(11)})[0].Int()
1661 t
.Errorf("Type MethodByName returned %d; want 275", i
)
1664 i
= TypeOf(&p
).Method(1).Func
.Call([]Value
{ValueOf(&p
), ValueOf(12)})[0].Int()
1666 t
.Errorf("Pointer Type Method returned %d; want 300", i
)
1669 m
, ok
= TypeOf(&p
).MethodByName("Dist")
1671 t
.Fatalf("ptr method by name failed")
1673 i
= m
.Func
.Call([]Value
{ValueOf(&p
), ValueOf(13)})[0].Int()
1675 t
.Errorf("Pointer Type MethodByName returned %d; want 325", i
)
1678 // Curried method of value.
1679 tfunc
:= TypeOf((func(int) int)(nil))
1680 v
:= ValueOf(p
).Method(1)
1681 if tt
:= v
.Type(); tt
!= tfunc
{
1682 t
.Errorf("Value Method Type is %s; want %s", tt
, tfunc
)
1684 i
= v
.Call([]Value
{ValueOf(14)})[0].Int()
1686 t
.Errorf("Value Method returned %d; want 350", i
)
1688 v
= ValueOf(p
).MethodByName("Dist")
1689 if tt
:= v
.Type(); tt
!= tfunc
{
1690 t
.Errorf("Value MethodByName Type is %s; want %s", tt
, tfunc
)
1692 i
= v
.Call([]Value
{ValueOf(15)})[0].Int()
1694 t
.Errorf("Value MethodByName returned %d; want 375", i
)
1697 // Curried method of pointer.
1698 v
= ValueOf(&p
).Method(1)
1699 if tt
:= v
.Type(); tt
!= tfunc
{
1700 t
.Errorf("Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1702 i
= v
.Call([]Value
{ValueOf(16)})[0].Int()
1704 t
.Errorf("Pointer Value Method returned %d; want 400", i
)
1706 v
= ValueOf(&p
).MethodByName("Dist")
1707 if tt
:= v
.Type(); tt
!= tfunc
{
1708 t
.Errorf("Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1710 i
= v
.Call([]Value
{ValueOf(17)})[0].Int()
1712 t
.Errorf("Pointer Value MethodByName returned %d; want 425", i
)
1715 // Curried method of interface value.
1716 // Have to wrap interface value in a struct to get at it.
1717 // Passing it to ValueOf directly would
1718 // access the underlying Point, not the interface.
1722 pv
:= ValueOf(&x
).Elem()
1724 if tt
:= v
.Type(); tt
!= tfunc
{
1725 t
.Errorf("Interface Method Type is %s; want %s", tt
, tfunc
)
1727 i
= v
.Call([]Value
{ValueOf(18)})[0].Int()
1729 t
.Errorf("Interface Method returned %d; want 450", i
)
1731 v
= pv
.MethodByName("Dist")
1732 if tt
:= v
.Type(); tt
!= tfunc
{
1733 t
.Errorf("Interface MethodByName Type is %s; want %s", tt
, tfunc
)
1735 i
= v
.Call([]Value
{ValueOf(19)})[0].Int()
1737 t
.Errorf("Interface MethodByName returned %d; want 475", i
)
1741 func TestMethodValue(t
*testing
.T
) {
1745 // Curried method of value.
1746 tfunc
:= TypeOf((func(int) int)(nil))
1747 v
:= ValueOf(p
).Method(1)
1748 if tt
:= v
.Type(); tt
!= tfunc
{
1749 t
.Errorf("Value Method Type is %s; want %s", tt
, tfunc
)
1751 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(10)})[0].Int()
1753 t
.Errorf("Value Method returned %d; want 250", i
)
1755 v
= ValueOf(p
).MethodByName("Dist")
1756 if tt
:= v
.Type(); tt
!= tfunc
{
1757 t
.Errorf("Value MethodByName Type is %s; want %s", tt
, tfunc
)
1759 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(11)})[0].Int()
1761 t
.Errorf("Value MethodByName returned %d; want 275", i
)
1764 // Curried method of pointer.
1765 v
= ValueOf(&p
).Method(1)
1766 if tt
:= v
.Type(); tt
!= tfunc
{
1767 t
.Errorf("Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1769 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(12)})[0].Int()
1771 t
.Errorf("Pointer Value Method returned %d; want 300", i
)
1773 v
= ValueOf(&p
).MethodByName("Dist")
1774 if tt
:= v
.Type(); tt
!= tfunc
{
1775 t
.Errorf("Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1777 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(13)})[0].Int()
1779 t
.Errorf("Pointer Value MethodByName returned %d; want 325", i
)
1782 // Curried method of pointer to pointer.
1784 v
= ValueOf(&pp
).Elem().Method(1)
1785 if tt
:= v
.Type(); tt
!= tfunc
{
1786 t
.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1788 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(14)})[0].Int()
1790 t
.Errorf("Pointer Pointer Value Method returned %d; want 350", i
)
1792 v
= ValueOf(&pp
).Elem().MethodByName("Dist")
1793 if tt
:= v
.Type(); tt
!= tfunc
{
1794 t
.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1796 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(15)})[0].Int()
1798 t
.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i
)
1801 // Curried method of interface value.
1802 // Have to wrap interface value in a struct to get at it.
1803 // Passing it to ValueOf directly would
1804 // access the underlying Point, not the interface.
1810 pv
:= ValueOf(s
).Field(0)
1812 if tt
:= v
.Type(); tt
!= tfunc
{
1813 t
.Errorf("Interface Method Type is %s; want %s", tt
, tfunc
)
1815 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(16)})[0].Int()
1817 t
.Errorf("Interface Method returned %d; want 400", i
)
1819 v
= pv
.MethodByName("Dist")
1820 if tt
:= v
.Type(); tt
!= tfunc
{
1821 t
.Errorf("Interface MethodByName Type is %s; want %s", tt
, tfunc
)
1823 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(17)})[0].Int()
1825 t
.Errorf("Interface MethodByName returned %d; want 425", i
)
1829 func TestVariadicMethodValue(t
*testing
.T
) {
1831 points
:= []Point
{{20, 21}, {22, 23}, {24, 25}}
1832 want
:= int64(p
.TotalDist(points
[0], points
[1], points
[2]))
1834 // Curried method of value.
1835 tfunc
:= TypeOf((func(...Point
) int)(nil))
1836 v
:= ValueOf(p
).Method(3)
1837 if tt
:= v
.Type(); tt
!= tfunc
{
1838 t
.Errorf("Variadic Method Type is %s; want %s", tt
, tfunc
)
1840 i
:= ValueOf(v
.Interface()).Call([]Value
{ValueOf(points
[0]), ValueOf(points
[1]), ValueOf(points
[2])})[0].Int()
1842 t
.Errorf("Variadic Method returned %d; want %d", i
, want
)
1844 i
= ValueOf(v
.Interface()).CallSlice([]Value
{ValueOf(points
)})[0].Int()
1846 t
.Errorf("Variadic Method CallSlice returned %d; want %d", i
, want
)
1849 f
:= v
.Interface().(func(...Point
) int)
1850 i
= int64(f(points
[0], points
[1], points
[2]))
1852 t
.Errorf("Variadic Method Interface returned %d; want %d", i
, want
)
1854 i
= int64(f(points
...))
1856 t
.Errorf("Variadic Method Interface Slice returned %d; want %d", i
, want
)
1860 // Reflect version of $GOROOT/test/method5.go
1862 // Concrete types implementing M method.
1863 // Smaller than a word, word-sized, larger than a word.
1864 // Value and pointer receivers.
1866 type Tinter
interface {
1867 M(int, byte) (byte, int)
1872 func (v Tsmallv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1876 func (p
*Tsmallp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1880 func (v Twordv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1884 func (p
*Twordp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1886 type Tbigv
[2]uintptr
1888 func (v Tbigv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
[0]) + int(v
[1]) }
1890 type Tbigp
[2]uintptr
1892 func (p
*Tbigp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(p
[0]) + int(p
[1]) }
1894 // Again, with an unexported method.
1898 func (v tsmallv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1902 func (p
*tsmallp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1906 func (v twordv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1910 func (p
*twordp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1912 type tbigv
[2]uintptr
1914 func (v tbigv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
[0]) + int(v
[1]) }
1916 type tbigp
[2]uintptr
1918 func (p
*tbigp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(p
[0]) + int(p
[1]) }
1920 type tinter
interface {
1921 m(int, byte) (byte, int)
1924 // Embedding via pointer.
1941 func (t4 Tm4
) M(x
int, b
byte) (byte, int) { return b
, x
+ 40 }
1943 func TestMethod5(t
*testing
.T
) {
1944 CheckF
:= func(name
string, f
func(int, byte) (byte, int), inc
int) {
1946 if b
!= 99 || x
!= 1000+inc
{
1947 t
.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name
, b
, x
, 1000+inc
)
1951 CheckV
:= func(name
string, i Value
, inc
int) {
1952 bx
:= i
.Method(0).Call([]Value
{ValueOf(1000), ValueOf(byte(99))})
1953 b
:= bx
[0].Interface()
1954 x
:= bx
[1].Interface()
1955 if b
!= byte(99) || x
!= 1000+inc
{
1956 t
.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name
, b
, x
, 1000+inc
)
1959 CheckF(name
+".M", i
.Method(0).Interface().(func(int, byte) (byte, int)), inc
)
1962 var TinterType
= TypeOf(new(Tinter
)).Elem()
1963 var tinterType
= TypeOf(new(tinter
)).Elem()
1965 CheckI
:= func(name
string, i
interface{}, inc
int) {
1967 CheckV(name
, v
, inc
)
1968 CheckV("(i="+name
+")", v
.Convert(TinterType
), inc
)
1973 CheckI("&sv", &sv
, 1)
1976 CheckI("&sp", &sp
, 2)
1980 CheckI("&wv", &wv
, 3)
1983 CheckI("&wp", &wp
, 4)
1985 bv
:= Tbigv([2]uintptr{5, 6})
1986 CheckI("bv", bv
, 11)
1987 CheckI("&bv", &bv
, 11)
1989 bp
:= Tbigp([2]uintptr{7, 8})
1990 CheckI("&bp", &bp
, 15)
1996 CheckI("t4", t4
, 40)
1997 CheckI("&t4", &t4
, 40)
1998 CheckI("t3", t3
, 40)
1999 CheckI("&t3", &t3
, 40)
2000 CheckI("t2", t2
, 40)
2001 CheckI("&t2", &t2
, 40)
2002 CheckI("t1", t1
, 40)
2003 CheckI("&t1", &t1
, 40)
2005 methodShouldPanic
:= func(name
string, i
interface{}) {
2008 shouldPanic(func() { m
.Call([]Value
{ValueOf(1000), ValueOf(byte(99))}) })
2009 shouldPanic(func() { m
.Interface() })
2011 v
= v
.Convert(tinterType
)
2013 shouldPanic(func() { m
.Call([]Value
{ValueOf(1000), ValueOf(byte(99))}) })
2014 shouldPanic(func() { m
.Interface() })
2018 methodShouldPanic("_sv", _sv
)
2019 methodShouldPanic("&_sv", &_sv
)
2022 methodShouldPanic("&_sp", &_sp
)
2025 methodShouldPanic("_wv", _wv
)
2026 methodShouldPanic("&_wv", &_wv
)
2029 methodShouldPanic("&_wp", &_wp
)
2031 _bv
:= tbigv([2]uintptr{5, 6})
2032 methodShouldPanic("_bv", _bv
)
2033 methodShouldPanic("&_bv", &_bv
)
2035 _bp
:= tbigp([2]uintptr{7, 8})
2036 methodShouldPanic("&_bp", &_bp
)
2039 vnil
:= ValueOf(&tnil
).Elem()
2040 shouldPanic(func() { vnil
.Method(0) })
2043 func TestInterfaceSet(t
*testing
.T
) {
2052 sv
:= ValueOf(&s
).Elem()
2053 sv
.Field(0).Set(ValueOf(p
))
2054 if q
:= s
.I
.(*Point
); q
!= p
{
2055 t
.Errorf("i: have %p want %p", q
, p
)
2060 if q
:= s
.P
.(*Point
); q
!= p
{
2061 t
.Errorf("i: have %p want %p", q
, p
)
2064 i
:= pv
.Method(0).Call([]Value
{ValueOf(10)})[0].Int()
2066 t
.Errorf("Interface Method returned %d; want 250", i
)
2075 func TestAnonymousFields(t
*testing
.T
) {
2076 var field StructField
2080 if field
, ok
= type1
.FieldByName("int"); !ok
{
2081 t
.Fatal("no field 'int'")
2083 if field
.Index
[0] != 1 {
2084 t
.Error("field index should be 1; is", field
.Index
)
2138 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2160 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2179 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2193 var fieldTests
= []FTest
{
2194 {struct{}{}, "", nil, 0},
2195 {struct{}{}, "Foo", nil, 0},
2196 {S0
{A
: 'a'}, "A", []int{0}, 'a'},
2197 {S0
{}, "D", nil, 0},
2198 {S1
{S0
: S0
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2199 {S1
{B
: 'b'}, "B", []int{0}, 'b'},
2200 {S1
{}, "S0", []int{1}, 0},
2201 {S1
{S0
: S0
{C
: 'c'}}, "C", []int{1, 2}, 'c'},
2202 {S2
{A
: 'a'}, "A", []int{0}, 'a'},
2203 {S2
{}, "S1", []int{1}, 0},
2204 {S2
{S1
: &S1
{B
: 'b'}}, "B", []int{1, 0}, 'b'},
2205 {S2
{S1
: &S1
{S0
: S0
{C
: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2206 {S2
{}, "D", nil, 0},
2207 {S3
{}, "S1", nil, 0},
2208 {S3
{S2
: S2
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2209 {S3
{}, "B", nil, 0},
2210 {S3
{D
: 'd'}, "D", []int{2}, 0},
2211 {S3
{E
: 'e'}, "E", []int{3}, 'e'},
2212 {S4
{A
: 'a'}, "A", []int{1}, 'a'},
2213 {S4
{}, "B", nil, 0},
2214 {S5
{}, "X", nil, 0},
2215 {S5
{}, "Y", []int{2, 0, 1}, 0},
2216 {S10
{}, "X", nil, 0},
2217 {S10
{}, "Y", []int{2, 0, 0, 1}, 0},
2218 {S14
{}, "X", nil, 0},
2221 func TestFieldByIndex(t
*testing
.T
) {
2222 for _
, test
:= range fieldTests
{
2224 f
:= s
.FieldByIndex(test
.index
)
2226 if test
.index
!= nil {
2227 if f
.Name
!= test
.name
{
2228 t
.Errorf("%s.%s found; want %s", s
.Name(), f
.Name
, test
.name
)
2231 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2233 } else if len(test
.index
) > 0 {
2234 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2237 if test
.value
!= 0 {
2238 v
:= ValueOf(test
.s
).FieldByIndex(test
.index
)
2240 if x
, ok
:= v
.Interface().(int); ok
{
2241 if x
!= test
.value
{
2242 t
.Errorf("%s%v is %d; want %d", s
.Name(), test
.index
, x
, test
.value
)
2245 t
.Errorf("%s%v value not an int", s
.Name(), test
.index
)
2248 t
.Errorf("%s%v value not found", s
.Name(), test
.index
)
2254 func TestFieldByName(t
*testing
.T
) {
2255 for _
, test
:= range fieldTests
{
2257 f
, found
:= s
.FieldByName(test
.name
)
2259 if test
.index
!= nil {
2260 // Verify field depth and index.
2261 if len(f
.Index
) != len(test
.index
) {
2262 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
)
2264 for i
, x
:= range f
.Index
{
2265 if x
!= test
.index
[i
] {
2266 t
.Errorf("%s.%s.Index[%d] is %d; want %d", s
.Name(), test
.name
, i
, x
, test
.index
[i
])
2271 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2273 } else if len(test
.index
) > 0 {
2274 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2277 if test
.value
!= 0 {
2278 v
:= ValueOf(test
.s
).FieldByName(test
.name
)
2280 if x
, ok
:= v
.Interface().(int); ok
{
2281 if x
!= test
.value
{
2282 t
.Errorf("%s.%s is %d; want %d", s
.Name(), test
.name
, x
, test
.value
)
2285 t
.Errorf("%s.%s value not an int", s
.Name(), test
.name
)
2288 t
.Errorf("%s.%s value not found", s
.Name(), test
.name
)
2294 func TestImportPath(t
*testing
.T
) {
2299 {TypeOf(&base64
.Encoding
{}).Elem(), "encoding/base64"},
2300 {TypeOf(int(0)), ""},
2301 {TypeOf(int8(0)), ""},
2302 {TypeOf(int16(0)), ""},
2303 {TypeOf(int32(0)), ""},
2304 {TypeOf(int64(0)), ""},
2305 {TypeOf(uint(0)), ""},
2306 {TypeOf(uint8(0)), ""},
2307 {TypeOf(uint16(0)), ""},
2308 {TypeOf(uint32(0)), ""},
2309 {TypeOf(uint64(0)), ""},
2310 {TypeOf(uintptr(0)), ""},
2311 {TypeOf(float32(0)), ""},
2312 {TypeOf(float64(0)), ""},
2313 {TypeOf(complex64(0)), ""},
2314 {TypeOf(complex128(0)), ""},
2315 {TypeOf(byte(0)), ""},
2316 {TypeOf(rune(0)), ""},
2317 {TypeOf([]byte(nil)), ""},
2318 {TypeOf([]rune(nil)), ""},
2319 {TypeOf(string("")), ""},
2320 {TypeOf((*interface{})(nil)).Elem(), ""},
2321 {TypeOf((*byte)(nil)), ""},
2322 {TypeOf((*rune
)(nil)), ""},
2323 {TypeOf((*int64)(nil)), ""},
2324 {TypeOf(map[string]int{}), ""},
2325 {TypeOf((*error
)(nil)).Elem(), ""},
2327 for _
, test
:= range tests
{
2328 if path
:= test
.t
.PkgPath(); path
!= test
.path
{
2329 t
.Errorf("%v.PkgPath() = %q, want %q", test
.t
, path
, test
.path
)
2334 func TestVariadicType(t
*testing
.T
) {
2335 // Test example from Type documentation.
2336 var f
func(x
int, y
...float64)
2338 if typ
.NumIn() == 2 && typ
.In(0) == TypeOf(int(0)) {
2340 if sl
.Kind() == Slice
{
2341 if sl
.Elem() == TypeOf(0.0) {
2349 t
.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2350 s
:= fmt
.Sprintf("have NumIn() = %d", typ
.NumIn())
2351 for i
:= 0; i
< typ
.NumIn(); i
++ {
2352 s
+= fmt
.Sprintf(", In(%d) = %s", i
, typ
.In(i
))
2366 func (*inner
) m() {}
2367 func (*outer
) m() {}
2369 func TestNestedMethods(t
*testing
.T
) {
2370 t
.Skip("fails on gccgo due to function wrappers")
2371 typ
:= TypeOf((*outer
)(nil))
2372 if typ
.NumMethod() != 1 || typ
.Method(0).Func
.Pointer() != ValueOf((*outer
).m
).Pointer() {
2373 t
.Errorf("Wrong method table for outer: (m=%p)", (*outer
).m
)
2374 for i
:= 0; i
< typ
.NumMethod(); i
++ {
2376 t
.Errorf("\t%d: %s %#x\n", i
, m
.Name
, m
.Func
.Pointer())
2381 type InnerInt
struct {
2385 type OuterInt
struct {
2390 func (i
*InnerInt
) M() int {
2394 func TestEmbeddedMethods(t
*testing
.T
) {
2395 /* This part of the test fails on gccgo due to function wrappers.
2396 typ := TypeOf((*OuterInt)(nil))
2397 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2398 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2399 for i := 0; i < typ.NumMethod(); i++ {
2401 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2407 if v
:= ValueOf(i
).Method(0).Call(nil)[0].Int(); v
!= 3 {
2408 t
.Errorf("i.M() = %d, want 3", v
)
2411 o
:= &OuterInt
{1, InnerInt
{2}}
2412 if v
:= ValueOf(o
).Method(0).Call(nil)[0].Int(); v
!= 2 {
2413 t
.Errorf("i.M() = %d, want 2", v
)
2417 if v
:= f(o
); v
!= 2 {
2418 t
.Errorf("f(o) = %d, want 2", v
)
2422 func TestPtrTo(t
*testing
.T
) {
2426 for i
= 0; i
< 100; i
++ {
2429 for i
= 0; i
< 100; i
++ {
2432 if typ
!= TypeOf(i
) {
2433 t
.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ
, TypeOf(i
))
2437 func TestPtrToGC(t
*testing
.T
) {
2439 tt
:= TypeOf(T(nil))
2443 for i
:= 0; i
< n
; i
++ {
2448 v
.Elem().Set(ValueOf(p
).Convert(pt
))
2449 x
= append(x
, v
.Interface())
2453 for i
, xi
:= range x
{
2454 k
:= ValueOf(xi
).Elem().Elem().Elem().Interface().(uintptr)
2455 if k
!= uintptr(i
) {
2456 t
.Errorf("lost x[%d] = %d, want %d", i
, k
, i
)
2461 func TestAddr(t
*testing
.T
) {
2473 t
.Errorf("Addr.Elem.Set failed to set value")
2476 // Again but take address of the ValueOf value.
2477 // Exercises generation of PtrTypes not present in the binary.
2479 v
= ValueOf(&q
).Elem()
2488 t
.Errorf("Addr.Elem.Set failed to set value")
2491 // Starting without pointer we should get changed value
2494 v
= ValueOf(&qq
).Elem()
2500 if p
.X
!= 3 { // should be unchanged from last time
2501 t
.Errorf("somehow value Set changed original p")
2503 p
= v0
.Interface().(struct {
2507 t
.Errorf("Addr.Elem.Set valued to set value in top value")
2510 // Verify that taking the address of a type gives us a pointer
2511 // which we can convert back using the usual interface
2516 ps
:= ValueOf(&s
).Elem().Field(0).Addr().Interface()
2517 *(ps
.(**bool)) = new(bool)
2519 t
.Errorf("Addr.Interface direct assignment failed")
2523 /* gccgo does do allocations here.
2525 func noAlloc(t *testing.T, n int, f func(int)) {
2526 if testing.Short() {
2527 t.Skip("skipping malloc count in short mode")
2529 if runtime.GOMAXPROCS(0) > 1 {
2530 t.Skip("skipping; GOMAXPROCS>1")
2533 allocs := testing.AllocsPerRun(n, func() {
2538 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2542 func TestAllocations(t *testing.T) {
2543 noAlloc(t, 100, func(j int) {
2547 // We can uncomment this when compiler escape analysis
2548 // is good enough to see that the integer assigned to i
2549 // does not escape and therefore need not be allocated.
2553 // if int(v.Int()) != 42+j {
2554 // panic("wrong int")
2557 i = func(j int) int { return j }
2559 if v.Interface().(func(int) int)(j) != j {
2560 panic("wrong result")
2567 func TestSmallNegativeInt(t
*testing
.T
) {
2571 t
.Errorf("int16(-1).Int() returned %v", v
.Int())
2575 func TestIndex(t
*testing
.T
) {
2576 xs
:= []byte{1, 2, 3, 4, 5, 6, 7, 8}
2577 v
:= ValueOf(xs
).Index(3).Interface().(byte)
2579 t
.Errorf("xs.Index(3) = %v; expected %v", v
, xs
[3])
2581 xa
:= [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2582 v
= ValueOf(xa
).Index(2).Interface().(byte)
2584 t
.Errorf("xa.Index(2) = %v; expected %v", v
, xa
[2])
2587 v
= ValueOf(s
).Index(3).Interface().(byte)
2589 t
.Errorf("s.Index(3) = %v; expected %v", v
, s
[3])
2593 func TestSlice(t
*testing
.T
) {
2594 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2595 v
:= ValueOf(xs
).Slice(3, 5).Interface().([]int)
2597 t
.Errorf("len(xs.Slice(3, 5)) = %d", len(v
))
2600 t
.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v
))
2602 if !DeepEqual(v
[0:5], xs
[3:]) {
2603 t
.Errorf("xs.Slice(3, 5)[0:5] = %v", v
[0:5])
2605 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2606 v
= ValueOf(&xa
).Elem().Slice(2, 5).Interface().([]int)
2608 t
.Errorf("len(xa.Slice(2, 5)) = %d", len(v
))
2611 t
.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v
))
2613 if !DeepEqual(v
[0:6], xa
[2:]) {
2614 t
.Errorf("xs.Slice(2, 5)[0:6] = %v", v
[0:6])
2617 vs
:= ValueOf(s
).Slice(3, 5).Interface().(string)
2619 t
.Errorf("s.Slice(3, 5) = %q; expected %q", vs
, s
[3:5])
2622 rv
:= ValueOf(&xs
).Elem()
2624 ptr2
:= rv
.Pointer()
2626 ptr3
:= rv
.Pointer()
2628 t
.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3
, ptr2
)
2632 func TestSlice3(t
*testing
.T
) {
2633 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2634 v
:= ValueOf(xs
).Slice3(3, 5, 7).Interface().([]int)
2636 t
.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v
))
2639 t
.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v
))
2641 if !DeepEqual(v
[0:4], xs
[3:7:7]) {
2642 t
.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v
[0:4])
2644 rv
:= ValueOf(&xs
).Elem()
2645 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2646 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2647 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2649 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2650 v
= ValueOf(&xa
).Elem().Slice3(2, 5, 6).Interface().([]int)
2652 t
.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v
))
2655 t
.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v
))
2657 if !DeepEqual(v
[0:4], xa
[2:6:6]) {
2658 t
.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v
[0:4])
2660 rv
= ValueOf(&xa
).Elem()
2661 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2662 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2663 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2666 rv
= ValueOf(&s
).Elem()
2667 shouldPanic(func() { rv
.Slice3(1, 2, 3) })
2669 rv
= ValueOf(&xs
).Elem()
2670 rv
= rv
.Slice3(3, 5, 7)
2671 ptr2
:= rv
.Pointer()
2672 rv
= rv
.Slice3(4, 4, 4)
2673 ptr3
:= rv
.Pointer()
2675 t
.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3
, ptr2
)
2679 func TestSetLenCap(t
*testing
.T
) {
2680 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2681 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2683 vs
:= ValueOf(&xs
).Elem()
2684 shouldPanic(func() { vs
.SetLen(10) })
2685 shouldPanic(func() { vs
.SetCap(10) })
2686 shouldPanic(func() { vs
.SetLen(-1) })
2687 shouldPanic(func() { vs
.SetCap(-1) })
2688 shouldPanic(func() { vs
.SetCap(6) }) // smaller than len
2690 if len(xs
) != 5 ||
cap(xs
) != 8 {
2691 t
.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs
), cap(xs
))
2694 if len(xs
) != 5 ||
cap(xs
) != 6 {
2695 t
.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs
), cap(xs
))
2698 if len(xs
) != 5 ||
cap(xs
) != 5 {
2699 t
.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs
), cap(xs
))
2701 shouldPanic(func() { vs
.SetCap(4) }) // smaller than len
2702 shouldPanic(func() { vs
.SetLen(6) }) // bigger than cap
2704 va
:= ValueOf(&xa
).Elem()
2705 shouldPanic(func() { va
.SetLen(8) })
2706 shouldPanic(func() { va
.SetCap(8) })
2709 func TestVariadic(t
*testing
.T
) {
2714 V(fmt
.Fprintf
).Call([]Value
{V(&b
), V("%s, %d world"), V("hello"), V(42)})
2715 if b
.String() != "hello, 42 world" {
2716 t
.Errorf("after Fprintf Call: %q != %q", b
.String(), "hello 42 world")
2720 V(fmt
.Fprintf
).CallSlice([]Value
{V(&b
), V("%s, %d world"), V([]interface{}{"hello", 42})})
2721 if b
.String() != "hello, 42 world" {
2722 t
.Errorf("after Fprintf CallSlice: %q != %q", b
.String(), "hello 42 world")
2726 func TestFuncArg(t
*testing
.T
) {
2727 f1
:= func(i
int, f
func(int) int) int { return f(i
) }
2728 f2
:= func(i
int) int { return i
+ 1 }
2729 r
:= ValueOf(f1
).Call([]Value
{ValueOf(100), ValueOf(f2
)})
2730 if r
[0].Int() != 101 {
2731 t
.Errorf("function returned %d, want 101", r
[0].Int())
2735 func TestStructArg(t
*testing
.T
) {
2736 type padded
struct {
2743 wantA
= padded
{"3", 4}
2746 f
:= func(a padded
, b
uint32) {
2749 ValueOf(f
).Call([]Value
{ValueOf(wantA
), ValueOf(wantB
)})
2750 if gotA
!= wantA || gotB
!= wantB
{
2751 t
.Errorf("function called with (%v, %v), want (%v, %v)", gotA
, gotB
, wantA
, wantB
)
2755 var tagGetTests
= []struct {
2760 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2761 {`protobuf:"PB(1,2)"`, `foo`, ``},
2762 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2763 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2764 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2765 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
2766 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
2769 func TestTagGet(t
*testing
.T
) {
2770 for _
, tt
:= range tagGetTests
{
2771 if v
:= tt
.Tag
.Get(tt
.Key
); v
!= tt
.Value
{
2772 t
.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt
.Tag
, tt
.Key
, v
, tt
.Value
)
2777 func TestBytes(t
*testing
.T
) {
2780 y
:= ValueOf(x
).Bytes()
2781 if !bytes
.Equal(x
, y
) {
2782 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
2785 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
2789 func TestSetBytes(t
*testing
.T
) {
2792 y
:= []byte{1, 2, 3, 4}
2793 ValueOf(&x
).Elem().SetBytes(y
)
2794 if !bytes
.Equal(x
, y
) {
2795 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
2798 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
2802 type Private
struct {
2808 func (p
*Private
) m() {
2811 type private
struct {
2819 func (p
*private
) P() {
2822 type Public
struct {
2828 func (p
*Public
) M() {
2831 func TestUnexported(t
*testing
.T
) {
2836 isValid(v
.Elem().Field(0))
2837 isValid(v
.Elem().Field(1))
2838 isValid(v
.Elem().Field(2))
2839 isValid(v
.Elem().FieldByName("X"))
2840 isValid(v
.Elem().FieldByName("Y"))
2841 isValid(v
.Elem().FieldByName("Z"))
2842 isValid(v
.Type().Method(0).Func
)
2843 m
, _
:= v
.Type().MethodByName("M")
2845 m
, _
= v
.Type().MethodByName("P")
2847 isNonNil(v
.Elem().Field(0).Interface())
2848 isNonNil(v
.Elem().Field(1).Interface())
2849 isNonNil(v
.Elem().Field(2).Field(2).Index(0))
2850 isNonNil(v
.Elem().FieldByName("X").Interface())
2851 isNonNil(v
.Elem().FieldByName("Y").Interface())
2852 isNonNil(v
.Elem().FieldByName("Z").Interface())
2853 isNonNil(v
.Elem().FieldByName("S").Index(0).Interface())
2854 isNonNil(v
.Type().Method(0).Func
.Interface())
2855 m
, _
= v
.Type().MethodByName("P")
2856 isNonNil(m
.Func
.Interface())
2860 isValid(v
.Elem().Field(0))
2861 isValid(v
.Elem().Field(1))
2862 isValid(v
.Elem().FieldByName("x"))
2863 isValid(v
.Elem().FieldByName("y"))
2864 isValid(v
.Type().Method(0).Func
)
2865 shouldPanic(func() { v
.Elem().Field(0).Interface() })
2866 shouldPanic(func() { v
.Elem().Field(1).Interface() })
2867 shouldPanic(func() { v
.Elem().FieldByName("x").Interface() })
2868 shouldPanic(func() { v
.Elem().FieldByName("y").Interface() })
2869 shouldPanic(func() { v
.Type().Method(0).Func
.Interface() })
2872 func TestSetPanic(t
*testing
.T
) {
2873 ok
:= func(f
func()) { f() }
2875 clear
:= func(v Value
) { v
.Set(Zero(v
.Type())) }
2903 bad(func() { clear(v
.Field(0)) }) // .X
2904 bad(func() { clear(v
.Field(1)) }) // .t1
2905 bad(func() { clear(v
.Field(1).Field(0)) }) // .t1.Y
2906 bad(func() { clear(v
.Field(1).Field(1)) }) // .t1.t0
2907 bad(func() { clear(v
.Field(1).Field(1).Field(0)) }) // .t1.t0.W
2908 bad(func() { clear(v
.Field(2)) }) // .T2
2909 bad(func() { clear(v
.Field(2).Field(0)) }) // .T2.Z
2910 bad(func() { clear(v
.Field(2).Field(1)) }) // .T2.namedT0
2911 bad(func() { clear(v
.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
2912 bad(func() { clear(v
.Field(3)) }) // .NamedT1
2913 bad(func() { clear(v
.Field(3).Field(0)) }) // .NamedT1.Y
2914 bad(func() { clear(v
.Field(3).Field(1)) }) // .NamedT1.t0
2915 bad(func() { clear(v
.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
2916 bad(func() { clear(v
.Field(4)) }) // .NamedT2
2917 bad(func() { clear(v
.Field(4).Field(0)) }) // .NamedT2.Z
2918 bad(func() { clear(v
.Field(4).Field(1)) }) // .NamedT2.namedT0
2919 bad(func() { clear(v
.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
2920 bad(func() { clear(v
.Field(5)) }) // .namedT1
2921 bad(func() { clear(v
.Field(5).Field(0)) }) // .namedT1.Y
2922 bad(func() { clear(v
.Field(5).Field(1)) }) // .namedT1.t0
2923 bad(func() { clear(v
.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
2924 bad(func() { clear(v
.Field(6)) }) // .namedT2
2925 bad(func() { clear(v
.Field(6).Field(0)) }) // .namedT2.Z
2926 bad(func() { clear(v
.Field(6).Field(1)) }) // .namedT2.namedT0
2927 bad(func() { clear(v
.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
2930 v
= ValueOf(&T
{}).Elem()
2931 ok(func() { clear(v
.Field(0)) }) // .X
2932 bad(func() { clear(v
.Field(1)) }) // .t1
2933 ok(func() { clear(v
.Field(1).Field(0)) }) // .t1.Y
2934 bad(func() { clear(v
.Field(1).Field(1)) }) // .t1.t0
2935 ok(func() { clear(v
.Field(1).Field(1).Field(0)) }) // .t1.t0.W
2936 ok(func() { clear(v
.Field(2)) }) // .T2
2937 ok(func() { clear(v
.Field(2).Field(0)) }) // .T2.Z
2938 bad(func() { clear(v
.Field(2).Field(1)) }) // .T2.namedT0
2939 bad(func() { clear(v
.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
2940 ok(func() { clear(v
.Field(3)) }) // .NamedT1
2941 ok(func() { clear(v
.Field(3).Field(0)) }) // .NamedT1.Y
2942 bad(func() { clear(v
.Field(3).Field(1)) }) // .NamedT1.t0
2943 ok(func() { clear(v
.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
2944 ok(func() { clear(v
.Field(4)) }) // .NamedT2
2945 ok(func() { clear(v
.Field(4).Field(0)) }) // .NamedT2.Z
2946 bad(func() { clear(v
.Field(4).Field(1)) }) // .NamedT2.namedT0
2947 bad(func() { clear(v
.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
2948 bad(func() { clear(v
.Field(5)) }) // .namedT1
2949 bad(func() { clear(v
.Field(5).Field(0)) }) // .namedT1.Y
2950 bad(func() { clear(v
.Field(5).Field(1)) }) // .namedT1.t0
2951 bad(func() { clear(v
.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
2952 bad(func() { clear(v
.Field(6)) }) // .namedT2
2953 bad(func() { clear(v
.Field(6).Field(0)) }) // .namedT2.Z
2954 bad(func() { clear(v
.Field(6).Field(1)) }) // .namedT2.namedT0
2955 bad(func() { clear(v
.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
2960 func (t timp
) W() {}
2961 func (t timp
) Y() {}
2962 func (t timp
) w() {}
2963 func (t timp
) y() {}
2965 func TestCallPanic(t
*testing
.T
) {
2990 ok
:= func(f
func()) { f() }
2992 call
:= func(v Value
) { v
.Call(nil) }
2995 v
:= ValueOf(T
{i
, i
, i
, i
, T2
{i
, i
}, i
, i
, T2
{i
, i
}})
2996 ok(func() { call(v
.Field(0).Method(0)) }) // .t0.W
2997 ok(func() { call(v
.Field(0).Elem().Method(0)) }) // .t0.W
2998 bad(func() { call(v
.Field(0).Method(1)) }) // .t0.w
2999 bad(func() { call(v
.Field(0).Elem().Method(2)) }) // .t0.w
3000 ok(func() { call(v
.Field(1).Method(0)) }) // .T1.Y
3001 ok(func() { call(v
.Field(1).Elem().Method(0)) }) // .T1.Y
3002 bad(func() { call(v
.Field(1).Method(1)) }) // .T1.y
3003 bad(func() { call(v
.Field(1).Elem().Method(2)) }) // .T1.y
3005 ok(func() { call(v
.Field(2).Method(0)) }) // .NamedT0.W
3006 ok(func() { call(v
.Field(2).Elem().Method(0)) }) // .NamedT0.W
3007 bad(func() { call(v
.Field(2).Method(1)) }) // .NamedT0.w
3008 bad(func() { call(v
.Field(2).Elem().Method(2)) }) // .NamedT0.w
3010 ok(func() { call(v
.Field(3).Method(0)) }) // .NamedT1.Y
3011 ok(func() { call(v
.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3012 bad(func() { call(v
.Field(3).Method(1)) }) // .NamedT1.y
3013 bad(func() { call(v
.Field(3).Elem().Method(3)) }) // .NamedT1.y
3015 ok(func() { call(v
.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3016 ok(func() { call(v
.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3017 ok(func() { call(v
.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3018 ok(func() { call(v
.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3020 bad(func() { call(v
.Field(5).Method(0)) }) // .namedT0.W
3021 bad(func() { call(v
.Field(5).Elem().Method(0)) }) // .namedT0.W
3022 bad(func() { call(v
.Field(5).Method(1)) }) // .namedT0.w
3023 bad(func() { call(v
.Field(5).Elem().Method(2)) }) // .namedT0.w
3025 bad(func() { call(v
.Field(6).Method(0)) }) // .namedT1.Y
3026 bad(func() { call(v
.Field(6).Elem().Method(0)) }) // .namedT1.Y
3027 bad(func() { call(v
.Field(6).Method(0)) }) // .namedT1.y
3028 bad(func() { call(v
.Field(6).Elem().Method(0)) }) // .namedT1.y
3030 bad(func() { call(v
.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3031 bad(func() { call(v
.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3032 bad(func() { call(v
.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3033 bad(func() { call(v
.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3036 func shouldPanic(f
func()) {
3038 if recover() == nil {
3039 panic("did not panic")
3045 func isNonNil(x
interface{}) {
3047 panic("nil interface")
3051 func isValid(v Value
) {
3057 func TestAlias(t
*testing
.T
) {
3058 x
:= string("hello")
3059 v
:= ValueOf(&x
).Elem()
3060 oldvalue
:= v
.Interface()
3061 v
.SetString("world")
3062 newvalue
:= v
.Interface()
3064 if oldvalue
!= "hello" || newvalue
!= "world" {
3065 t
.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue
, newvalue
)
3071 func EmptyInterfaceV(x
interface{}) Value
{
3072 return ValueOf(&x
).Elem()
3075 func ReaderV(x io
.Reader
) Value
{
3076 return ValueOf(&x
).Elem()
3079 func ReadWriterV(x io
.ReadWriter
) Value
{
3080 return ValueOf(&x
).Elem()
3084 type MyString
string
3086 type MyRunes
[]int32
3090 var convertTests
= []struct {
3096 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3102 var numbers = []string{
3103 "int8", "uint8", "int16", "uint16",
3104 "int32", "uint32", "int64", "uint64",
3105 "int", "uint", "uintptr",
3106 "float32", "float64",
3110 // all pairs but in an unusual order,
3111 // to emit all the int8, uint8 cases
3112 // before n grows too big.
3114 for i, f := range numbers {
3115 for _, g := range numbers[i:] {
3116 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3119 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3126 {V(int8(1)), V(int8(1))},
3127 {V(int8(2)), V(uint8(2))},
3128 {V(uint8(3)), V(int8(3))},
3129 {V(int8(4)), V(int16(4))},
3130 {V(int16(5)), V(int8(5))},
3131 {V(int8(6)), V(uint16(6))},
3132 {V(uint16(7)), V(int8(7))},
3133 {V(int8(8)), V(int32(8))},
3134 {V(int32(9)), V(int8(9))},
3135 {V(int8(10)), V(uint32(10))},
3136 {V(uint32(11)), V(int8(11))},
3137 {V(int8(12)), V(int64(12))},
3138 {V(int64(13)), V(int8(13))},
3139 {V(int8(14)), V(uint64(14))},
3140 {V(uint64(15)), V(int8(15))},
3141 {V(int8(16)), V(int(16))},
3142 {V(int(17)), V(int8(17))},
3143 {V(int8(18)), V(uint(18))},
3144 {V(uint(19)), V(int8(19))},
3145 {V(int8(20)), V(uintptr(20))},
3146 {V(uintptr(21)), V(int8(21))},
3147 {V(int8(22)), V(float32(22))},
3148 {V(float32(23)), V(int8(23))},
3149 {V(int8(24)), V(float64(24))},
3150 {V(float64(25)), V(int8(25))},
3151 {V(uint8(26)), V(uint8(26))},
3152 {V(uint8(27)), V(int16(27))},
3153 {V(int16(28)), V(uint8(28))},
3154 {V(uint8(29)), V(uint16(29))},
3155 {V(uint16(30)), V(uint8(30))},
3156 {V(uint8(31)), V(int32(31))},
3157 {V(int32(32)), V(uint8(32))},
3158 {V(uint8(33)), V(uint32(33))},
3159 {V(uint32(34)), V(uint8(34))},
3160 {V(uint8(35)), V(int64(35))},
3161 {V(int64(36)), V(uint8(36))},
3162 {V(uint8(37)), V(uint64(37))},
3163 {V(uint64(38)), V(uint8(38))},
3164 {V(uint8(39)), V(int(39))},
3165 {V(int(40)), V(uint8(40))},
3166 {V(uint8(41)), V(uint(41))},
3167 {V(uint(42)), V(uint8(42))},
3168 {V(uint8(43)), V(uintptr(43))},
3169 {V(uintptr(44)), V(uint8(44))},
3170 {V(uint8(45)), V(float32(45))},
3171 {V(float32(46)), V(uint8(46))},
3172 {V(uint8(47)), V(float64(47))},
3173 {V(float64(48)), V(uint8(48))},
3174 {V(int16(49)), V(int16(49))},
3175 {V(int16(50)), V(uint16(50))},
3176 {V(uint16(51)), V(int16(51))},
3177 {V(int16(52)), V(int32(52))},
3178 {V(int32(53)), V(int16(53))},
3179 {V(int16(54)), V(uint32(54))},
3180 {V(uint32(55)), V(int16(55))},
3181 {V(int16(56)), V(int64(56))},
3182 {V(int64(57)), V(int16(57))},
3183 {V(int16(58)), V(uint64(58))},
3184 {V(uint64(59)), V(int16(59))},
3185 {V(int16(60)), V(int(60))},
3186 {V(int(61)), V(int16(61))},
3187 {V(int16(62)), V(uint(62))},
3188 {V(uint(63)), V(int16(63))},
3189 {V(int16(64)), V(uintptr(64))},
3190 {V(uintptr(65)), V(int16(65))},
3191 {V(int16(66)), V(float32(66))},
3192 {V(float32(67)), V(int16(67))},
3193 {V(int16(68)), V(float64(68))},
3194 {V(float64(69)), V(int16(69))},
3195 {V(uint16(70)), V(uint16(70))},
3196 {V(uint16(71)), V(int32(71))},
3197 {V(int32(72)), V(uint16(72))},
3198 {V(uint16(73)), V(uint32(73))},
3199 {V(uint32(74)), V(uint16(74))},
3200 {V(uint16(75)), V(int64(75))},
3201 {V(int64(76)), V(uint16(76))},
3202 {V(uint16(77)), V(uint64(77))},
3203 {V(uint64(78)), V(uint16(78))},
3204 {V(uint16(79)), V(int(79))},
3205 {V(int(80)), V(uint16(80))},
3206 {V(uint16(81)), V(uint(81))},
3207 {V(uint(82)), V(uint16(82))},
3208 {V(uint16(83)), V(uintptr(83))},
3209 {V(uintptr(84)), V(uint16(84))},
3210 {V(uint16(85)), V(float32(85))},
3211 {V(float32(86)), V(uint16(86))},
3212 {V(uint16(87)), V(float64(87))},
3213 {V(float64(88)), V(uint16(88))},
3214 {V(int32(89)), V(int32(89))},
3215 {V(int32(90)), V(uint32(90))},
3216 {V(uint32(91)), V(int32(91))},
3217 {V(int32(92)), V(int64(92))},
3218 {V(int64(93)), V(int32(93))},
3219 {V(int32(94)), V(uint64(94))},
3220 {V(uint64(95)), V(int32(95))},
3221 {V(int32(96)), V(int(96))},
3222 {V(int(97)), V(int32(97))},
3223 {V(int32(98)), V(uint(98))},
3224 {V(uint(99)), V(int32(99))},
3225 {V(int32(100)), V(uintptr(100))},
3226 {V(uintptr(101)), V(int32(101))},
3227 {V(int32(102)), V(float32(102))},
3228 {V(float32(103)), V(int32(103))},
3229 {V(int32(104)), V(float64(104))},
3230 {V(float64(105)), V(int32(105))},
3231 {V(uint32(106)), V(uint32(106))},
3232 {V(uint32(107)), V(int64(107))},
3233 {V(int64(108)), V(uint32(108))},
3234 {V(uint32(109)), V(uint64(109))},
3235 {V(uint64(110)), V(uint32(110))},
3236 {V(uint32(111)), V(int(111))},
3237 {V(int(112)), V(uint32(112))},
3238 {V(uint32(113)), V(uint(113))},
3239 {V(uint(114)), V(uint32(114))},
3240 {V(uint32(115)), V(uintptr(115))},
3241 {V(uintptr(116)), V(uint32(116))},
3242 {V(uint32(117)), V(float32(117))},
3243 {V(float32(118)), V(uint32(118))},
3244 {V(uint32(119)), V(float64(119))},
3245 {V(float64(120)), V(uint32(120))},
3246 {V(int64(121)), V(int64(121))},
3247 {V(int64(122)), V(uint64(122))},
3248 {V(uint64(123)), V(int64(123))},
3249 {V(int64(124)), V(int(124))},
3250 {V(int(125)), V(int64(125))},
3251 {V(int64(126)), V(uint(126))},
3252 {V(uint(127)), V(int64(127))},
3253 {V(int64(128)), V(uintptr(128))},
3254 {V(uintptr(129)), V(int64(129))},
3255 {V(int64(130)), V(float32(130))},
3256 {V(float32(131)), V(int64(131))},
3257 {V(int64(132)), V(float64(132))},
3258 {V(float64(133)), V(int64(133))},
3259 {V(uint64(134)), V(uint64(134))},
3260 {V(uint64(135)), V(int(135))},
3261 {V(int(136)), V(uint64(136))},
3262 {V(uint64(137)), V(uint(137))},
3263 {V(uint(138)), V(uint64(138))},
3264 {V(uint64(139)), V(uintptr(139))},
3265 {V(uintptr(140)), V(uint64(140))},
3266 {V(uint64(141)), V(float32(141))},
3267 {V(float32(142)), V(uint64(142))},
3268 {V(uint64(143)), V(float64(143))},
3269 {V(float64(144)), V(uint64(144))},
3270 {V(int(145)), V(int(145))},
3271 {V(int(146)), V(uint(146))},
3272 {V(uint(147)), V(int(147))},
3273 {V(int(148)), V(uintptr(148))},
3274 {V(uintptr(149)), V(int(149))},
3275 {V(int(150)), V(float32(150))},
3276 {V(float32(151)), V(int(151))},
3277 {V(int(152)), V(float64(152))},
3278 {V(float64(153)), V(int(153))},
3279 {V(uint(154)), V(uint(154))},
3280 {V(uint(155)), V(uintptr(155))},
3281 {V(uintptr(156)), V(uint(156))},
3282 {V(uint(157)), V(float32(157))},
3283 {V(float32(158)), V(uint(158))},
3284 {V(uint(159)), V(float64(159))},
3285 {V(float64(160)), V(uint(160))},
3286 {V(uintptr(161)), V(uintptr(161))},
3287 {V(uintptr(162)), V(float32(162))},
3288 {V(float32(163)), V(uintptr(163))},
3289 {V(uintptr(164)), V(float64(164))},
3290 {V(float64(165)), V(uintptr(165))},
3291 {V(float32(166)), V(float32(166))},
3292 {V(float32(167)), V(float64(167))},
3293 {V(float64(168)), V(float32(168))},
3294 {V(float64(169)), V(float64(169))},
3297 {V(float64(1.5)), V(int(1))},
3300 {V(complex64(1i
)), V(complex64(1i
))},
3301 {V(complex64(2i
)), V(complex128(2i
))},
3302 {V(complex128(3i
)), V(complex64(3i
))},
3303 {V(complex128(4i
)), V(complex128(4i
))},
3306 {V(string("hello")), V(string("hello"))},
3307 {V(string("bytes1")), V([]byte("bytes1"))},
3308 {V([]byte("bytes2")), V(string("bytes2"))},
3309 {V([]byte("bytes3")), V([]byte("bytes3"))},
3310 {V(string("runes♝")), V([]rune("runes♝"))},
3311 {V([]rune("runes♕")), V(string("runes♕"))},
3312 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3313 {V(int('a')), V(string("a"))},
3314 {V(int8('a')), V(string("a"))},
3315 {V(int16('a')), V(string("a"))},
3316 {V(int32('a')), V(string("a"))},
3317 {V(int64('a')), V(string("a"))},
3318 {V(uint('a')), V(string("a"))},
3319 {V(uint8('a')), V(string("a"))},
3320 {V(uint16('a')), V(string("a"))},
3321 {V(uint32('a')), V(string("a"))},
3322 {V(uint64('a')), V(string("a"))},
3323 {V(uintptr('a')), V(string("a"))},
3324 {V(int(-1)), V(string("\uFFFD"))},
3325 {V(int8(-2)), V(string("\uFFFD"))},
3326 {V(int16(-3)), V(string("\uFFFD"))},
3327 {V(int32(-4)), V(string("\uFFFD"))},
3328 {V(int64(-5)), V(string("\uFFFD"))},
3329 {V(uint(0x110001)), V(string("\uFFFD"))},
3330 {V(uint32(0x110002)), V(string("\uFFFD"))},
3331 {V(uint64(0x110003)), V(string("\uFFFD"))},
3332 {V(uintptr(0x110004)), V(string("\uFFFD"))},
3335 {V(MyString("hello")), V(string("hello"))},
3336 {V(string("hello")), V(MyString("hello"))},
3337 {V(string("hello")), V(string("hello"))},
3338 {V(MyString("hello")), V(MyString("hello"))},
3339 {V(MyString("bytes1")), V([]byte("bytes1"))},
3340 {V([]byte("bytes2")), V(MyString("bytes2"))},
3341 {V([]byte("bytes3")), V([]byte("bytes3"))},
3342 {V(MyString("runes♝")), V([]rune("runes♝"))},
3343 {V([]rune("runes♕")), V(MyString("runes♕"))},
3344 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3345 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3346 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3347 {V(int('a')), V(MyString("a"))},
3348 {V(int8('a')), V(MyString("a"))},
3349 {V(int16('a')), V(MyString("a"))},
3350 {V(int32('a')), V(MyString("a"))},
3351 {V(int64('a')), V(MyString("a"))},
3352 {V(uint('a')), V(MyString("a"))},
3353 {V(uint8('a')), V(MyString("a"))},
3354 {V(uint16('a')), V(MyString("a"))},
3355 {V(uint32('a')), V(MyString("a"))},
3356 {V(uint64('a')), V(MyString("a"))},
3357 {V(uintptr('a')), V(MyString("a"))},
3358 {V(int(-1)), V(MyString("\uFFFD"))},
3359 {V(int8(-2)), V(MyString("\uFFFD"))},
3360 {V(int16(-3)), V(MyString("\uFFFD"))},
3361 {V(int32(-4)), V(MyString("\uFFFD"))},
3362 {V(int64(-5)), V(MyString("\uFFFD"))},
3363 {V(uint(0x110001)), V(MyString("\uFFFD"))},
3364 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
3365 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3366 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3369 {V(string("bytes1")), V(MyBytes("bytes1"))},
3370 {V(MyBytes("bytes2")), V(string("bytes2"))},
3371 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3372 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3373 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3376 {V(string("runes♝")), V(MyRunes("runes♝"))},
3377 {V(MyRunes("runes♕")), V(string("runes♕"))},
3378 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3379 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3380 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3382 // named types and equal underlying types
3383 {V(new(int)), V(new(integer
))},
3384 {V(new(integer
)), V(new(int))},
3385 {V(Empty
{}), V(struct{}{})},
3386 {V(new(Empty
)), V(new(struct{}))},
3387 {V(struct{}{}), V(Empty
{})},
3388 {V(new(struct{})), V(new(Empty
))},
3389 {V(Empty
{}), V(Empty
{})},
3390 {V(MyBytes
{}), V([]byte{})},
3391 {V([]byte{}), V(MyBytes
{})},
3392 {V((func())(nil)), V(MyFunc(nil))},
3393 {V((MyFunc
)(nil)), V((func())(nil))},
3395 // can convert *byte and *MyByte
3396 {V((*byte)(nil)), V((*MyByte
)(nil))},
3397 {V((*MyByte
)(nil)), V((*byte)(nil))},
3399 // cannot convert mismatched array sizes
3400 {V([2]byte{}), V([2]byte{})},
3401 {V([3]byte{}), V([3]byte{})},
3403 // cannot convert other instances
3404 {V((**byte)(nil)), V((**byte)(nil))},
3405 {V((**MyByte
)(nil)), V((**MyByte
)(nil))},
3406 {V((chan byte)(nil)), V((chan byte)(nil))},
3407 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
3408 {V(([]byte)(nil)), V(([]byte)(nil))},
3409 {V(([]MyByte
)(nil)), V(([]MyByte
)(nil))},
3410 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3411 {V((map[int]MyByte
)(nil)), V((map[int]MyByte
)(nil))},
3412 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3413 {V((map[MyByte
]int)(nil)), V((map[MyByte
]int)(nil))},
3414 {V([2]byte{}), V([2]byte{})},
3415 {V([2]MyByte
{}), V([2]MyByte
{})},
3418 {V((***int)(nil)), V((***int)(nil))},
3419 {V((***byte)(nil)), V((***byte)(nil))},
3420 {V((***int32)(nil)), V((***int32)(nil))},
3421 {V((***int64)(nil)), V((***int64)(nil))},
3422 {V((chan int)(nil)), V((<-chan int)(nil))},
3423 {V((chan int)(nil)), V((chan<- int)(nil))},
3424 {V((chan string)(nil)), V((<-chan string)(nil))},
3425 {V((chan string)(nil)), V((chan<- string)(nil))},
3426 {V((chan byte)(nil)), V((chan byte)(nil))},
3427 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
3428 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3429 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3430 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3431 {V([]uint(nil)), V([]uint(nil))},
3432 {V([]int(nil)), V([]int(nil))},
3433 {V(new(interface{})), V(new(interface{}))},
3434 {V(new(io
.Reader
)), V(new(io
.Reader
))},
3435 {V(new(io
.Writer
)), V(new(io
.Writer
))},
3438 {V(int(1)), EmptyInterfaceV(int(1))},
3439 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3440 {V(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3441 {ReadWriterV(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3442 {V(new(bytes
.Buffer
)), ReadWriterV(new(bytes
.Buffer
))},
3445 func TestConvert(t
*testing
.T
) {
3446 canConvert
:= map[[2]Type
]bool{}
3447 all
:= map[Type
]bool{}
3449 for _
, tt
:= range convertTests
{
3451 if !t1
.ConvertibleTo(t1
) {
3452 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t1
)
3457 if !t1
.ConvertibleTo(t2
) {
3458 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t2
)
3464 canConvert
[[2]Type
{t1
, t2
}] = true
3466 // vout1 represents the in value converted to the in type.
3468 vout1
:= v1
.Convert(t1
)
3469 out1
:= vout1
.Interface()
3470 if vout1
.Type() != tt
.in
.Type() ||
!DeepEqual(out1
, tt
.in
.Interface()) {
3471 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t1
, out1
, tt
.in
.Interface())
3474 // vout2 represents the in value converted to the out type.
3475 vout2
:= v1
.Convert(t2
)
3476 out2
:= vout2
.Interface()
3477 if vout2
.Type() != tt
.out
.Type() ||
!DeepEqual(out2
, tt
.out
.Interface()) {
3478 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out2
, tt
.out
.Interface())
3481 // vout3 represents a new value of the out type, set to vout2. This makes
3482 // sure the converted value vout2 is really usable as a regular value.
3483 vout3
:= New(t2
).Elem()
3485 out3
:= vout3
.Interface()
3486 if vout3
.Type() != tt
.out
.Type() ||
!DeepEqual(out3
, tt
.out
.Interface()) {
3487 t
.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out3
, tt
.out
.Interface())
3491 t
.Errorf("table entry %v is RO, should not be", v1
)
3494 t
.Errorf("self-conversion output %v is RO, should not be", vout1
)
3497 t
.Errorf("conversion output %v is RO, should not be", vout2
)
3500 t
.Errorf("set(conversion output) %v is RO, should not be", vout3
)
3502 if !IsRO(MakeRO(v1
).Convert(t1
)) {
3503 t
.Errorf("RO self-conversion output %v is not RO, should be", v1
)
3505 if !IsRO(MakeRO(v1
).Convert(t2
)) {
3506 t
.Errorf("RO conversion output %v is not RO, should be", v1
)
3510 // Assume that of all the types we saw during the tests,
3511 // if there wasn't an explicit entry for a conversion between
3512 // a pair of types, then it's not to be allowed. This checks for
3513 // things like 'int64' converting to '*int'.
3514 for t1
:= range all
{
3515 for t2
:= range all
{
3516 expectOK
:= t1
== t2 || canConvert
[[2]Type
{t1
, t2
}] || t2
.Kind() == Interface
&& t2
.NumMethod() == 0
3517 if ok
:= t1
.ConvertibleTo(t2
); ok
!= expectOK
{
3518 t
.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1
, t2
, ok
, expectOK
)
3524 type ComparableStruct
struct {
3528 type NonComparableStruct
struct {
3533 var comparableTests
= []struct {
3538 {TypeOf("hello"), true},
3539 {TypeOf(new(byte)), true},
3540 {TypeOf((func())(nil)), false},
3541 {TypeOf([]byte{}), false},
3542 {TypeOf(map[string]int{}), false},
3543 {TypeOf(make(chan int)), true},
3544 {TypeOf(1.5), true},
3545 {TypeOf(false), true},
3547 {TypeOf(ComparableStruct
{}), true},
3548 {TypeOf(NonComparableStruct
{}), false},
3549 {TypeOf([10]map[string]int{}), false},
3550 {TypeOf([10]string{}), true},
3551 {TypeOf(new(interface{})).Elem(), true},
3554 func TestComparable(t
*testing
.T
) {
3555 for _
, tt
:= range comparableTests
{
3556 if ok
:= tt
.typ
.Comparable(); ok
!= tt
.ok
{
3557 t
.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt
.typ
, ok
, tt
.ok
)
3562 func TestOverflow(t
*testing
.T
) {
3563 if ovf
:= V(float64(0)).OverflowFloat(1e300
); ovf
{
3564 t
.Errorf("%v wrongly overflows float64", 1e300
)
3567 maxFloat32
:= float64((1<<24 - 1) << (127 - 23))
3568 if ovf
:= V(float32(0)).OverflowFloat(maxFloat32
); ovf
{
3569 t
.Errorf("%v wrongly overflows float32", maxFloat32
)
3571 ovfFloat32
:= float64((1<<24-1)<<(127-23) + 1<<(127-52))
3572 if ovf
:= V(float32(0)).OverflowFloat(ovfFloat32
); !ovf
{
3573 t
.Errorf("%v should overflow float32", ovfFloat32
)
3575 if ovf
:= V(float32(0)).OverflowFloat(-ovfFloat32
); !ovf
{
3576 t
.Errorf("%v should overflow float32", -ovfFloat32
)
3579 maxInt32
:= int64(0x7fffffff)
3580 if ovf
:= V(int32(0)).OverflowInt(maxInt32
); ovf
{
3581 t
.Errorf("%v wrongly overflows int32", maxInt32
)
3583 if ovf
:= V(int32(0)).OverflowInt(-1 << 31); ovf
{
3584 t
.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3586 ovfInt32
:= int64(1 << 31)
3587 if ovf
:= V(int32(0)).OverflowInt(ovfInt32
); !ovf
{
3588 t
.Errorf("%v should overflow int32", ovfInt32
)
3591 maxUint32
:= uint64(0xffffffff)
3592 if ovf
:= V(uint32(0)).OverflowUint(maxUint32
); ovf
{
3593 t
.Errorf("%v wrongly overflows uint32", maxUint32
)
3595 ovfUint32
:= uint64(1 << 32)
3596 if ovf
:= V(uint32(0)).OverflowUint(ovfUint32
); !ovf
{
3597 t
.Errorf("%v should overflow uint32", ovfUint32
)
3601 func checkSameType(t
*testing
.T
, x
, y
interface{}) {
3602 if TypeOf(x
) != TypeOf(y
) {
3603 t
.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x
), TypeOf(y
))
3607 func TestArrayOf(t
*testing
.T
) {
3608 // check construction and use of type not in binary
3609 for _
, table
:= range []struct {
3611 value
func(i
int) interface{}
3617 value
: func(i
int) interface{} { type Tint
int; return Tint(i
) },
3623 value
: func(i
int) interface{} { type Tint
int; return Tint(i
) },
3625 want
: "[0 1 2 3 4 5 6 7 8 9]",
3629 value
: func(i
int) interface{} { type Tfloat
float64; return Tfloat(i
) },
3631 want
: "[0 1 2 3 4 5 6 7 8 9]",
3635 value
: func(i
int) interface{} { type Tstring
string; return Tstring(strconv
.Itoa(i
)) },
3637 want
: "[0 1 2 3 4 5 6 7 8 9]",
3641 value
: func(i
int) interface{} { type Tstruct
struct{ V
int }; return Tstruct
{i
} },
3643 want
: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
3647 value
: func(i
int) interface{} { type Tint
int; return []Tint
{Tint(i
)} },
3649 want
: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3653 value
: func(i
int) interface{} { type Tint
int; return [1]Tint
{Tint(i
)} },
3655 want
: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3659 value
: func(i
int) interface{} { type Tstruct
struct{ V
[1]int }; return Tstruct
{[1]int{i
}} },
3661 want
: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3665 value
: func(i
int) interface{} { type Tstruct
struct{ V
[]int }; return Tstruct
{[]int{i
}} },
3667 want
: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3671 value
: func(i
int) interface{} { type TstructUV
struct{ U
, V
int }; return TstructUV
{i
, i
} },
3673 want
: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
3677 value
: func(i
int) interface{} {
3678 type TstructUV
struct {
3682 return TstructUV
{i
, float64(i
)}
3685 want
: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
3688 at
:= ArrayOf(table
.n
, TypeOf(table
.value(0)))
3690 vok
:= New(at
).Elem()
3691 vnot
:= New(at
).Elem()
3692 for i
:= 0; i
< v
.Len(); i
++ {
3693 v
.Index(i
).Set(ValueOf(table
.value(i
)))
3694 vok
.Index(i
).Set(ValueOf(table
.value(i
)))
3699 vnot
.Index(i
).Set(ValueOf(table
.value(j
))) // make it differ only by last element
3701 s
:= fmt
.Sprint(v
.Interface())
3702 if s
!= table
.want
{
3703 t
.Errorf("constructed array = %s, want %s", s
, table
.want
)
3706 if table
.comparable
!= at
.Comparable() {
3707 t
.Errorf("constructed array (%#v) is comparable=%v, want=%v", v
.Interface(), at
.Comparable(), table
.comparable
)
3709 if table
.comparable
{
3711 if DeepEqual(vnot
.Interface(), v
.Interface()) {
3713 "arrays (%#v) compare ok (but should not)",
3718 if !DeepEqual(vok
.Interface(), v
.Interface()) {
3720 "arrays (%#v) compare NOT-ok (but should)",
3727 // check that type already in binary is found
3729 checkSameType(t
, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T
{})
3732 func TestArrayOfGC(t
*testing
.T
) {
3734 tt
:= TypeOf(T(nil))
3737 for i
:= 0; i
< n
; i
++ {
3738 v
:= New(ArrayOf(n
, tt
)).Elem()
3739 for j
:= 0; j
< v
.Len(); j
++ {
3741 *p
= uintptr(i
*n
+ j
)
3742 v
.Index(j
).Set(ValueOf(p
).Convert(tt
))
3744 x
= append(x
, v
.Interface())
3748 for i
, xi
:= range x
{
3750 for j
:= 0; j
< v
.Len(); j
++ {
3751 k
:= v
.Index(j
).Elem().Interface()
3752 if k
!= uintptr(i
*n
+j
) {
3753 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3759 func TestArrayOfAlg(t
*testing
.T
) {
3760 at
:= ArrayOf(6, TypeOf(byte(0)))
3761 v1
:= New(at
).Elem()
3762 v2
:= New(at
).Elem()
3763 if v1
.Interface() != v1
.Interface() {
3764 t
.Errorf("constructed array %v not equal to itself", v1
.Interface())
3766 v1
.Index(5).Set(ValueOf(byte(1)))
3767 if i1
, i2
:= v1
.Interface(), v2
.Interface(); i1
== i2
{
3768 t
.Errorf("constructed arrays %v and %v should not be equal", i1
, i2
)
3771 at
= ArrayOf(6, TypeOf([]int(nil)))
3773 shouldPanic(func() { _
= v1
.Interface() == v1
.Interface() })
3776 func TestArrayOfGenericAlg(t
*testing
.T
) {
3777 at1
:= ArrayOf(5, TypeOf(string("")))
3778 at
:= ArrayOf(6, at1
)
3779 v1
:= New(at
).Elem()
3780 v2
:= New(at
).Elem()
3781 if v1
.Interface() != v1
.Interface() {
3782 t
.Errorf("constructed array %v not equal to itself", v1
.Interface())
3785 v1
.Index(0).Index(0).Set(ValueOf("abc"))
3786 v2
.Index(0).Index(0).Set(ValueOf("efg"))
3787 if i1
, i2
:= v1
.Interface(), v2
.Interface(); i1
== i2
{
3788 t
.Errorf("constructed arrays %v and %v should not be equal", i1
, i2
)
3791 v1
.Index(0).Index(0).Set(ValueOf("abc"))
3792 v2
.Index(0).Index(0).Set(ValueOf((v1
.Index(0).Index(0).String() + " ")[:3]))
3793 if i1
, i2
:= v1
.Interface(), v2
.Interface(); i1
!= i2
{
3794 t
.Errorf("constructed arrays %v and %v should be equal", i1
, i2
)
3798 m
:= MakeMap(MapOf(at
, TypeOf(int(0))))
3799 m
.SetMapIndex(v1
, ValueOf(1))
3800 if i1
, i2
:= v1
.Interface(), v2
.Interface(); !m
.MapIndex(v2
).IsValid() {
3801 t
.Errorf("constructed arrays %v and %v have different hashes", i1
, i2
)
3805 func TestArrayOfDirectIface(t
*testing
.T
) {
3806 t
.Skip("skipping test because gccgo uses a different directiface value")
3809 i1
:= Zero(TypeOf(T
{})).Interface()
3810 v1
:= ValueOf(&i1
).Elem()
3811 p1
:= v1
.InterfaceData()[1]
3813 i2
:= Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
3814 v2
:= ValueOf(&i2
).Elem()
3815 p2
:= v2
.InterfaceData()[1]
3818 t
.Errorf("got p1=%v. want=%v", p1
, nil)
3822 t
.Errorf("got p2=%v. want=%v", p2
, nil)
3827 i1
:= Zero(TypeOf(T
{})).Interface()
3828 v1
:= ValueOf(&i1
).Elem()
3829 p1
:= v1
.InterfaceData()[1]
3831 i2
:= Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
3832 v2
:= ValueOf(&i2
).Elem()
3833 p2
:= v2
.InterfaceData()[1]
3836 t
.Errorf("got p1=%v. want=not-%v", p1
, nil)
3840 t
.Errorf("got p2=%v. want=not-%v", p2
, nil)
3845 func TestSliceOf(t
*testing
.T
) {
3846 // check construction and use of type not in binary
3848 st
:= SliceOf(TypeOf(T(1)))
3849 v
:= MakeSlice(st
, 10, 10)
3851 for i
:= 0; i
< v
.Len(); i
++ {
3852 v
.Index(i
).Set(ValueOf(T(i
)))
3855 s
:= fmt
.Sprint(v
.Interface())
3856 want
:= "[0 1 2 3 4 5 6 7 8 9]"
3858 t
.Errorf("constructed slice = %s, want %s", s
, want
)
3861 // check that type already in binary is found
3863 checkSameType(t
, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1
{})
3866 func TestSliceOverflow(t
*testing
.T
) {
3867 // check that MakeSlice panics when size of slice overflows uint
3870 l
:= (1<<(unsafe
.Sizeof((*byte)(nil))*8)-1)/s
+ 1
3872 t
.Fatal("slice size does not overflow")
3875 st
:= SliceOf(TypeOf(x
))
3879 t
.Fatal("slice overflow does not panic")
3882 MakeSlice(st
, int(l
), int(l
))
3885 func TestSliceOfGC(t
*testing
.T
) {
3887 tt
:= TypeOf(T(nil))
3891 for i
:= 0; i
< n
; i
++ {
3892 v
:= MakeSlice(st
, n
, n
)
3893 for j
:= 0; j
< v
.Len(); j
++ {
3895 *p
= uintptr(i
*n
+ j
)
3896 v
.Index(j
).Set(ValueOf(p
).Convert(tt
))
3898 x
= append(x
, v
.Interface())
3902 for i
, xi
:= range x
{
3904 for j
:= 0; j
< v
.Len(); j
++ {
3905 k
:= v
.Index(j
).Elem().Interface()
3906 if k
!= uintptr(i
*n
+j
) {
3907 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3913 func TestChanOf(t
*testing
.T
) {
3914 // check construction and use of type not in binary
3916 ct
:= ChanOf(BothDir
, TypeOf(T("")))
3917 v
:= MakeChan(ct
, 2)
3919 v
.Send(ValueOf(T("hello")))
3921 v
.Send(ValueOf(T("world")))
3928 if s1
!= "hello" || s2
!= "world" {
3929 t
.Errorf("constructed chan: have %q, %q, want %q, %q", s1
, s2
, "hello", "world")
3932 // check that type already in binary is found
3934 checkSameType(t
, Zero(ChanOf(BothDir
, TypeOf(T1(1)))).Interface(), (chan T1
)(nil))
3937 func TestChanOfDir(t
*testing
.T
) {
3938 // check construction and use of type not in binary
3940 crt
:= ChanOf(RecvDir
, TypeOf(T("")))
3941 cst
:= ChanOf(SendDir
, TypeOf(T("")))
3943 // check that type already in binary is found
3945 checkSameType(t
, Zero(ChanOf(RecvDir
, TypeOf(T1(1)))).Interface(), (<-chan T1
)(nil))
3946 checkSameType(t
, Zero(ChanOf(SendDir
, TypeOf(T1(1)))).Interface(), (chan<- T1
)(nil))
3948 // check String form of ChanDir
3949 if crt
.ChanDir().String() != "<-chan" {
3950 t
.Errorf("chan dir: have %q, want %q", crt
.ChanDir().String(), "<-chan")
3952 if cst
.ChanDir().String() != "chan<-" {
3953 t
.Errorf("chan dir: have %q, want %q", cst
.ChanDir().String(), "chan<-")
3957 func TestChanOfGC(t
*testing
.T
) {
3958 done
:= make(chan bool, 1)
3962 case <-time
.After(5 * time
.Second
):
3963 panic("deadlock in TestChanOfGC")
3972 tt
:= TypeOf(T(nil))
3973 ct
:= ChanOf(BothDir
, tt
)
3975 // NOTE: The garbage collector handles allocated channels specially,
3976 // so we have to save pointers to channels in x; the pointer code will
3977 // use the gc info in the newly constructed chan type.
3980 for i
:= 0; i
< n
; i
++ {
3981 v
:= MakeChan(ct
, n
)
3982 for j
:= 0; j
< n
; j
++ {
3984 *p
= uintptr(i
*n
+ j
)
3985 v
.Send(ValueOf(p
).Convert(tt
))
3989 x
= append(x
, pv
.Interface())
3993 for i
, xi
:= range x
{
3994 v
:= ValueOf(xi
).Elem()
3995 for j
:= 0; j
< n
; j
++ {
3997 k
:= pv
.Elem().Interface()
3998 if k
!= uintptr(i
*n
+j
) {
3999 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
4005 func TestMapOf(t
*testing
.T
) {
4006 // check construction and use of type not in binary
4010 v
:= MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
4012 v
.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
4015 s
:= fmt
.Sprint(v
.Interface())
4018 t
.Errorf("constructed map = %s, want %s", s
, want
)
4021 // check that type already in binary is found
4022 checkSameType(t
, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V
]K(nil))
4024 // check that invalid key type panics
4025 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
4028 func TestMapOfGCKeys(t
*testing
.T
) {
4030 tt
:= TypeOf(T(nil))
4031 mt
:= MapOf(tt
, TypeOf(false))
4033 // NOTE: The garbage collector handles allocated maps specially,
4034 // so we have to save pointers to maps in x; the pointer code will
4035 // use the gc info in the newly constructed map type.
4038 for i
:= 0; i
< n
; i
++ {
4040 for j
:= 0; j
< n
; j
++ {
4042 *p
= uintptr(i
*n
+ j
)
4043 v
.SetMapIndex(ValueOf(p
).Convert(tt
), ValueOf(true))
4047 x
= append(x
, pv
.Interface())
4051 for i
, xi
:= range x
{
4052 v
:= ValueOf(xi
).Elem()
4054 for _
, kv
:= range v
.MapKeys() {
4055 out
= append(out
, int(kv
.Elem().Interface().(uintptr)))
4058 for j
, k
:= range out
{
4060 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
4066 func TestMapOfGCValues(t
*testing
.T
) {
4068 tt
:= TypeOf(T(nil))
4069 mt
:= MapOf(TypeOf(1), tt
)
4071 // NOTE: The garbage collector handles allocated maps specially,
4072 // so we have to save pointers to maps in x; the pointer code will
4073 // use the gc info in the newly constructed map type.
4076 for i
:= 0; i
< n
; i
++ {
4078 for j
:= 0; j
< n
; j
++ {
4080 *p
= uintptr(i
*n
+ j
)
4081 v
.SetMapIndex(ValueOf(j
), ValueOf(p
).Convert(tt
))
4085 x
= append(x
, pv
.Interface())
4089 for i
, xi
:= range x
{
4090 v
:= ValueOf(xi
).Elem()
4091 for j
:= 0; j
< n
; j
++ {
4092 k
:= v
.MapIndex(ValueOf(j
)).Elem().Interface().(uintptr)
4093 if k
!= uintptr(i
*n
+j
) {
4094 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
4100 func TestTypelinksSorted(t
*testing
.T
) {
4102 for i
, n
:= range TypeLinks() {
4104 t
.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last
, i
-1, n
, i
)
4110 func TestFuncOf(t
*testing
.T
) {
4111 // check construction and use of type not in binary
4115 fn
:= func(args
[]Value
) []Value
{
4117 t
.Errorf("args == %v, want exactly one arg", args
)
4118 } else if args
[0].Type() != TypeOf(K("")) {
4119 t
.Errorf("args[0] is type %v, want %v", args
[0].Type
, TypeOf(K("")))
4120 } else if args
[0].String() != "gopher" {
4121 t
.Errorf("args[0] = %q, want %q", args
[0].String(), "gopher")
4123 return []Value
{ValueOf(V(3.14))}
4125 v
:= MakeFunc(FuncOf([]Type
{TypeOf(K(""))}, []Type
{TypeOf(V(0))}, false), fn
)
4127 outs
:= v
.Call([]Value
{ValueOf(K("gopher"))})
4129 t
.Fatalf("v.Call returned %v, want exactly one result", outs
)
4130 } else if outs
[0].Type() != TypeOf(V(0)) {
4131 t
.Fatalf("c.Call[0] is type %v, want %v", outs
[0].Type
, TypeOf(V(0)))
4133 f
:= outs
[0].Float()
4135 t
.Errorf("constructed func returned %f, want %f", f
, 3.14)
4138 // check that types already in binary are found
4140 testCases
:= []struct {
4145 {in
: []Type
{TypeOf(T1(0))}, want
: (func(T1
))(nil)},
4146 {in
: []Type
{TypeOf(int(0))}, want
: (func(int))(nil)},
4147 {in
: []Type
{SliceOf(TypeOf(int(0)))}, variadic
: true, want
: (func(...int))(nil)},
4148 {in
: []Type
{TypeOf(int(0))}, out
: []Type
{TypeOf(false)}, want
: (func(int) bool)(nil)},
4149 {in
: []Type
{TypeOf(int(0))}, out
: []Type
{TypeOf(false), TypeOf("")}, want
: (func(int) (bool, string))(nil)},
4151 for _
, tt
:= range testCases
{
4152 checkSameType(t
, Zero(FuncOf(tt
.in
, tt
.out
, tt
.variadic
)).Interface(), tt
.want
)
4155 // check that variadic requires last element be a slice.
4156 FuncOf([]Type
{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
4157 shouldPanic(func() { FuncOf([]Type
{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
4158 shouldPanic(func() { FuncOf(nil, nil, true) })
4167 func BenchmarkFieldByName1(b
*testing
.B
) {
4169 for i
:= 0; i
< b
.N
; i
++ {
4174 func BenchmarkFieldByName2(b
*testing
.B
) {
4176 for i
:= 0; i
< b
.N
; i
++ {
4251 func TestEmbed(t
*testing
.T
) {
4253 f
, ok
:= typ
.FieldByName("X")
4255 t
.Fatalf(`FieldByName("X") should fail, returned %v`, f
.Index
)
4259 func BenchmarkFieldByName3(b
*testing
.B
) {
4261 for i
:= 0; i
< b
.N
; i
++ {
4271 func BenchmarkInterfaceBig(b
*testing
.B
) {
4273 for i
:= 0; i
< b
.N
; i
++ {
4279 func TestAllocsInterfaceBig(t
*testing
.T
) {
4280 if testing
.Short() {
4281 t
.Skip("skipping malloc count in short mode")
4284 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
4285 t
.Error("allocs:", allocs
)
4289 func BenchmarkInterfaceSmall(b
*testing
.B
) {
4290 v
:= ValueOf(int64(0))
4291 for i
:= 0; i
< b
.N
; i
++ {
4296 func TestAllocsInterfaceSmall(t
*testing
.T
) {
4297 if testing
.Short() {
4298 t
.Skip("skipping malloc count in short mode")
4300 v
:= ValueOf(int64(0))
4301 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
4302 t
.Error("allocs:", allocs
)
4306 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
4307 // The basic usage is:
4310 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
4313 // Each iteration of the loop returns a different set of results, until all
4314 // possible result sets have been explored. It is okay for different code paths
4315 // to make different method call sequences on x, but there must be no
4316 // other source of non-determinism in the call sequences.
4318 // When faced with a new decision, x chooses randomly. Future explorations
4319 // of that path will choose successive values for the result. Thus, stopping
4320 // the loop after a fixed number of iterations gives somewhat stochastic
4326 // v := make([]bool, x.Choose(4))
4327 // for i := range v {
4333 // prints (in some order):
4342 // [false false false]
4345 // [false false false false]
4347 // [true true true true]
4349 type exhaustive
struct {
4355 type choice
struct {
4361 func (x
*exhaustive
) Next() bool {
4363 x
.r
= rand
.New(rand
.NewSource(time
.Now().UnixNano()))
4370 for i
:= len(x
.last
) - 1; i
>= 0; i
-- {
4374 x
.last
= x
.last
[:i
+1]
4381 func (x
*exhaustive
) Choose(max
int) int {
4382 if x
.pos
>= len(x
.last
) {
4383 x
.last
= append(x
.last
, choice
{x
.r
.Intn(max
), 0, max
})
4388 panic("inconsistent use of exhaustive tester")
4390 return (c
.n
+ c
.off
) % max
4393 func (x
*exhaustive
) Maybe() bool {
4394 return x
.Choose(2) == 1
4397 func GCFunc(args
[]Value
) []Value
{
4402 func TestReflectFuncTraceback(t
*testing
.T
) {
4403 f
:= MakeFunc(TypeOf(func() {}), GCFunc
)
4407 func TestReflectMethodTraceback(t
*testing
.T
) {
4409 m
:= ValueOf(p
).MethodByName("GCMethod")
4410 i
:= ValueOf(m
.Interface()).Call([]Value
{ValueOf(5)})[0].Int()
4412 t
.Errorf("Call returned %d; want 8", i
)
4416 func TestBigZero(t
*testing
.T
) {
4417 const size
= 1 << 10
4419 z
:= Zero(ValueOf(v
).Type()).Interface().([size
]byte)
4420 for i
:= 0; i
< size
; i
++ {
4422 t
.Fatalf("Zero object not all zero, index %d", i
)
4427 func TestFieldByIndexNil(t
*testing
.T
) {
4436 v
.FieldByName("P") // should be fine
4439 if err
:= recover(); err
== nil {
4440 t
.Fatalf("no error")
4441 } else if !strings
.Contains(fmt
.Sprint(err
), "nil pointer to embedded struct") {
4442 t
.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err
)
4445 v
.FieldByName("F") // should panic
4447 t
.Fatalf("did not panic")
4451 // type Outer struct {
4455 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
4456 // The implementation is logically:
4457 // func (p *Outer) M() {
4460 // but since the only change here is the replacement of one pointer receiver with another,
4461 // the actual generated code overwrites the original receiver with the p.Inner pointer and
4462 // then jumps to the M method expecting the *Inner receiver.
4464 // During reflect.Value.Call, we create an argument frame and the associated data structures
4465 // to describe it to the garbage collector, populate the frame, call reflect.call to
4466 // run a function call using that frame, and then copy the results back out of the frame.
4467 // The reflect.call function does a memmove of the frame structure onto the
4468 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
4469 // the frame structure (to preserve the outputs).
4471 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
4472 // were for the full stack frame. However, in the case where the called function was
4473 // one of these wrappers, the rewritten receiver is almost certainly a different type
4474 // than the original receiver. This is not a problem on the stack, where we use the
4475 // program counter to determine the type information and understand that
4476 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
4477 // memory word is now an *Inner. But in the statically typed argument frame created
4478 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
4479 // off the stack into the frame will store an *Inner there, and then if a garbage collection
4480 // happens to scan that argument frame before it is discarded, it will scan the *Inner
4481 // memory as if it were an *Outer. If the two have different memory layouts, the
4482 // collection will intepret the memory incorrectly.
4484 // One such possible incorrect interpretation is to treat two arbitrary memory words
4485 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
4486 // an interface requires dereferencing the itab word, the misinterpretation will try to
4487 // deference Inner.P1, causing a crash during garbage collection.
4489 // This came up in a real program in issue 7725.
4502 func (pi
*Inner
) M() {
4503 // Clear references to pi so that the only way the
4504 // garbage collection will find the pointer is in the
4505 // argument frame, typed as a *Outer.
4508 // Set up an interface value that will cause a crash.
4509 // P1 = 1 is a non-zero, so the interface looks non-nil.
4510 // P2 = pi ensures that the data word points into the
4511 // allocated heap; if not the collection skips the interface
4512 // value as irrelevant, without dereferencing P1.
4514 pi
.P2
= uintptr(unsafe
.Pointer(pi
))
4517 func TestCallMethodJump(t
*testing
.T
) {
4518 // In reflect.Value.Call, trigger a garbage collection after reflect.call
4519 // returns but before the args frame has been discarded.
4520 // This is a little clumsy but makes the failure repeatable.
4523 p
:= &Outer
{Inner
: new(Inner
)}
4525 ValueOf(p
).Method(0).Call(nil)
4527 // Stop garbage collecting during reflect.call.
4531 func TestMakeFuncStackCopy(t
*testing
.T
) {
4532 target
:= func(in
[]Value
) []Value
{
4535 return []Value
{ValueOf(9)}
4538 var concrete
func(*int, int) int
4539 fn
:= MakeFunc(ValueOf(concrete
).Type(), target
)
4540 ValueOf(&concrete
).Elem().Set(fn
)
4541 x
:= concrete(nil, 7)
4543 t
.Errorf("have %#q want 9", x
)
4547 // use about n KB of stack
4548 func useStack(n
int) {
4552 var b
[1024]byte // makes frame about 1KB
4553 useStack(n
- 1 + int(b
[99]))
4560 func TestValueString(t
*testing
.T
) {
4561 rv
:= ValueOf(Impl
{})
4562 if rv
.String() != "<reflect_test.Impl Value>" {
4563 t
.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv
.String(), "<reflect_test.Impl Value>")
4566 method
:= rv
.Method(0)
4567 if method
.String() != "<func() Value>" {
4568 t
.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method
.String(), "<func() Value>")
4572 func TestInvalid(t
*testing
.T
) {
4573 // Used to have inconsistency between IsValid() and Kind() != Invalid.
4574 type T
struct{ v
interface{} }
4576 v
:= ValueOf(T
{}).Field(0)
4577 if v
.IsValid() != true || v
.Kind() != Interface
{
4578 t
.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v
.IsValid(), v
.Kind())
4581 if v
.IsValid() != false || v
.Kind() != Invalid
{
4582 t
.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v
.IsValid(), v
.Kind())
4587 func TestLargeGCProg(t
*testing
.T
) {
4588 fv
:= ValueOf(func([256]*byte) {})
4589 fv
.Call([]Value
{ValueOf([256]*byte{})})
4593 func TestCallGC(t
*testing
.T
) {
4594 f
:= func(a
, b
, c
, d
, e
string) {
4596 g
:= func(in
[]Value
) []Value
{
4600 typ
:= ValueOf(f
).Type()
4601 f2
:= MakeFunc(typ
, g
).Interface().(func(string, string, string, string, string))
4602 f2("four", "five5", "six666", "seven77", "eight888")
4605 type funcLayoutTest
struct {
4607 size
, argsize
, retOffset
uintptr
4608 stack
[]byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized)
4612 var funcLayoutTests
[]funcLayoutTest
4615 var argAlign
uintptr = PtrSize
4616 if runtime
.GOARCH
== "amd64p32" {
4617 argAlign
= 2 * PtrSize
4619 roundup
:= func(x
uintptr, a
uintptr) uintptr {
4620 return (x
+ a
- 1) / a
* a
4623 funcLayoutTests
= append(funcLayoutTests
,
4626 ValueOf(func(a
, b
string) string { return "" }).Type(),
4631 []byte{1, 0, 1, 0, 1},
4636 r
= []byte{0, 0, 0, 1}
4640 funcLayoutTests
= append(funcLayoutTests
,
4643 ValueOf(func(a
, b
, c
uint32, p
*byte, d
uint16) {}).Type(),
4644 roundup(roundup(3*4, PtrSize
)+PtrSize
+2, argAlign
),
4645 roundup(3*4, PtrSize
) + PtrSize
+ 2,
4646 roundup(roundup(3*4, PtrSize
)+PtrSize
+2, argAlign
),
4651 funcLayoutTests
= append(funcLayoutTests
,
4654 ValueOf(func(a
map[int]int, b
uintptr, c
interface{}) {}).Type(),
4666 funcLayoutTests
= append(funcLayoutTests
,
4669 ValueOf(func(a S
) {}).Type(),
4677 funcLayoutTests
= append(funcLayoutTests
,
4679 ValueOf((*byte)(nil)).Type(),
4680 ValueOf(func(a
uintptr, b
*int) {}).Type(),
4681 roundup(3*PtrSize
, argAlign
),
4683 roundup(3*PtrSize
, argAlign
),
4688 funcLayoutTests
= append(funcLayoutTests
,
4691 ValueOf(func(a
uintptr) {}).Type(),
4692 roundup(PtrSize
, argAlign
),
4694 roundup(PtrSize
, argAlign
),
4699 funcLayoutTests
= append(funcLayoutTests
,
4702 ValueOf(func() uintptr { return 0 }).Type(),
4710 funcLayoutTests
= append(funcLayoutTests
,
4712 ValueOf(uintptr(0)).Type(),
4713 ValueOf(func(a
uintptr) {}).Type(),
4719 // Note: this one is tricky, as the receiver is not a pointer. But we
4720 // pass the receiver by reference to the autogenerated pointer-receiver
4721 // version of the function.
4725 func TestFuncLayout(t
*testing
.T
) {
4726 t
.Skip("gccgo does not use funcLayout")
4727 for _
, lt
:= range funcLayoutTests
{
4728 typ
, argsize
, retOffset
, stack
, gc
, ptrs
:= FuncLayout(lt
.t
, lt
.rcvr
)
4729 if typ
.Size() != lt
.size
{
4730 t
.Errorf("funcLayout(%v, %v).size=%d, want %d", lt
.t
, lt
.rcvr
, typ
.Size(), lt
.size
)
4732 if argsize
!= lt
.argsize
{
4733 t
.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt
.t
, lt
.rcvr
, argsize
, lt
.argsize
)
4735 if retOffset
!= lt
.retOffset
{
4736 t
.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt
.t
, lt
.rcvr
, retOffset
, lt
.retOffset
)
4738 if !bytes
.Equal(stack
, lt
.stack
) {
4739 t
.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt
.t
, lt
.rcvr
, stack
, lt
.stack
)
4741 if !bytes
.Equal(gc
, lt
.gc
) {
4742 t
.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt
.t
, lt
.rcvr
, gc
, lt
.gc
)
4744 if ptrs
&& len(stack
) == 0 ||
!ptrs
&& len(stack
) > 0 {
4745 t
.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt
.t
, lt
.rcvr
, ptrs
, !ptrs
)
4750 func verifyGCBits(t
*testing
.T
, typ Type
, bits
[]byte) {
4751 heapBits
:= GCBits(New(typ
).Interface())
4752 if !bytes
.Equal(heapBits
, bits
) {
4753 t
.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ
, heapBits
, bits
)
4757 func verifyGCBitsSlice(t
*testing
.T
, typ Type
, cap int, bits
[]byte) {
4758 // Creating a slice causes the runtime to repeat a bitmap,
4759 // which exercises a different path from making the compiler
4760 // repeat a bitmap for a small array or executing a repeat in
4762 val
:= MakeSlice(typ
, 0, cap)
4763 data
:= NewAt(ArrayOf(cap, typ
), unsafe
.Pointer(val
.Pointer()))
4764 heapBits
:= GCBits(data
.Interface())
4765 // Repeat the bitmap for the slice size, trimming scalars in
4766 // the last element.
4767 bits
= rep(cap, bits
)
4768 for len(bits
) > 2 && bits
[len(bits
)-1] == 0 {
4769 bits
= bits
[:len(bits
)-1]
4771 if !bytes
.Equal(heapBits
, bits
) {
4772 t
.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ
, cap, heapBits
, bits
)
4776 func TestGCBits(t
*testing
.T
) {
4777 t
.Skip("gccgo does not use gcbits yet")
4779 verifyGCBits(t
, TypeOf((*byte)(nil)), []byte{1})
4781 // Building blocks for types seen by the compiler (like [2]Xscalar).
4782 // The compiler will create the type structures for the derived types,
4783 // including their GC metadata.
4784 type Xscalar
struct{ x
uintptr }
4785 type Xptr
struct{ x
*byte }
4786 type Xptrscalar
struct {
4790 type Xscalarptr
struct {
4794 type Xbigptrscalar
struct {
4799 var Tscalar
, Tint64
, Tptr
, Tscalarptr
, Tptrscalar
, Tbigptrscalar Type
4801 // Building blocks for types constructed by reflect.
4802 // This code is in a separate block so that code below
4803 // cannot accidentally refer to these.
4804 // The compiler must NOT see types derived from these
4805 // (for example, [2]Scalar must NOT appear in the program),
4806 // or else reflect will use it instead of having to construct one.
4807 // The goal is to test the construction.
4808 type Scalar
struct{ x
uintptr }
4809 type Ptr
struct{ x
*byte }
4810 type Ptrscalar
struct {
4814 type Scalarptr
struct {
4818 type Bigptrscalar
struct {
4823 Tscalar
= TypeOf(Scalar
{})
4824 Tint64
= TypeOf(Int64(0))
4825 Tptr
= TypeOf(Ptr
{})
4826 Tscalarptr
= TypeOf(Scalarptr
{})
4827 Tptrscalar
= TypeOf(Ptrscalar
{})
4828 Tbigptrscalar
= TypeOf(Bigptrscalar
{})
4833 verifyGCBits(t
, TypeOf(Xscalar
{}), empty
)
4834 verifyGCBits(t
, Tscalar
, empty
)
4835 verifyGCBits(t
, TypeOf(Xptr
{}), lit(1))
4836 verifyGCBits(t
, Tptr
, lit(1))
4837 verifyGCBits(t
, TypeOf(Xscalarptr
{}), lit(0, 1))
4838 verifyGCBits(t
, Tscalarptr
, lit(0, 1))
4839 verifyGCBits(t
, TypeOf(Xptrscalar
{}), lit(1))
4840 verifyGCBits(t
, Tptrscalar
, lit(1))
4842 verifyGCBits(t
, TypeOf([0]Xptr
{}), empty
)
4843 verifyGCBits(t
, ArrayOf(0, Tptr
), empty
)
4844 verifyGCBits(t
, TypeOf([1]Xptrscalar
{}), lit(1))
4845 verifyGCBits(t
, ArrayOf(1, Tptrscalar
), lit(1))
4846 verifyGCBits(t
, TypeOf([2]Xscalar
{}), empty
)
4847 verifyGCBits(t
, ArrayOf(2, Tscalar
), empty
)
4848 verifyGCBits(t
, TypeOf([10000]Xscalar
{}), empty
)
4849 verifyGCBits(t
, ArrayOf(10000, Tscalar
), empty
)
4850 verifyGCBits(t
, TypeOf([2]Xptr
{}), lit(1, 1))
4851 verifyGCBits(t
, ArrayOf(2, Tptr
), lit(1, 1))
4852 verifyGCBits(t
, TypeOf([10000]Xptr
{}), rep(10000, lit(1)))
4853 verifyGCBits(t
, ArrayOf(10000, Tptr
), rep(10000, lit(1)))
4854 verifyGCBits(t
, TypeOf([2]Xscalarptr
{}), lit(0, 1, 0, 1))
4855 verifyGCBits(t
, ArrayOf(2, Tscalarptr
), lit(0, 1, 0, 1))
4856 verifyGCBits(t
, TypeOf([10000]Xscalarptr
{}), rep(10000, lit(0, 1)))
4857 verifyGCBits(t
, ArrayOf(10000, Tscalarptr
), rep(10000, lit(0, 1)))
4858 verifyGCBits(t
, TypeOf([2]Xptrscalar
{}), lit(1, 0, 1))
4859 verifyGCBits(t
, ArrayOf(2, Tptrscalar
), lit(1, 0, 1))
4860 verifyGCBits(t
, TypeOf([10000]Xptrscalar
{}), rep(10000, lit(1, 0)))
4861 verifyGCBits(t
, ArrayOf(10000, Tptrscalar
), rep(10000, lit(1, 0)))
4862 verifyGCBits(t
, TypeOf([1][10000]Xptrscalar
{}), rep(10000, lit(1, 0)))
4863 verifyGCBits(t
, ArrayOf(1, ArrayOf(10000, Tptrscalar
)), rep(10000, lit(1, 0)))
4864 verifyGCBits(t
, TypeOf([2][10000]Xptrscalar
{}), rep(2*10000, lit(1, 0)))
4865 verifyGCBits(t
, ArrayOf(2, ArrayOf(10000, Tptrscalar
)), rep(2*10000, lit(1, 0)))
4866 verifyGCBits(t
, TypeOf([4]Xbigptrscalar
{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
4867 verifyGCBits(t
, ArrayOf(4, Tbigptrscalar
), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
4869 verifyGCBitsSlice(t
, TypeOf([]Xptr
{}), 0, empty
)
4870 verifyGCBitsSlice(t
, SliceOf(Tptr
), 0, empty
)
4871 verifyGCBitsSlice(t
, TypeOf([]Xptrscalar
{}), 1, lit(1))
4872 verifyGCBitsSlice(t
, SliceOf(Tptrscalar
), 1, lit(1))
4873 verifyGCBitsSlice(t
, TypeOf([]Xscalar
{}), 2, lit(0))
4874 verifyGCBitsSlice(t
, SliceOf(Tscalar
), 2, lit(0))
4875 verifyGCBitsSlice(t
, TypeOf([]Xscalar
{}), 10000, lit(0))
4876 verifyGCBitsSlice(t
, SliceOf(Tscalar
), 10000, lit(0))
4877 verifyGCBitsSlice(t
, TypeOf([]Xptr
{}), 2, lit(1))
4878 verifyGCBitsSlice(t
, SliceOf(Tptr
), 2, lit(1))
4879 verifyGCBitsSlice(t
, TypeOf([]Xptr
{}), 10000, lit(1))
4880 verifyGCBitsSlice(t
, SliceOf(Tptr
), 10000, lit(1))
4881 verifyGCBitsSlice(t
, TypeOf([]Xscalarptr
{}), 2, lit(0, 1))
4882 verifyGCBitsSlice(t
, SliceOf(Tscalarptr
), 2, lit(0, 1))
4883 verifyGCBitsSlice(t
, TypeOf([]Xscalarptr
{}), 10000, lit(0, 1))
4884 verifyGCBitsSlice(t
, SliceOf(Tscalarptr
), 10000, lit(0, 1))
4885 verifyGCBitsSlice(t
, TypeOf([]Xptrscalar
{}), 2, lit(1, 0))
4886 verifyGCBitsSlice(t
, SliceOf(Tptrscalar
), 2, lit(1, 0))
4887 verifyGCBitsSlice(t
, TypeOf([]Xptrscalar
{}), 10000, lit(1, 0))
4888 verifyGCBitsSlice(t
, SliceOf(Tptrscalar
), 10000, lit(1, 0))
4889 verifyGCBitsSlice(t
, TypeOf([][10000]Xptrscalar
{}), 1, rep(10000, lit(1, 0)))
4890 verifyGCBitsSlice(t
, SliceOf(ArrayOf(10000, Tptrscalar
)), 1, rep(10000, lit(1, 0)))
4891 verifyGCBitsSlice(t
, TypeOf([][10000]Xptrscalar
{}), 2, rep(10000, lit(1, 0)))
4892 verifyGCBitsSlice(t
, SliceOf(ArrayOf(10000, Tptrscalar
)), 2, rep(10000, lit(1, 0)))
4893 verifyGCBitsSlice(t
, TypeOf([]Xbigptrscalar
{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
4894 verifyGCBitsSlice(t
, SliceOf(Tbigptrscalar
), 4, join(rep(100, lit(1)), rep(100, lit(0))))
4896 verifyGCBits(t
, TypeOf((chan [100]Xscalar
)(nil)), lit(1))
4897 verifyGCBits(t
, ChanOf(BothDir
, ArrayOf(100, Tscalar
)), lit(1))
4899 verifyGCBits(t
, TypeOf((func([10000]Xscalarptr
))(nil)), lit(1))
4900 verifyGCBits(t
, FuncOf([]Type
{ArrayOf(10000, Tscalarptr
)}, nil, false), lit(1))
4902 verifyGCBits(t
, TypeOf((map[[10000]Xscalarptr
]Xscalar
)(nil)), lit(1))
4903 verifyGCBits(t
, MapOf(ArrayOf(10000, Tscalarptr
), Tscalar
), lit(1))
4905 verifyGCBits(t
, TypeOf((*[10000]Xscalar
)(nil)), lit(1))
4906 verifyGCBits(t
, PtrTo(ArrayOf(10000, Tscalar
)), lit(1))
4908 verifyGCBits(t
, TypeOf(([][10000]Xscalar
)(nil)), lit(1))
4909 verifyGCBits(t
, SliceOf(ArrayOf(10000, Tscalar
)), lit(1))
4911 hdr
:= make([]byte, 8/PtrSize
)
4913 verifyMapBucket
:= func(t
*testing
.T
, k
, e Type
, m
interface{}, want
[]byte) {
4914 verifyGCBits(t
, MapBucketOf(k
, e
), want
)
4915 verifyGCBits(t
, CachedBucketOf(TypeOf(m
)), want
)
4919 map[Xscalar
]Xptr(nil),
4920 join(hdr
, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
4923 map[Xscalarptr
]Xptr(nil),
4924 join(hdr
, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
4925 verifyMapBucket(t
, Tint64
, Tptr
,
4926 map[int64]Xptr(nil),
4927 join(hdr
, rep(8, rep(8/PtrSize
, lit(0))), rep(8, lit(1)), naclpad(), lit(1)))
4930 map[Xscalar
]Xscalar(nil),
4933 ArrayOf(2, Tscalarptr
), ArrayOf(3, Tptrscalar
),
4934 map[[2]Xscalarptr
][3]Xptrscalar(nil),
4935 join(hdr
, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
4937 ArrayOf(64/PtrSize
, Tscalarptr
), ArrayOf(64/PtrSize
, Tptrscalar
),
4938 map[[64 / PtrSize
]Xscalarptr
][64 / PtrSize
]Xptrscalar(nil),
4939 join(hdr
, rep(8*64/PtrSize
, lit(0, 1)), rep(8*64/PtrSize
, lit(1, 0)), lit(1)))
4941 ArrayOf(64/PtrSize
+1, Tscalarptr
), ArrayOf(64/PtrSize
, Tptrscalar
),
4942 map[[64/PtrSize
+ 1]Xscalarptr
][64 / PtrSize
]Xptrscalar(nil),
4943 join(hdr
, rep(8, lit(1)), rep(8*64/PtrSize
, lit(1, 0)), lit(1)))
4945 ArrayOf(64/PtrSize
, Tscalarptr
), ArrayOf(64/PtrSize
+1, Tptrscalar
),
4946 map[[64 / PtrSize
]Xscalarptr
][64/PtrSize
+ 1]Xptrscalar(nil),
4947 join(hdr
, rep(8*64/PtrSize
, lit(0, 1)), rep(8, lit(1)), lit(1)))
4949 ArrayOf(64/PtrSize
+1, Tscalarptr
), ArrayOf(64/PtrSize
+1, Tptrscalar
),
4950 map[[64/PtrSize
+ 1]Xscalarptr
][64/PtrSize
+ 1]Xptrscalar(nil),
4951 join(hdr
, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
4954 func naclpad() []byte {
4955 if runtime
.GOARCH
== "amd64p32" {
4961 func rep(n
int, b
[]byte) []byte { return bytes
.Repeat(b
, n
) }
4962 func join(b
...[]byte) []byte { return bytes
.Join(b
, nil) }
4963 func lit(x
...byte) []byte { return x
}
4965 func TestTypeOfTypeOf(t
*testing
.T
) {
4966 // Check that all the type constructors return concrete *rtype implementations.
4967 // It's difficult to test directly because the reflect package is only at arm's length.
4968 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
4969 check
:= func(name
string, typ Type
) {
4970 if underlying
:= TypeOf(typ
).String(); underlying
!= "*reflect.rtype" {
4971 t
.Errorf("%v returned %v, not *reflect.rtype", name
, underlying
)
4975 type T
struct{ int }
4976 check("TypeOf", TypeOf(T
{}))
4978 check("ArrayOf", ArrayOf(10, TypeOf(T
{})))
4979 check("ChanOf", ChanOf(BothDir
, TypeOf(T
{})))
4980 check("FuncOf", FuncOf([]Type
{TypeOf(T
{})}, nil, false))
4981 check("MapOf", MapOf(TypeOf(T
{}), TypeOf(T
{})))
4982 check("PtrTo", PtrTo(TypeOf(T
{})))
4983 check("SliceOf", SliceOf(TypeOf(T
{})))
4988 func (*XM
) String() string { return "" }
4990 func TestPtrToMethods(t
*testing
.T
) {
4992 yp
:= New(TypeOf(y
)).Interface()
4993 _
, ok
:= yp
.(fmt
.Stringer
)
4995 t
.Fatal("does not implement Stringer, but should")
4999 func TestMapAlloc(t
*testing
.T
) {
5000 if runtime
.Compiler
== "gccgo" {
5001 t
.Skip("skipping on gccgo until we have escape analysis")
5003 m
:= ValueOf(make(map[int]int, 10))
5006 allocs
:= testing
.AllocsPerRun(100, func() {
5010 t
.Errorf("allocs per map assignment: want 0 got %f", allocs
)
5014 func TestChanAlloc(t
*testing
.T
) {
5015 if runtime
.Compiler
== "gccgo" {
5016 t
.Skip("skipping on gccgo until we have escape analysis")
5018 // Note: for a chan int, the return Value must be allocated, so we
5019 // use a chan *int instead.
5020 c
:= ValueOf(make(chan *int, 1))
5021 v
:= ValueOf(new(int))
5022 allocs
:= testing
.AllocsPerRun(100, func() {
5026 if allocs
< 0.5 || allocs
> 1.5 {
5027 t
.Errorf("allocs per chan send/recv: want 1 got %f", allocs
)
5029 // Note: there is one allocation in reflect.recv which seems to be
5030 // a limitation of escape analysis. If that is ever fixed the
5031 // allocs < 0.5 condition will trigger and this test should be fixed.