github.com/likebike/go--@v0.0.0-20190911215757-0bd925d16e96/go/src/reflect/all_test.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package reflect_test 6 7 import ( 8 "bytes" 9 "encoding/base64" 10 "flag" 11 "fmt" 12 "io" 13 "math" 14 "math/rand" 15 "os" 16 . "reflect" 17 "runtime" 18 "sort" 19 "strconv" 20 "strings" 21 "sync" 22 "sync/atomic" 23 "testing" 24 "time" 25 "unicode" 26 "unicode/utf8" 27 "unsafe" 28 ) 29 30 var sink interface{} 31 32 func TestBool(t *testing.T) { 33 v := ValueOf(true) 34 if v.Bool() != true { 35 t.Fatal("ValueOf(true).Bool() = false") 36 } 37 } 38 39 type integer int 40 type T struct { 41 a int 42 b float64 43 c string 44 d *int 45 } 46 47 type pair struct { 48 i interface{} 49 s string 50 } 51 52 func assert(t *testing.T, s, want string) { 53 if s != want { 54 t.Errorf("have %#q want %#q", s, want) 55 } 56 } 57 58 var typeTests = []pair{ 59 {struct{ x int }{}, "int"}, 60 {struct{ x int8 }{}, "int8"}, 61 {struct{ x int16 }{}, "int16"}, 62 {struct{ x int32 }{}, "int32"}, 63 {struct{ x int64 }{}, "int64"}, 64 {struct{ x uint }{}, "uint"}, 65 {struct{ x uint8 }{}, "uint8"}, 66 {struct{ x uint16 }{}, "uint16"}, 67 {struct{ x uint32 }{}, "uint32"}, 68 {struct{ x uint64 }{}, "uint64"}, 69 {struct{ x float32 }{}, "float32"}, 70 {struct{ x float64 }{}, "float64"}, 71 {struct{ x int8 }{}, "int8"}, 72 {struct{ x (**int8) }{}, "**int8"}, 73 {struct{ x (**integer) }{}, "**reflect_test.integer"}, 74 {struct{ x ([32]int32) }{}, "[32]int32"}, 75 {struct{ x ([]int8) }{}, "[]int8"}, 76 {struct{ x (map[string]int32) }{}, "map[string]int32"}, 77 {struct{ x (chan<- string) }{}, "chan<- string"}, 78 {struct { 79 x struct { 80 c chan *int32 81 d float32 82 } 83 }{}, 84 "struct { c chan *int32; d float32 }", 85 }, 86 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"}, 87 {struct { 88 x struct { 89 c func(chan *integer, *int8) 90 } 91 }{}, 92 "struct { c func(chan *reflect_test.integer, *int8) }", 93 }, 94 {struct { 95 x struct { 96 a int8 97 b int32 98 } 99 }{}, 100 "struct { a int8; b int32 }", 101 }, 102 {struct { 103 x struct { 104 a int8 105 b int8 106 c int32 107 } 108 }{}, 109 "struct { a int8; b int8; c int32 }", 110 }, 111 {struct { 112 x struct { 113 a int8 114 b int8 115 c int8 116 d int32 117 } 118 }{}, 119 "struct { a int8; b int8; c int8; d int32 }", 120 }, 121 {struct { 122 x struct { 123 a int8 124 b int8 125 c int8 126 d int8 127 e int32 128 } 129 }{}, 130 "struct { a int8; b int8; c int8; d int8; e int32 }", 131 }, 132 {struct { 133 x struct { 134 a int8 135 b int8 136 c int8 137 d int8 138 e int8 139 f int32 140 } 141 }{}, 142 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }", 143 }, 144 {struct { 145 x struct { 146 a int8 `reflect:"hi there"` 147 } 148 }{}, 149 `struct { a int8 "reflect:\"hi there\"" }`, 150 }, 151 {struct { 152 x struct { 153 a int8 `reflect:"hi \x00there\t\n\"\\"` 154 } 155 }{}, 156 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`, 157 }, 158 {struct { 159 x struct { 160 f func(args ...int) 161 } 162 }{}, 163 "struct { f func(...int) }", 164 }, 165 {struct { 166 x (interface { 167 a(func(func(int) int) func(func(int)) int) 168 b() 169 }) 170 }{}, 171 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }", 172 }, 173 } 174 175 var valueTests = []pair{ 176 {new(int), "132"}, 177 {new(int8), "8"}, 178 {new(int16), "16"}, 179 {new(int32), "32"}, 180 {new(int64), "64"}, 181 {new(uint), "132"}, 182 {new(uint8), "8"}, 183 {new(uint16), "16"}, 184 {new(uint32), "32"}, 185 {new(uint64), "64"}, 186 {new(float32), "256.25"}, 187 {new(float64), "512.125"}, 188 {new(complex64), "532.125+10i"}, 189 {new(complex128), "564.25+1i"}, 190 {new(string), "stringy cheese"}, 191 {new(bool), "true"}, 192 {new(*int8), "*int8(0)"}, 193 {new(**int8), "**int8(0)"}, 194 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"}, 195 {new(**integer), "**reflect_test.integer(0)"}, 196 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"}, 197 {new(chan<- string), "chan<- string"}, 198 {new(func(a int8, b int32)), "func(int8, int32)(0)"}, 199 {new(struct { 200 c chan *int32 201 d float32 202 }), 203 "struct { c chan *int32; d float32 }{chan *int32, 0}", 204 }, 205 {new(struct{ c func(chan *integer, *int8) }), 206 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}", 207 }, 208 {new(struct { 209 a int8 210 b int32 211 }), 212 "struct { a int8; b int32 }{0, 0}", 213 }, 214 {new(struct { 215 a int8 216 b int8 217 c int32 218 }), 219 "struct { a int8; b int8; c int32 }{0, 0, 0}", 220 }, 221 } 222 223 func testType(t *testing.T, i int, typ Type, want string) { 224 s := typ.String() 225 if s != want { 226 t.Errorf("#%d: have %#q, want %#q", i, s, want) 227 } 228 } 229 230 func TestTypes(t *testing.T) { 231 for i, tt := range typeTests { 232 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s) 233 } 234 } 235 236 func TestSet(t *testing.T) { 237 for i, tt := range valueTests { 238 v := ValueOf(tt.i) 239 v = v.Elem() 240 switch v.Kind() { 241 case Int: 242 v.SetInt(132) 243 case Int8: 244 v.SetInt(8) 245 case Int16: 246 v.SetInt(16) 247 case Int32: 248 v.SetInt(32) 249 case Int64: 250 v.SetInt(64) 251 case Uint: 252 v.SetUint(132) 253 case Uint8: 254 v.SetUint(8) 255 case Uint16: 256 v.SetUint(16) 257 case Uint32: 258 v.SetUint(32) 259 case Uint64: 260 v.SetUint(64) 261 case Float32: 262 v.SetFloat(256.25) 263 case Float64: 264 v.SetFloat(512.125) 265 case Complex64: 266 v.SetComplex(532.125 + 10i) 267 case Complex128: 268 v.SetComplex(564.25 + 1i) 269 case String: 270 v.SetString("stringy cheese") 271 case Bool: 272 v.SetBool(true) 273 } 274 s := valueToString(v) 275 if s != tt.s { 276 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s) 277 } 278 } 279 } 280 281 func TestSetValue(t *testing.T) { 282 for i, tt := range valueTests { 283 v := ValueOf(tt.i).Elem() 284 switch v.Kind() { 285 case Int: 286 v.Set(ValueOf(int(132))) 287 case Int8: 288 v.Set(ValueOf(int8(8))) 289 case Int16: 290 v.Set(ValueOf(int16(16))) 291 case Int32: 292 v.Set(ValueOf(int32(32))) 293 case Int64: 294 v.Set(ValueOf(int64(64))) 295 case Uint: 296 v.Set(ValueOf(uint(132))) 297 case Uint8: 298 v.Set(ValueOf(uint8(8))) 299 case Uint16: 300 v.Set(ValueOf(uint16(16))) 301 case Uint32: 302 v.Set(ValueOf(uint32(32))) 303 case Uint64: 304 v.Set(ValueOf(uint64(64))) 305 case Float32: 306 v.Set(ValueOf(float32(256.25))) 307 case Float64: 308 v.Set(ValueOf(512.125)) 309 case Complex64: 310 v.Set(ValueOf(complex64(532.125 + 10i))) 311 case Complex128: 312 v.Set(ValueOf(complex128(564.25 + 1i))) 313 case String: 314 v.Set(ValueOf("stringy cheese")) 315 case Bool: 316 v.Set(ValueOf(true)) 317 } 318 s := valueToString(v) 319 if s != tt.s { 320 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s) 321 } 322 } 323 } 324 325 func TestCanSetField(t *testing.T) { 326 type embed struct{ x, X int } 327 type Embed struct{ x, X int } 328 type S1 struct { 329 embed 330 x, X int 331 } 332 type S2 struct { 333 *embed 334 x, X int 335 } 336 type S3 struct { 337 Embed 338 x, X int 339 } 340 type S4 struct { 341 *Embed 342 x, X int 343 } 344 345 type testCase struct { 346 index []int 347 canSet bool 348 } 349 tests := []struct { 350 val Value 351 cases []testCase 352 }{{ 353 val: ValueOf(&S1{}), 354 cases: []testCase{ 355 {[]int{0}, false}, 356 {[]int{0, 0}, false}, 357 {[]int{0, 1}, true}, 358 {[]int{1}, false}, 359 {[]int{2}, true}, 360 }, 361 }, { 362 val: ValueOf(&S2{embed: &embed{}}), 363 cases: []testCase{ 364 {[]int{0}, false}, 365 {[]int{0, 0}, false}, 366 {[]int{0, 1}, true}, 367 {[]int{1}, false}, 368 {[]int{2}, true}, 369 }, 370 }, { 371 val: ValueOf(&S3{}), 372 cases: []testCase{ 373 {[]int{0}, true}, 374 {[]int{0, 0}, false}, 375 {[]int{0, 1}, true}, 376 {[]int{1}, false}, 377 {[]int{2}, true}, 378 }, 379 }, { 380 val: ValueOf(&S4{Embed: &Embed{}}), 381 cases: []testCase{ 382 {[]int{0}, true}, 383 {[]int{0, 0}, false}, 384 {[]int{0, 1}, true}, 385 {[]int{1}, false}, 386 {[]int{2}, true}, 387 }, 388 }} 389 390 for _, tt := range tests { 391 t.Run(tt.val.Type().Name(), func(t *testing.T) { 392 for _, tc := range tt.cases { 393 f := tt.val 394 for _, i := range tc.index { 395 if f.Kind() == Ptr { 396 f = f.Elem() 397 } 398 f = f.Field(i) 399 } 400 if got := f.CanSet(); got != tc.canSet { 401 t.Errorf("CanSet() = %v, want %v", got, tc.canSet) 402 } 403 } 404 }) 405 } 406 } 407 408 var _i = 7 409 410 var valueToStringTests = []pair{ 411 {123, "123"}, 412 {123.5, "123.5"}, 413 {byte(123), "123"}, 414 {"abc", "abc"}, 415 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"}, 416 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"}, 417 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, 418 {&[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})"}, 419 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, 420 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"}, 421 } 422 423 func TestValueToString(t *testing.T) { 424 for i, test := range valueToStringTests { 425 s := valueToString(ValueOf(test.i)) 426 if s != test.s { 427 t.Errorf("#%d: have %#q, want %#q", i, s, test.s) 428 } 429 } 430 } 431 432 func TestArrayElemSet(t *testing.T) { 433 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem() 434 v.Index(4).SetInt(123) 435 s := valueToString(v) 436 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}" 437 if s != want { 438 t.Errorf("[10]int: have %#q want %#q", s, want) 439 } 440 441 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) 442 v.Index(4).SetInt(123) 443 s = valueToString(v) 444 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}" 445 if s != want1 { 446 t.Errorf("[]int: have %#q want %#q", s, want1) 447 } 448 } 449 450 func TestPtrPointTo(t *testing.T) { 451 var ip *int32 452 var i int32 = 1234 453 vip := ValueOf(&ip) 454 vi := ValueOf(&i).Elem() 455 vip.Elem().Set(vi.Addr()) 456 if *ip != 1234 { 457 t.Errorf("got %d, want 1234", *ip) 458 } 459 460 ip = nil 461 vp := ValueOf(&ip).Elem() 462 vp.Set(Zero(vp.Type())) 463 if ip != nil { 464 t.Errorf("got non-nil (%p), want nil", ip) 465 } 466 } 467 468 func TestPtrSetNil(t *testing.T) { 469 var i int32 = 1234 470 ip := &i 471 vip := ValueOf(&ip) 472 vip.Elem().Set(Zero(vip.Elem().Type())) 473 if ip != nil { 474 t.Errorf("got non-nil (%d), want nil", *ip) 475 } 476 } 477 478 func TestMapSetNil(t *testing.T) { 479 m := make(map[string]int) 480 vm := ValueOf(&m) 481 vm.Elem().Set(Zero(vm.Elem().Type())) 482 if m != nil { 483 t.Errorf("got non-nil (%p), want nil", m) 484 } 485 } 486 487 func TestAll(t *testing.T) { 488 testType(t, 1, TypeOf((int8)(0)), "int8") 489 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8") 490 491 typ := TypeOf((*struct { 492 c chan *int32 493 d float32 494 })(nil)) 495 testType(t, 3, typ, "*struct { c chan *int32; d float32 }") 496 etyp := typ.Elem() 497 testType(t, 4, etyp, "struct { c chan *int32; d float32 }") 498 styp := etyp 499 f := styp.Field(0) 500 testType(t, 5, f.Type, "chan *int32") 501 502 f, present := styp.FieldByName("d") 503 if !present { 504 t.Errorf("FieldByName says present field is absent") 505 } 506 testType(t, 6, f.Type, "float32") 507 508 f, present = styp.FieldByName("absent") 509 if present { 510 t.Errorf("FieldByName says absent field is present") 511 } 512 513 typ = TypeOf([32]int32{}) 514 testType(t, 7, typ, "[32]int32") 515 testType(t, 8, typ.Elem(), "int32") 516 517 typ = TypeOf((map[string]*int32)(nil)) 518 testType(t, 9, typ, "map[string]*int32") 519 mtyp := typ 520 testType(t, 10, mtyp.Key(), "string") 521 testType(t, 11, mtyp.Elem(), "*int32") 522 523 typ = TypeOf((chan<- string)(nil)) 524 testType(t, 12, typ, "chan<- string") 525 testType(t, 13, typ.Elem(), "string") 526 527 // make sure tag strings are not part of element type 528 typ = TypeOf(struct { 529 d []uint32 `reflect:"TAG"` 530 }{}).Field(0).Type 531 testType(t, 14, typ, "[]uint32") 532 } 533 534 func TestInterfaceGet(t *testing.T) { 535 var inter struct { 536 E interface{} 537 } 538 inter.E = 123.456 539 v1 := ValueOf(&inter) 540 v2 := v1.Elem().Field(0) 541 assert(t, v2.Type().String(), "interface {}") 542 i2 := v2.Interface() 543 v3 := ValueOf(i2) 544 assert(t, v3.Type().String(), "float64") 545 } 546 547 func TestInterfaceValue(t *testing.T) { 548 var inter struct { 549 E interface{} 550 } 551 inter.E = 123.456 552 v1 := ValueOf(&inter) 553 v2 := v1.Elem().Field(0) 554 assert(t, v2.Type().String(), "interface {}") 555 v3 := v2.Elem() 556 assert(t, v3.Type().String(), "float64") 557 558 i3 := v2.Interface() 559 if _, ok := i3.(float64); !ok { 560 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3)) 561 } 562 } 563 564 func TestFunctionValue(t *testing.T) { 565 var x interface{} = func() {} 566 v := ValueOf(x) 567 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) { 568 t.Fatalf("TestFunction returned wrong pointer") 569 } 570 assert(t, v.Type().String(), "func()") 571 } 572 573 var appendTests = []struct { 574 orig, extra []int 575 }{ 576 {make([]int, 2, 4), []int{22}}, 577 {make([]int, 2, 4), []int{22, 33, 44}}, 578 } 579 580 func sameInts(x, y []int) bool { 581 if len(x) != len(y) { 582 return false 583 } 584 for i, xx := range x { 585 if xx != y[i] { 586 return false 587 } 588 } 589 return true 590 } 591 592 func TestAppend(t *testing.T) { 593 for i, test := range appendTests { 594 origLen, extraLen := len(test.orig), len(test.extra) 595 want := append(test.orig, test.extra...) 596 // Convert extra from []int to []Value. 597 e0 := make([]Value, len(test.extra)) 598 for j, e := range test.extra { 599 e0[j] = ValueOf(e) 600 } 601 // Convert extra from []int to *SliceValue. 602 e1 := ValueOf(test.extra) 603 // Test Append. 604 a0 := ValueOf(test.orig) 605 have0 := Append(a0, e0...).Interface().([]int) 606 if !sameInts(have0, want) { 607 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0) 608 } 609 // Check that the orig and extra slices were not modified. 610 if len(test.orig) != origLen { 611 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen) 612 } 613 if len(test.extra) != extraLen { 614 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen) 615 } 616 // Test AppendSlice. 617 a1 := ValueOf(test.orig) 618 have1 := AppendSlice(a1, e1).Interface().([]int) 619 if !sameInts(have1, want) { 620 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want) 621 } 622 // Check that the orig and extra slices were not modified. 623 if len(test.orig) != origLen { 624 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen) 625 } 626 if len(test.extra) != extraLen { 627 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen) 628 } 629 } 630 } 631 632 func TestCopy(t *testing.T) { 633 a := []int{1, 2, 3, 4, 10, 9, 8, 7} 634 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} 635 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} 636 for i := 0; i < len(b); i++ { 637 if b[i] != c[i] { 638 t.Fatalf("b != c before test") 639 } 640 } 641 a1 := a 642 b1 := b 643 aa := ValueOf(&a1).Elem() 644 ab := ValueOf(&b1).Elem() 645 for tocopy := 1; tocopy <= 7; tocopy++ { 646 aa.SetLen(tocopy) 647 Copy(ab, aa) 648 aa.SetLen(8) 649 for i := 0; i < tocopy; i++ { 650 if a[i] != b[i] { 651 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d", 652 tocopy, i, a[i], i, b[i]) 653 } 654 } 655 for i := tocopy; i < len(b); i++ { 656 if b[i] != c[i] { 657 if i < len(a) { 658 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d", 659 tocopy, i, a[i], i, b[i], i, c[i]) 660 } else { 661 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d", 662 tocopy, i, b[i], i, c[i]) 663 } 664 } else { 665 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i) 666 } 667 } 668 } 669 } 670 671 func TestCopyString(t *testing.T) { 672 t.Run("Slice", func(t *testing.T) { 673 s := bytes.Repeat([]byte{'_'}, 8) 674 val := ValueOf(s) 675 676 n := Copy(val, ValueOf("")) 677 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) { 678 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting) 679 } 680 681 n = Copy(val, ValueOf("hello")) 682 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) { 683 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting) 684 } 685 686 n = Copy(val, ValueOf("helloworld")) 687 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) { 688 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting) 689 } 690 }) 691 t.Run("Array", func(t *testing.T) { 692 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'} 693 val := ValueOf(&s).Elem() 694 695 n := Copy(val, ValueOf("")) 696 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) { 697 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting) 698 } 699 700 n = Copy(val, ValueOf("hello")) 701 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) { 702 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting) 703 } 704 705 n = Copy(val, ValueOf("helloworld")) 706 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) { 707 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting) 708 } 709 }) 710 } 711 712 func TestCopyArray(t *testing.T) { 713 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7} 714 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} 715 c := b 716 aa := ValueOf(&a).Elem() 717 ab := ValueOf(&b).Elem() 718 Copy(ab, aa) 719 for i := 0; i < len(a); i++ { 720 if a[i] != b[i] { 721 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i]) 722 } 723 } 724 for i := len(a); i < len(b); i++ { 725 if b[i] != c[i] { 726 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i]) 727 } else { 728 t.Logf("elem %d is okay\n", i) 729 } 730 } 731 } 732 733 func TestBigUnnamedStruct(t *testing.T) { 734 b := struct{ a, b, c, d int64 }{1, 2, 3, 4} 735 v := ValueOf(b) 736 b1 := v.Interface().(struct { 737 a, b, c, d int64 738 }) 739 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d { 740 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1) 741 } 742 } 743 744 type big struct { 745 a, b, c, d, e int64 746 } 747 748 func TestBigStruct(t *testing.T) { 749 b := big{1, 2, 3, 4, 5} 750 v := ValueOf(b) 751 b1 := v.Interface().(big) 752 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e { 753 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1) 754 } 755 } 756 757 type Basic struct { 758 x int 759 y float32 760 } 761 762 type NotBasic Basic 763 764 type DeepEqualTest struct { 765 a, b interface{} 766 eq bool 767 } 768 769 // Simple functions for DeepEqual tests. 770 var ( 771 fn1 func() // nil. 772 fn2 func() // nil. 773 fn3 = func() { fn1() } // Not nil. 774 ) 775 776 type self struct{} 777 778 type Loop *Loop 779 type Loopy interface{} 780 781 var loop1, loop2 Loop 782 var loopy1, loopy2 Loopy 783 784 func init() { 785 loop1 = &loop2 786 loop2 = &loop1 787 788 loopy1 = &loopy2 789 loopy2 = &loopy1 790 } 791 792 var deepEqualTests = []DeepEqualTest{ 793 // Equalities 794 {nil, nil, true}, 795 {1, 1, true}, 796 {int32(1), int32(1), true}, 797 {0.5, 0.5, true}, 798 {float32(0.5), float32(0.5), true}, 799 {"hello", "hello", true}, 800 {make([]int, 10), make([]int, 10), true}, 801 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true}, 802 {Basic{1, 0.5}, Basic{1, 0.5}, true}, 803 {error(nil), error(nil), true}, 804 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true}, 805 {fn1, fn2, true}, 806 807 // Inequalities 808 {1, 2, false}, 809 {int32(1), int32(2), false}, 810 {0.5, 0.6, false}, 811 {float32(0.5), float32(0.6), false}, 812 {"hello", "hey", false}, 813 {make([]int, 10), make([]int, 11), false}, 814 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false}, 815 {Basic{1, 0.5}, Basic{1, 0.6}, false}, 816 {Basic{1, 0}, Basic{2, 0}, false}, 817 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false}, 818 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false}, 819 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false}, 820 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false}, 821 {nil, 1, false}, 822 {1, nil, false}, 823 {fn1, fn3, false}, 824 {fn3, fn3, false}, 825 {[][]int{{1}}, [][]int{{2}}, false}, 826 {math.NaN(), math.NaN(), false}, 827 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false}, 828 {&[1]float64{math.NaN()}, self{}, true}, 829 {[]float64{math.NaN()}, []float64{math.NaN()}, false}, 830 {[]float64{math.NaN()}, self{}, true}, 831 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false}, 832 {map[float64]float64{math.NaN(): 1}, self{}, true}, 833 834 // Nil vs empty: not the same. 835 {[]int{}, []int(nil), false}, 836 {[]int{}, []int{}, true}, 837 {[]int(nil), []int(nil), true}, 838 {map[int]int{}, map[int]int(nil), false}, 839 {map[int]int{}, map[int]int{}, true}, 840 {map[int]int(nil), map[int]int(nil), true}, 841 842 // Mismatched types 843 {1, 1.0, false}, 844 {int32(1), int64(1), false}, 845 {0.5, "hello", false}, 846 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false}, 847 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false}, 848 {Basic{1, 0.5}, NotBasic{1, 0.5}, false}, 849 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false}, 850 851 // Possible loops. 852 {&loop1, &loop1, true}, 853 {&loop1, &loop2, true}, 854 {&loopy1, &loopy1, true}, 855 {&loopy1, &loopy2, true}, 856 } 857 858 func TestDeepEqual(t *testing.T) { 859 for _, test := range deepEqualTests { 860 if test.b == (self{}) { 861 test.b = test.a 862 } 863 if r := DeepEqual(test.a, test.b); r != test.eq { 864 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq) 865 } 866 } 867 } 868 869 func TestTypeOf(t *testing.T) { 870 // Special case for nil 871 if typ := TypeOf(nil); typ != nil { 872 t.Errorf("expected nil type for nil value; got %v", typ) 873 } 874 for _, test := range deepEqualTests { 875 v := ValueOf(test.a) 876 if !v.IsValid() { 877 continue 878 } 879 typ := TypeOf(test.a) 880 if typ != v.Type() { 881 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type()) 882 } 883 } 884 } 885 886 type Recursive struct { 887 x int 888 r *Recursive 889 } 890 891 func TestDeepEqualRecursiveStruct(t *testing.T) { 892 a, b := new(Recursive), new(Recursive) 893 *a = Recursive{12, a} 894 *b = Recursive{12, b} 895 if !DeepEqual(a, b) { 896 t.Error("DeepEqual(recursive same) = false, want true") 897 } 898 } 899 900 type _Complex struct { 901 a int 902 b [3]*_Complex 903 c *string 904 d map[float64]float64 905 } 906 907 func TestDeepEqualComplexStruct(t *testing.T) { 908 m := make(map[float64]float64) 909 stra, strb := "hello", "hello" 910 a, b := new(_Complex), new(_Complex) 911 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m} 912 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m} 913 if !DeepEqual(a, b) { 914 t.Error("DeepEqual(complex same) = false, want true") 915 } 916 } 917 918 func TestDeepEqualComplexStructInequality(t *testing.T) { 919 m := make(map[float64]float64) 920 stra, strb := "hello", "helloo" // Difference is here 921 a, b := new(_Complex), new(_Complex) 922 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m} 923 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m} 924 if DeepEqual(a, b) { 925 t.Error("DeepEqual(complex different) = true, want false") 926 } 927 } 928 929 type UnexpT struct { 930 m map[int]int 931 } 932 933 func TestDeepEqualUnexportedMap(t *testing.T) { 934 // Check that DeepEqual can look at unexported fields. 935 x1 := UnexpT{map[int]int{1: 2}} 936 x2 := UnexpT{map[int]int{1: 2}} 937 if !DeepEqual(&x1, &x2) { 938 t.Error("DeepEqual(x1, x2) = false, want true") 939 } 940 941 y1 := UnexpT{map[int]int{2: 3}} 942 if DeepEqual(&x1, &y1) { 943 t.Error("DeepEqual(x1, y1) = true, want false") 944 } 945 } 946 947 func check2ndField(x interface{}, offs uintptr, t *testing.T) { 948 s := ValueOf(x) 949 f := s.Type().Field(1) 950 if f.Offset != offs { 951 t.Error("mismatched offsets in structure alignment:", f.Offset, offs) 952 } 953 } 954 955 // Check that structure alignment & offsets viewed through reflect agree with those 956 // from the compiler itself. 957 func TestAlignment(t *testing.T) { 958 type T1inner struct { 959 a int 960 } 961 type T1 struct { 962 T1inner 963 f int 964 } 965 type T2inner struct { 966 a, b int 967 } 968 type T2 struct { 969 T2inner 970 f int 971 } 972 973 x := T1{T1inner{2}, 17} 974 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t) 975 976 x1 := T2{T2inner{2, 3}, 17} 977 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t) 978 } 979 980 func Nil(a interface{}, t *testing.T) { 981 n := ValueOf(a).Field(0) 982 if !n.IsNil() { 983 t.Errorf("%v should be nil", a) 984 } 985 } 986 987 func NotNil(a interface{}, t *testing.T) { 988 n := ValueOf(a).Field(0) 989 if n.IsNil() { 990 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String()) 991 } 992 } 993 994 func TestIsNil(t *testing.T) { 995 // These implement IsNil. 996 // Wrap in extra struct to hide interface type. 997 doNil := []interface{}{ 998 struct{ x *int }{}, 999 struct{ x interface{} }{}, 1000 struct{ x map[string]int }{}, 1001 struct{ x func() bool }{}, 1002 struct{ x chan int }{}, 1003 struct{ x []string }{}, 1004 } 1005 for _, ts := range doNil { 1006 ty := TypeOf(ts).Field(0).Type 1007 v := Zero(ty) 1008 v.IsNil() // panics if not okay to call 1009 } 1010 1011 // Check the implementations 1012 var pi struct { 1013 x *int 1014 } 1015 Nil(pi, t) 1016 pi.x = new(int) 1017 NotNil(pi, t) 1018 1019 var si struct { 1020 x []int 1021 } 1022 Nil(si, t) 1023 si.x = make([]int, 10) 1024 NotNil(si, t) 1025 1026 var ci struct { 1027 x chan int 1028 } 1029 Nil(ci, t) 1030 ci.x = make(chan int) 1031 NotNil(ci, t) 1032 1033 var mi struct { 1034 x map[int]int 1035 } 1036 Nil(mi, t) 1037 mi.x = make(map[int]int) 1038 NotNil(mi, t) 1039 1040 var ii struct { 1041 x interface{} 1042 } 1043 Nil(ii, t) 1044 ii.x = 2 1045 NotNil(ii, t) 1046 1047 var fi struct { 1048 x func(t *testing.T) 1049 } 1050 Nil(fi, t) 1051 fi.x = TestIsNil 1052 NotNil(fi, t) 1053 } 1054 1055 func TestInterfaceExtraction(t *testing.T) { 1056 var s struct { 1057 W io.Writer 1058 } 1059 1060 s.W = os.Stdout 1061 v := Indirect(ValueOf(&s)).Field(0).Interface() 1062 if v != s.W.(interface{}) { 1063 t.Error("Interface() on interface: ", v, s.W) 1064 } 1065 } 1066 1067 func TestNilPtrValueSub(t *testing.T) { 1068 var pi *int 1069 if pv := ValueOf(pi); pv.Elem().IsValid() { 1070 t.Error("ValueOf((*int)(nil)).Elem().IsValid()") 1071 } 1072 } 1073 1074 func TestMap(t *testing.T) { 1075 m := map[string]int{"a": 1, "b": 2} 1076 mv := ValueOf(m) 1077 if n := mv.Len(); n != len(m) { 1078 t.Errorf("Len = %d, want %d", n, len(m)) 1079 } 1080 keys := mv.MapKeys() 1081 newmap := MakeMap(mv.Type()) 1082 for k, v := range m { 1083 // Check that returned Keys match keys in range. 1084 // These aren't required to be in the same order. 1085 seen := false 1086 for _, kv := range keys { 1087 if kv.String() == k { 1088 seen = true 1089 break 1090 } 1091 } 1092 if !seen { 1093 t.Errorf("Missing key %q", k) 1094 } 1095 1096 // Check that value lookup is correct. 1097 vv := mv.MapIndex(ValueOf(k)) 1098 if vi := vv.Int(); vi != int64(v) { 1099 t.Errorf("Key %q: have value %d, want %d", k, vi, v) 1100 } 1101 1102 // Copy into new map. 1103 newmap.SetMapIndex(ValueOf(k), ValueOf(v)) 1104 } 1105 vv := mv.MapIndex(ValueOf("not-present")) 1106 if vv.IsValid() { 1107 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv)) 1108 } 1109 1110 newm := newmap.Interface().(map[string]int) 1111 if len(newm) != len(m) { 1112 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m)) 1113 } 1114 1115 for k, v := range newm { 1116 mv, ok := m[k] 1117 if mv != v { 1118 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok) 1119 } 1120 } 1121 1122 newmap.SetMapIndex(ValueOf("a"), Value{}) 1123 v, ok := newm["a"] 1124 if ok { 1125 t.Errorf("newm[\"a\"] = %d after delete", v) 1126 } 1127 1128 mv = ValueOf(&m).Elem() 1129 mv.Set(Zero(mv.Type())) 1130 if m != nil { 1131 t.Errorf("mv.Set(nil) failed") 1132 } 1133 } 1134 1135 func TestNilMap(t *testing.T) { 1136 var m map[string]int 1137 mv := ValueOf(m) 1138 keys := mv.MapKeys() 1139 if len(keys) != 0 { 1140 t.Errorf(">0 keys for nil map: %v", keys) 1141 } 1142 1143 // Check that value for missing key is zero. 1144 x := mv.MapIndex(ValueOf("hello")) 1145 if x.Kind() != Invalid { 1146 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x) 1147 } 1148 1149 // Check big value too. 1150 var mbig map[string][10 << 20]byte 1151 x = ValueOf(mbig).MapIndex(ValueOf("hello")) 1152 if x.Kind() != Invalid { 1153 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x) 1154 } 1155 1156 // Test that deletes from a nil map succeed. 1157 mv.SetMapIndex(ValueOf("hi"), Value{}) 1158 } 1159 1160 func TestChan(t *testing.T) { 1161 for loop := 0; loop < 2; loop++ { 1162 var c chan int 1163 var cv Value 1164 1165 // check both ways to allocate channels 1166 switch loop { 1167 case 1: 1168 c = make(chan int, 1) 1169 cv = ValueOf(c) 1170 case 0: 1171 cv = MakeChan(TypeOf(c), 1) 1172 c = cv.Interface().(chan int) 1173 } 1174 1175 // Send 1176 cv.Send(ValueOf(2)) 1177 if i := <-c; i != 2 { 1178 t.Errorf("reflect Send 2, native recv %d", i) 1179 } 1180 1181 // Recv 1182 c <- 3 1183 if i, ok := cv.Recv(); i.Int() != 3 || !ok { 1184 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok) 1185 } 1186 1187 // TryRecv fail 1188 val, ok := cv.TryRecv() 1189 if val.IsValid() || ok { 1190 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok) 1191 } 1192 1193 // TryRecv success 1194 c <- 4 1195 val, ok = cv.TryRecv() 1196 if !val.IsValid() { 1197 t.Errorf("TryRecv on ready chan got nil") 1198 } else if i := val.Int(); i != 4 || !ok { 1199 t.Errorf("native send 4, TryRecv %d, %t", i, ok) 1200 } 1201 1202 // TrySend fail 1203 c <- 100 1204 ok = cv.TrySend(ValueOf(5)) 1205 i := <-c 1206 if ok { 1207 t.Errorf("TrySend on full chan succeeded: value %d", i) 1208 } 1209 1210 // TrySend success 1211 ok = cv.TrySend(ValueOf(6)) 1212 if !ok { 1213 t.Errorf("TrySend on empty chan failed") 1214 select { 1215 case x := <-c: 1216 t.Errorf("TrySend failed but it did send %d", x) 1217 default: 1218 } 1219 } else { 1220 if i = <-c; i != 6 { 1221 t.Errorf("TrySend 6, recv %d", i) 1222 } 1223 } 1224 1225 // Close 1226 c <- 123 1227 cv.Close() 1228 if i, ok := cv.Recv(); i.Int() != 123 || !ok { 1229 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok) 1230 } 1231 if i, ok := cv.Recv(); i.Int() != 0 || ok { 1232 t.Errorf("after close Recv %d, %t", i.Int(), ok) 1233 } 1234 } 1235 1236 // check creation of unbuffered channel 1237 var c chan int 1238 cv := MakeChan(TypeOf(c), 0) 1239 c = cv.Interface().(chan int) 1240 if cv.TrySend(ValueOf(7)) { 1241 t.Errorf("TrySend on sync chan succeeded") 1242 } 1243 if v, ok := cv.TryRecv(); v.IsValid() || ok { 1244 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok) 1245 } 1246 1247 // len/cap 1248 cv = MakeChan(TypeOf(c), 10) 1249 c = cv.Interface().(chan int) 1250 for i := 0; i < 3; i++ { 1251 c <- i 1252 } 1253 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) { 1254 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c)) 1255 } 1256 } 1257 1258 // caseInfo describes a single case in a select test. 1259 type caseInfo struct { 1260 desc string 1261 canSelect bool 1262 recv Value 1263 closed bool 1264 helper func() 1265 panic bool 1266 } 1267 1268 var allselect = flag.Bool("allselect", false, "exhaustive select test") 1269 1270 func TestSelect(t *testing.T) { 1271 selectWatch.once.Do(func() { go selectWatcher() }) 1272 1273 var x exhaustive 1274 nch := 0 1275 newop := func(n int, cap int) (ch, val Value) { 1276 nch++ 1277 if nch%101%2 == 1 { 1278 c := make(chan int, cap) 1279 ch = ValueOf(c) 1280 val = ValueOf(n) 1281 } else { 1282 c := make(chan string, cap) 1283 ch = ValueOf(c) 1284 val = ValueOf(fmt.Sprint(n)) 1285 } 1286 return 1287 } 1288 1289 for n := 0; x.Next(); n++ { 1290 if testing.Short() && n >= 1000 { 1291 break 1292 } 1293 if n >= 100000 && !*allselect { 1294 break 1295 } 1296 if n%100000 == 0 && testing.Verbose() { 1297 println("TestSelect", n) 1298 } 1299 var cases []SelectCase 1300 var info []caseInfo 1301 1302 // Ready send. 1303 if x.Maybe() { 1304 ch, val := newop(len(cases), 1) 1305 cases = append(cases, SelectCase{ 1306 Dir: SelectSend, 1307 Chan: ch, 1308 Send: val, 1309 }) 1310 info = append(info, caseInfo{desc: "ready send", canSelect: true}) 1311 } 1312 1313 // Ready recv. 1314 if x.Maybe() { 1315 ch, val := newop(len(cases), 1) 1316 ch.Send(val) 1317 cases = append(cases, SelectCase{ 1318 Dir: SelectRecv, 1319 Chan: ch, 1320 }) 1321 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val}) 1322 } 1323 1324 // Blocking send. 1325 if x.Maybe() { 1326 ch, val := newop(len(cases), 0) 1327 cases = append(cases, SelectCase{ 1328 Dir: SelectSend, 1329 Chan: ch, 1330 Send: val, 1331 }) 1332 // Let it execute? 1333 if x.Maybe() { 1334 f := func() { ch.Recv() } 1335 info = append(info, caseInfo{desc: "blocking send", helper: f}) 1336 } else { 1337 info = append(info, caseInfo{desc: "blocking send"}) 1338 } 1339 } 1340 1341 // Blocking recv. 1342 if x.Maybe() { 1343 ch, val := newop(len(cases), 0) 1344 cases = append(cases, SelectCase{ 1345 Dir: SelectRecv, 1346 Chan: ch, 1347 }) 1348 // Let it execute? 1349 if x.Maybe() { 1350 f := func() { ch.Send(val) } 1351 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f}) 1352 } else { 1353 info = append(info, caseInfo{desc: "blocking recv"}) 1354 } 1355 } 1356 1357 // Zero Chan send. 1358 if x.Maybe() { 1359 // Maybe include value to send. 1360 var val Value 1361 if x.Maybe() { 1362 val = ValueOf(100) 1363 } 1364 cases = append(cases, SelectCase{ 1365 Dir: SelectSend, 1366 Send: val, 1367 }) 1368 info = append(info, caseInfo{desc: "zero Chan send"}) 1369 } 1370 1371 // Zero Chan receive. 1372 if x.Maybe() { 1373 cases = append(cases, SelectCase{ 1374 Dir: SelectRecv, 1375 }) 1376 info = append(info, caseInfo{desc: "zero Chan recv"}) 1377 } 1378 1379 // nil Chan send. 1380 if x.Maybe() { 1381 cases = append(cases, SelectCase{ 1382 Dir: SelectSend, 1383 Chan: ValueOf((chan int)(nil)), 1384 Send: ValueOf(101), 1385 }) 1386 info = append(info, caseInfo{desc: "nil Chan send"}) 1387 } 1388 1389 // nil Chan recv. 1390 if x.Maybe() { 1391 cases = append(cases, SelectCase{ 1392 Dir: SelectRecv, 1393 Chan: ValueOf((chan int)(nil)), 1394 }) 1395 info = append(info, caseInfo{desc: "nil Chan recv"}) 1396 } 1397 1398 // closed Chan send. 1399 if x.Maybe() { 1400 ch := make(chan int) 1401 close(ch) 1402 cases = append(cases, SelectCase{ 1403 Dir: SelectSend, 1404 Chan: ValueOf(ch), 1405 Send: ValueOf(101), 1406 }) 1407 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true}) 1408 } 1409 1410 // closed Chan recv. 1411 if x.Maybe() { 1412 ch, val := newop(len(cases), 0) 1413 ch.Close() 1414 val = Zero(val.Type()) 1415 cases = append(cases, SelectCase{ 1416 Dir: SelectRecv, 1417 Chan: ch, 1418 }) 1419 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val}) 1420 } 1421 1422 var helper func() // goroutine to help the select complete 1423 1424 // Add default? Must be last case here, but will permute. 1425 // Add the default if the select would otherwise 1426 // block forever, and maybe add it anyway. 1427 numCanSelect := 0 1428 canProceed := false 1429 canBlock := true 1430 canPanic := false 1431 helpers := []int{} 1432 for i, c := range info { 1433 if c.canSelect { 1434 canProceed = true 1435 canBlock = false 1436 numCanSelect++ 1437 if c.panic { 1438 canPanic = true 1439 } 1440 } else if c.helper != nil { 1441 canProceed = true 1442 helpers = append(helpers, i) 1443 } 1444 } 1445 if !canProceed || x.Maybe() { 1446 cases = append(cases, SelectCase{ 1447 Dir: SelectDefault, 1448 }) 1449 info = append(info, caseInfo{desc: "default", canSelect: canBlock}) 1450 numCanSelect++ 1451 } else if canBlock { 1452 // Select needs to communicate with another goroutine. 1453 cas := &info[helpers[x.Choose(len(helpers))]] 1454 helper = cas.helper 1455 cas.canSelect = true 1456 numCanSelect++ 1457 } 1458 1459 // Permute cases and case info. 1460 // Doing too much here makes the exhaustive loop 1461 // too exhausting, so just do two swaps. 1462 for loop := 0; loop < 2; loop++ { 1463 i := x.Choose(len(cases)) 1464 j := x.Choose(len(cases)) 1465 cases[i], cases[j] = cases[j], cases[i] 1466 info[i], info[j] = info[j], info[i] 1467 } 1468 1469 if helper != nil { 1470 // We wait before kicking off a goroutine to satisfy a blocked select. 1471 // The pause needs to be big enough to let the select block before 1472 // we run the helper, but if we lose that race once in a while it's okay: the 1473 // select will just proceed immediately. Not a big deal. 1474 // For short tests we can grow [sic] the timeout a bit without fear of taking too long 1475 pause := 10 * time.Microsecond 1476 if testing.Short() { 1477 pause = 100 * time.Microsecond 1478 } 1479 time.AfterFunc(pause, helper) 1480 } 1481 1482 // Run select. 1483 i, recv, recvOK, panicErr := runSelect(cases, info) 1484 if panicErr != nil && !canPanic { 1485 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr) 1486 } 1487 if panicErr == nil && canPanic && numCanSelect == 1 { 1488 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i) 1489 } 1490 if panicErr != nil { 1491 continue 1492 } 1493 1494 cas := info[i] 1495 if !cas.canSelect { 1496 recvStr := "" 1497 if recv.IsValid() { 1498 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK) 1499 } 1500 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr) 1501 continue 1502 } 1503 if cas.panic { 1504 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i) 1505 continue 1506 } 1507 1508 if cases[i].Dir == SelectRecv { 1509 if !recv.IsValid() { 1510 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed) 1511 } 1512 if !cas.recv.IsValid() { 1513 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i) 1514 } 1515 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed { 1516 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed { 1517 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface()) 1518 } 1519 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed) 1520 } 1521 } else { 1522 if recv.IsValid() || recvOK { 1523 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false) 1524 } 1525 } 1526 } 1527 } 1528 1529 // selectWatch and the selectWatcher are a watchdog mechanism for running Select. 1530 // If the selectWatcher notices that the select has been blocked for >1 second, it prints 1531 // an error describing the select and panics the entire test binary. 1532 var selectWatch struct { 1533 sync.Mutex 1534 once sync.Once 1535 now time.Time 1536 info []caseInfo 1537 } 1538 1539 func selectWatcher() { 1540 for { 1541 time.Sleep(1 * time.Second) 1542 selectWatch.Lock() 1543 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second { 1544 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info)) 1545 panic("select stuck") 1546 } 1547 selectWatch.Unlock() 1548 } 1549 } 1550 1551 // runSelect runs a single select test. 1552 // It returns the values returned by Select but also returns 1553 // a panic value if the Select panics. 1554 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) { 1555 defer func() { 1556 panicErr = recover() 1557 1558 selectWatch.Lock() 1559 selectWatch.info = nil 1560 selectWatch.Unlock() 1561 }() 1562 1563 selectWatch.Lock() 1564 selectWatch.now = time.Now() 1565 selectWatch.info = info 1566 selectWatch.Unlock() 1567 1568 chosen, recv, recvOK = Select(cases) 1569 return 1570 } 1571 1572 // fmtSelect formats the information about a single select test. 1573 func fmtSelect(info []caseInfo) string { 1574 var buf bytes.Buffer 1575 fmt.Fprintf(&buf, "\nselect {\n") 1576 for i, cas := range info { 1577 fmt.Fprintf(&buf, "%d: %s", i, cas.desc) 1578 if cas.recv.IsValid() { 1579 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface()) 1580 } 1581 if cas.canSelect { 1582 fmt.Fprintf(&buf, " canselect") 1583 } 1584 if cas.panic { 1585 fmt.Fprintf(&buf, " panic") 1586 } 1587 fmt.Fprintf(&buf, "\n") 1588 } 1589 fmt.Fprintf(&buf, "}") 1590 return buf.String() 1591 } 1592 1593 type two [2]uintptr 1594 1595 // Difficult test for function call because of 1596 // implicit padding between arguments. 1597 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) { 1598 return b, c, d, e, f, g, h 1599 } 1600 1601 func TestFunc(t *testing.T) { 1602 ret := ValueOf(dummy).Call([]Value{ 1603 ValueOf(byte(10)), 1604 ValueOf(20), 1605 ValueOf(byte(30)), 1606 ValueOf(two{40, 50}), 1607 ValueOf(byte(60)), 1608 ValueOf(float32(70)), 1609 ValueOf(byte(80)), 1610 }) 1611 if len(ret) != 7 { 1612 t.Fatalf("Call returned %d values, want 7", len(ret)) 1613 } 1614 1615 i := byte(ret[0].Uint()) 1616 j := int(ret[1].Int()) 1617 k := byte(ret[2].Uint()) 1618 l := ret[3].Interface().(two) 1619 m := byte(ret[4].Uint()) 1620 n := float32(ret[5].Float()) 1621 o := byte(ret[6].Uint()) 1622 1623 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 { 1624 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) 1625 } 1626 1627 for i, v := range ret { 1628 if v.CanAddr() { 1629 t.Errorf("result %d is addressable", i) 1630 } 1631 } 1632 } 1633 1634 func TestCallConvert(t *testing.T) { 1635 v := ValueOf(new(io.ReadWriter)).Elem() 1636 f := ValueOf(func(r io.Reader) io.Reader { return r }) 1637 out := f.Call([]Value{v}) 1638 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() { 1639 t.Errorf("expected [nil], got %v", out) 1640 } 1641 } 1642 1643 type emptyStruct struct{} 1644 1645 type nonEmptyStruct struct { 1646 member int 1647 } 1648 1649 func returnEmpty() emptyStruct { 1650 return emptyStruct{} 1651 } 1652 1653 func takesEmpty(e emptyStruct) { 1654 } 1655 1656 func returnNonEmpty(i int) nonEmptyStruct { 1657 return nonEmptyStruct{member: i} 1658 } 1659 1660 func takesNonEmpty(n nonEmptyStruct) int { 1661 return n.member 1662 } 1663 1664 func TestCallWithStruct(t *testing.T) { 1665 r := ValueOf(returnEmpty).Call(nil) 1666 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) { 1667 t.Errorf("returning empty struct returned %#v instead", r) 1668 } 1669 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})}) 1670 if len(r) != 0 { 1671 t.Errorf("takesEmpty returned values: %#v", r) 1672 } 1673 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)}) 1674 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 { 1675 t.Errorf("returnNonEmpty returned %#v", r) 1676 } 1677 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})}) 1678 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 { 1679 t.Errorf("takesNonEmpty returned %#v", r) 1680 } 1681 } 1682 1683 func TestCallReturnsEmpty(t *testing.T) { 1684 // Issue 21717: past-the-end pointer write in Call with 1685 // nonzero-sized frame and zero-sized return value. 1686 runtime.GC() 1687 var finalized uint32 1688 f := func() (emptyStruct, *int) { 1689 i := new(int) 1690 runtime.SetFinalizer(i, func(*int) { atomic.StoreUint32(&finalized, 1) }) 1691 return emptyStruct{}, i 1692 } 1693 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run. 1694 timeout := time.After(5 * time.Second) 1695 for atomic.LoadUint32(&finalized) == 0 { 1696 select { 1697 case <-timeout: 1698 t.Fatal("finalizer did not run") 1699 default: 1700 } 1701 runtime.Gosched() 1702 runtime.GC() 1703 } 1704 runtime.KeepAlive(v) 1705 } 1706 1707 func BenchmarkCall(b *testing.B) { 1708 fv := ValueOf(func(a, b string) {}) 1709 b.ReportAllocs() 1710 b.RunParallel(func(pb *testing.PB) { 1711 args := []Value{ValueOf("a"), ValueOf("b")} 1712 for pb.Next() { 1713 fv.Call(args) 1714 } 1715 }) 1716 } 1717 1718 func BenchmarkCallArgCopy(b *testing.B) { 1719 byteArray := func(n int) Value { 1720 return Zero(ArrayOf(n, TypeOf(byte(0)))) 1721 } 1722 sizes := [...]struct { 1723 fv Value 1724 arg Value 1725 }{ 1726 {ValueOf(func(a [128]byte) {}), byteArray(128)}, 1727 {ValueOf(func(a [256]byte) {}), byteArray(256)}, 1728 {ValueOf(func(a [1024]byte) {}), byteArray(1024)}, 1729 {ValueOf(func(a [4096]byte) {}), byteArray(4096)}, 1730 {ValueOf(func(a [65536]byte) {}), byteArray(65536)}, 1731 } 1732 for _, size := range sizes { 1733 bench := func(b *testing.B) { 1734 args := []Value{size.arg} 1735 b.SetBytes(int64(size.arg.Len())) 1736 b.ResetTimer() 1737 b.RunParallel(func(pb *testing.PB) { 1738 for pb.Next() { 1739 size.fv.Call(args) 1740 } 1741 }) 1742 } 1743 name := fmt.Sprintf("size=%v", size.arg.Len()) 1744 b.Run(name, bench) 1745 } 1746 } 1747 1748 func TestMakeFunc(t *testing.T) { 1749 f := dummy 1750 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in }) 1751 ValueOf(&f).Elem().Set(fv) 1752 1753 // Call g with small arguments so that there is 1754 // something predictable (and different from the 1755 // correct results) in those positions on the stack. 1756 g := dummy 1757 g(1, 2, 3, two{4, 5}, 6, 7, 8) 1758 1759 // Call constructed function f. 1760 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80) 1761 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 { 1762 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) 1763 } 1764 } 1765 1766 func TestMakeFuncInterface(t *testing.T) { 1767 fn := func(i int) int { return i } 1768 incr := func(in []Value) []Value { 1769 return []Value{ValueOf(int(in[0].Int() + 1))} 1770 } 1771 fv := MakeFunc(TypeOf(fn), incr) 1772 ValueOf(&fn).Elem().Set(fv) 1773 if r := fn(2); r != 3 { 1774 t.Errorf("Call returned %d, want 3", r) 1775 } 1776 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 { 1777 t.Errorf("Call returned %d, want 15", r) 1778 } 1779 if r := fv.Interface().(func(int) int)(26); r != 27 { 1780 t.Errorf("Call returned %d, want 27", r) 1781 } 1782 } 1783 1784 func TestMakeFuncVariadic(t *testing.T) { 1785 // Test that variadic arguments are packed into a slice and passed as last arg 1786 fn := func(_ int, is ...int) []int { return nil } 1787 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] }) 1788 ValueOf(&fn).Elem().Set(fv) 1789 1790 r := fn(1, 2, 3) 1791 if r[0] != 2 || r[1] != 3 { 1792 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1793 } 1794 1795 r = fn(1, []int{2, 3}...) 1796 if r[0] != 2 || r[1] != 3 { 1797 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1798 } 1799 1800 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int) 1801 if r[0] != 2 || r[1] != 3 { 1802 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1803 } 1804 1805 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int) 1806 if r[0] != 2 || r[1] != 3 { 1807 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1808 } 1809 1810 f := fv.Interface().(func(int, ...int) []int) 1811 1812 r = f(1, 2, 3) 1813 if r[0] != 2 || r[1] != 3 { 1814 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1815 } 1816 r = f(1, []int{2, 3}...) 1817 if r[0] != 2 || r[1] != 3 { 1818 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1819 } 1820 } 1821 1822 type Point struct { 1823 x, y int 1824 } 1825 1826 // This will be index 0. 1827 func (p Point) AnotherMethod(scale int) int { 1828 return -1 1829 } 1830 1831 // This will be index 1. 1832 func (p Point) Dist(scale int) int { 1833 //println("Point.Dist", p.x, p.y, scale) 1834 return p.x*p.x*scale + p.y*p.y*scale 1835 } 1836 1837 // This will be index 2. 1838 func (p Point) GCMethod(k int) int { 1839 runtime.GC() 1840 return k + p.x 1841 } 1842 1843 // This will be index 3. 1844 func (p Point) NoArgs() { 1845 // Exercise no-argument/no-result paths. 1846 } 1847 1848 // This will be index 4. 1849 func (p Point) TotalDist(points ...Point) int { 1850 tot := 0 1851 for _, q := range points { 1852 dx := q.x - p.x 1853 dy := q.y - p.y 1854 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test. 1855 1856 } 1857 return tot 1858 } 1859 1860 func TestMethod(t *testing.T) { 1861 // Non-curried method of type. 1862 p := Point{3, 4} 1863 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int() 1864 if i != 250 { 1865 t.Errorf("Type Method returned %d; want 250", i) 1866 } 1867 1868 m, ok := TypeOf(p).MethodByName("Dist") 1869 if !ok { 1870 t.Fatalf("method by name failed") 1871 } 1872 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int() 1873 if i != 275 { 1874 t.Errorf("Type MethodByName returned %d; want 275", i) 1875 } 1876 1877 m, ok = TypeOf(p).MethodByName("NoArgs") 1878 if !ok { 1879 t.Fatalf("method by name failed") 1880 } 1881 n := len(m.Func.Call([]Value{ValueOf(p)})) 1882 if n != 0 { 1883 t.Errorf("NoArgs returned %d values; want 0", n) 1884 } 1885 1886 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int() 1887 if i != 300 { 1888 t.Errorf("Pointer Type Method returned %d; want 300", i) 1889 } 1890 1891 m, ok = TypeOf(&p).MethodByName("Dist") 1892 if !ok { 1893 t.Fatalf("ptr method by name failed") 1894 } 1895 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int() 1896 if i != 325 { 1897 t.Errorf("Pointer Type MethodByName returned %d; want 325", i) 1898 } 1899 1900 m, ok = TypeOf(&p).MethodByName("NoArgs") 1901 if !ok { 1902 t.Fatalf("method by name failed") 1903 } 1904 n = len(m.Func.Call([]Value{ValueOf(&p)})) 1905 if n != 0 { 1906 t.Errorf("NoArgs returned %d values; want 0", n) 1907 } 1908 1909 // Curried method of value. 1910 tfunc := TypeOf((func(int) int)(nil)) 1911 v := ValueOf(p).Method(1) 1912 if tt := v.Type(); tt != tfunc { 1913 t.Errorf("Value Method Type is %s; want %s", tt, tfunc) 1914 } 1915 i = v.Call([]Value{ValueOf(14)})[0].Int() 1916 if i != 350 { 1917 t.Errorf("Value Method returned %d; want 350", i) 1918 } 1919 v = ValueOf(p).MethodByName("Dist") 1920 if tt := v.Type(); tt != tfunc { 1921 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc) 1922 } 1923 i = v.Call([]Value{ValueOf(15)})[0].Int() 1924 if i != 375 { 1925 t.Errorf("Value MethodByName returned %d; want 375", i) 1926 } 1927 v = ValueOf(p).MethodByName("NoArgs") 1928 v.Call(nil) 1929 1930 // Curried method of pointer. 1931 v = ValueOf(&p).Method(1) 1932 if tt := v.Type(); tt != tfunc { 1933 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc) 1934 } 1935 i = v.Call([]Value{ValueOf(16)})[0].Int() 1936 if i != 400 { 1937 t.Errorf("Pointer Value Method returned %d; want 400", i) 1938 } 1939 v = ValueOf(&p).MethodByName("Dist") 1940 if tt := v.Type(); tt != tfunc { 1941 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc) 1942 } 1943 i = v.Call([]Value{ValueOf(17)})[0].Int() 1944 if i != 425 { 1945 t.Errorf("Pointer Value MethodByName returned %d; want 425", i) 1946 } 1947 v = ValueOf(&p).MethodByName("NoArgs") 1948 v.Call(nil) 1949 1950 // Curried method of interface value. 1951 // Have to wrap interface value in a struct to get at it. 1952 // Passing it to ValueOf directly would 1953 // access the underlying Point, not the interface. 1954 var x interface { 1955 Dist(int) int 1956 } = p 1957 pv := ValueOf(&x).Elem() 1958 v = pv.Method(0) 1959 if tt := v.Type(); tt != tfunc { 1960 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc) 1961 } 1962 i = v.Call([]Value{ValueOf(18)})[0].Int() 1963 if i != 450 { 1964 t.Errorf("Interface Method returned %d; want 450", i) 1965 } 1966 v = pv.MethodByName("Dist") 1967 if tt := v.Type(); tt != tfunc { 1968 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc) 1969 } 1970 i = v.Call([]Value{ValueOf(19)})[0].Int() 1971 if i != 475 { 1972 t.Errorf("Interface MethodByName returned %d; want 475", i) 1973 } 1974 } 1975 1976 func TestMethodValue(t *testing.T) { 1977 p := Point{3, 4} 1978 var i int64 1979 1980 // Curried method of value. 1981 tfunc := TypeOf((func(int) int)(nil)) 1982 v := ValueOf(p).Method(1) 1983 if tt := v.Type(); tt != tfunc { 1984 t.Errorf("Value Method Type is %s; want %s", tt, tfunc) 1985 } 1986 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int() 1987 if i != 250 { 1988 t.Errorf("Value Method returned %d; want 250", i) 1989 } 1990 v = ValueOf(p).MethodByName("Dist") 1991 if tt := v.Type(); tt != tfunc { 1992 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc) 1993 } 1994 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int() 1995 if i != 275 { 1996 t.Errorf("Value MethodByName returned %d; want 275", i) 1997 } 1998 v = ValueOf(p).MethodByName("NoArgs") 1999 ValueOf(v.Interface()).Call(nil) 2000 v.Interface().(func())() 2001 2002 // Curried method of pointer. 2003 v = ValueOf(&p).Method(1) 2004 if tt := v.Type(); tt != tfunc { 2005 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc) 2006 } 2007 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int() 2008 if i != 300 { 2009 t.Errorf("Pointer Value Method returned %d; want 300", i) 2010 } 2011 v = ValueOf(&p).MethodByName("Dist") 2012 if tt := v.Type(); tt != tfunc { 2013 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc) 2014 } 2015 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int() 2016 if i != 325 { 2017 t.Errorf("Pointer Value MethodByName returned %d; want 325", i) 2018 } 2019 v = ValueOf(&p).MethodByName("NoArgs") 2020 ValueOf(v.Interface()).Call(nil) 2021 v.Interface().(func())() 2022 2023 // Curried method of pointer to pointer. 2024 pp := &p 2025 v = ValueOf(&pp).Elem().Method(1) 2026 if tt := v.Type(); tt != tfunc { 2027 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc) 2028 } 2029 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int() 2030 if i != 350 { 2031 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i) 2032 } 2033 v = ValueOf(&pp).Elem().MethodByName("Dist") 2034 if tt := v.Type(); tt != tfunc { 2035 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc) 2036 } 2037 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int() 2038 if i != 375 { 2039 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i) 2040 } 2041 2042 // Curried method of interface value. 2043 // Have to wrap interface value in a struct to get at it. 2044 // Passing it to ValueOf directly would 2045 // access the underlying Point, not the interface. 2046 var s = struct { 2047 X interface { 2048 Dist(int) int 2049 } 2050 }{p} 2051 pv := ValueOf(s).Field(0) 2052 v = pv.Method(0) 2053 if tt := v.Type(); tt != tfunc { 2054 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc) 2055 } 2056 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int() 2057 if i != 400 { 2058 t.Errorf("Interface Method returned %d; want 400", i) 2059 } 2060 v = pv.MethodByName("Dist") 2061 if tt := v.Type(); tt != tfunc { 2062 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc) 2063 } 2064 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int() 2065 if i != 425 { 2066 t.Errorf("Interface MethodByName returned %d; want 425", i) 2067 } 2068 } 2069 2070 func TestVariadicMethodValue(t *testing.T) { 2071 p := Point{3, 4} 2072 points := []Point{{20, 21}, {22, 23}, {24, 25}} 2073 want := int64(p.TotalDist(points[0], points[1], points[2])) 2074 2075 // Curried method of value. 2076 tfunc := TypeOf((func(...Point) int)(nil)) 2077 v := ValueOf(p).Method(4) 2078 if tt := v.Type(); tt != tfunc { 2079 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc) 2080 } 2081 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int() 2082 if i != want { 2083 t.Errorf("Variadic Method returned %d; want %d", i, want) 2084 } 2085 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int() 2086 if i != want { 2087 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want) 2088 } 2089 2090 f := v.Interface().(func(...Point) int) 2091 i = int64(f(points[0], points[1], points[2])) 2092 if i != want { 2093 t.Errorf("Variadic Method Interface returned %d; want %d", i, want) 2094 } 2095 i = int64(f(points...)) 2096 if i != want { 2097 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want) 2098 } 2099 } 2100 2101 // Reflect version of $GOROOT/test/method5.go 2102 2103 // Concrete types implementing M method. 2104 // Smaller than a word, word-sized, larger than a word. 2105 // Value and pointer receivers. 2106 2107 type Tinter interface { 2108 M(int, byte) (byte, int) 2109 } 2110 2111 type Tsmallv byte 2112 2113 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) } 2114 2115 type Tsmallp byte 2116 2117 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) } 2118 2119 type Twordv uintptr 2120 2121 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) } 2122 2123 type Twordp uintptr 2124 2125 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) } 2126 2127 type Tbigv [2]uintptr 2128 2129 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) } 2130 2131 type Tbigp [2]uintptr 2132 2133 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) } 2134 2135 type tinter interface { 2136 m(int, byte) (byte, int) 2137 } 2138 2139 // Embedding via pointer. 2140 2141 type Tm1 struct { 2142 Tm2 2143 } 2144 2145 type Tm2 struct { 2146 *Tm3 2147 } 2148 2149 type Tm3 struct { 2150 *Tm4 2151 } 2152 2153 type Tm4 struct { 2154 } 2155 2156 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 } 2157 2158 func TestMethod5(t *testing.T) { 2159 CheckF := func(name string, f func(int, byte) (byte, int), inc int) { 2160 b, x := f(1000, 99) 2161 if b != 99 || x != 1000+inc { 2162 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc) 2163 } 2164 } 2165 2166 CheckV := func(name string, i Value, inc int) { 2167 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))}) 2168 b := bx[0].Interface() 2169 x := bx[1].Interface() 2170 if b != byte(99) || x != 1000+inc { 2171 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc) 2172 } 2173 2174 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc) 2175 } 2176 2177 var TinterType = TypeOf(new(Tinter)).Elem() 2178 2179 CheckI := func(name string, i interface{}, inc int) { 2180 v := ValueOf(i) 2181 CheckV(name, v, inc) 2182 CheckV("(i="+name+")", v.Convert(TinterType), inc) 2183 } 2184 2185 sv := Tsmallv(1) 2186 CheckI("sv", sv, 1) 2187 CheckI("&sv", &sv, 1) 2188 2189 sp := Tsmallp(2) 2190 CheckI("&sp", &sp, 2) 2191 2192 wv := Twordv(3) 2193 CheckI("wv", wv, 3) 2194 CheckI("&wv", &wv, 3) 2195 2196 wp := Twordp(4) 2197 CheckI("&wp", &wp, 4) 2198 2199 bv := Tbigv([2]uintptr{5, 6}) 2200 CheckI("bv", bv, 11) 2201 CheckI("&bv", &bv, 11) 2202 2203 bp := Tbigp([2]uintptr{7, 8}) 2204 CheckI("&bp", &bp, 15) 2205 2206 t4 := Tm4{} 2207 t3 := Tm3{&t4} 2208 t2 := Tm2{&t3} 2209 t1 := Tm1{t2} 2210 CheckI("t4", t4, 40) 2211 CheckI("&t4", &t4, 40) 2212 CheckI("t3", t3, 40) 2213 CheckI("&t3", &t3, 40) 2214 CheckI("t2", t2, 40) 2215 CheckI("&t2", &t2, 40) 2216 CheckI("t1", t1, 40) 2217 CheckI("&t1", &t1, 40) 2218 2219 var tnil Tinter 2220 vnil := ValueOf(&tnil).Elem() 2221 shouldPanic(func() { vnil.Method(0) }) 2222 } 2223 2224 func TestInterfaceSet(t *testing.T) { 2225 p := &Point{3, 4} 2226 2227 var s struct { 2228 I interface{} 2229 P interface { 2230 Dist(int) int 2231 } 2232 } 2233 sv := ValueOf(&s).Elem() 2234 sv.Field(0).Set(ValueOf(p)) 2235 if q := s.I.(*Point); q != p { 2236 t.Errorf("i: have %p want %p", q, p) 2237 } 2238 2239 pv := sv.Field(1) 2240 pv.Set(ValueOf(p)) 2241 if q := s.P.(*Point); q != p { 2242 t.Errorf("i: have %p want %p", q, p) 2243 } 2244 2245 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int() 2246 if i != 250 { 2247 t.Errorf("Interface Method returned %d; want 250", i) 2248 } 2249 } 2250 2251 type T1 struct { 2252 a string 2253 int 2254 } 2255 2256 func TestAnonymousFields(t *testing.T) { 2257 var field StructField 2258 var ok bool 2259 var t1 T1 2260 type1 := TypeOf(t1) 2261 if field, ok = type1.FieldByName("int"); !ok { 2262 t.Fatal("no field 'int'") 2263 } 2264 if field.Index[0] != 1 { 2265 t.Error("field index should be 1; is", field.Index) 2266 } 2267 } 2268 2269 type FTest struct { 2270 s interface{} 2271 name string 2272 index []int 2273 value int 2274 } 2275 2276 type D1 struct { 2277 d int 2278 } 2279 type D2 struct { 2280 d int 2281 } 2282 2283 type S0 struct { 2284 A, B, C int 2285 D1 2286 D2 2287 } 2288 2289 type S1 struct { 2290 B int 2291 S0 2292 } 2293 2294 type S2 struct { 2295 A int 2296 *S1 2297 } 2298 2299 type S1x struct { 2300 S1 2301 } 2302 2303 type S1y struct { 2304 S1 2305 } 2306 2307 type S3 struct { 2308 S1x 2309 S2 2310 D, E int 2311 *S1y 2312 } 2313 2314 type S4 struct { 2315 *S4 2316 A int 2317 } 2318 2319 // The X in S6 and S7 annihilate, but they also block the X in S8.S9. 2320 type S5 struct { 2321 S6 2322 S7 2323 S8 2324 } 2325 2326 type S6 struct { 2327 X int 2328 } 2329 2330 type S7 S6 2331 2332 type S8 struct { 2333 S9 2334 } 2335 2336 type S9 struct { 2337 X int 2338 Y int 2339 } 2340 2341 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. 2342 type S10 struct { 2343 S11 2344 S12 2345 S13 2346 } 2347 2348 type S11 struct { 2349 S6 2350 } 2351 2352 type S12 struct { 2353 S6 2354 } 2355 2356 type S13 struct { 2357 S8 2358 } 2359 2360 // The X in S15.S11.S1 and S16.S11.S1 annihilate. 2361 type S14 struct { 2362 S15 2363 S16 2364 } 2365 2366 type S15 struct { 2367 S11 2368 } 2369 2370 type S16 struct { 2371 S11 2372 } 2373 2374 var fieldTests = []FTest{ 2375 {struct{}{}, "", nil, 0}, 2376 {struct{}{}, "Foo", nil, 0}, 2377 {S0{A: 'a'}, "A", []int{0}, 'a'}, 2378 {S0{}, "D", nil, 0}, 2379 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'}, 2380 {S1{B: 'b'}, "B", []int{0}, 'b'}, 2381 {S1{}, "S0", []int{1}, 0}, 2382 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'}, 2383 {S2{A: 'a'}, "A", []int{0}, 'a'}, 2384 {S2{}, "S1", []int{1}, 0}, 2385 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'}, 2386 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'}, 2387 {S2{}, "D", nil, 0}, 2388 {S3{}, "S1", nil, 0}, 2389 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'}, 2390 {S3{}, "B", nil, 0}, 2391 {S3{D: 'd'}, "D", []int{2}, 0}, 2392 {S3{E: 'e'}, "E", []int{3}, 'e'}, 2393 {S4{A: 'a'}, "A", []int{1}, 'a'}, 2394 {S4{}, "B", nil, 0}, 2395 {S5{}, "X", nil, 0}, 2396 {S5{}, "Y", []int{2, 0, 1}, 0}, 2397 {S10{}, "X", nil, 0}, 2398 {S10{}, "Y", []int{2, 0, 0, 1}, 0}, 2399 {S14{}, "X", nil, 0}, 2400 } 2401 2402 func TestFieldByIndex(t *testing.T) { 2403 for _, test := range fieldTests { 2404 s := TypeOf(test.s) 2405 f := s.FieldByIndex(test.index) 2406 if f.Name != "" { 2407 if test.index != nil { 2408 if f.Name != test.name { 2409 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name) 2410 } 2411 } else { 2412 t.Errorf("%s.%s found", s.Name(), f.Name) 2413 } 2414 } else if len(test.index) > 0 { 2415 t.Errorf("%s.%s not found", s.Name(), test.name) 2416 } 2417 2418 if test.value != 0 { 2419 v := ValueOf(test.s).FieldByIndex(test.index) 2420 if v.IsValid() { 2421 if x, ok := v.Interface().(int); ok { 2422 if x != test.value { 2423 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value) 2424 } 2425 } else { 2426 t.Errorf("%s%v value not an int", s.Name(), test.index) 2427 } 2428 } else { 2429 t.Errorf("%s%v value not found", s.Name(), test.index) 2430 } 2431 } 2432 } 2433 } 2434 2435 func TestFieldByName(t *testing.T) { 2436 for _, test := range fieldTests { 2437 s := TypeOf(test.s) 2438 f, found := s.FieldByName(test.name) 2439 if found { 2440 if test.index != nil { 2441 // Verify field depth and index. 2442 if len(f.Index) != len(test.index) { 2443 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) 2444 } else { 2445 for i, x := range f.Index { 2446 if x != test.index[i] { 2447 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i]) 2448 } 2449 } 2450 } 2451 } else { 2452 t.Errorf("%s.%s found", s.Name(), f.Name) 2453 } 2454 } else if len(test.index) > 0 { 2455 t.Errorf("%s.%s not found", s.Name(), test.name) 2456 } 2457 2458 if test.value != 0 { 2459 v := ValueOf(test.s).FieldByName(test.name) 2460 if v.IsValid() { 2461 if x, ok := v.Interface().(int); ok { 2462 if x != test.value { 2463 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value) 2464 } 2465 } else { 2466 t.Errorf("%s.%s value not an int", s.Name(), test.name) 2467 } 2468 } else { 2469 t.Errorf("%s.%s value not found", s.Name(), test.name) 2470 } 2471 } 2472 } 2473 } 2474 2475 func TestImportPath(t *testing.T) { 2476 tests := []struct { 2477 t Type 2478 path string 2479 }{ 2480 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"}, 2481 {TypeOf(int(0)), ""}, 2482 {TypeOf(int8(0)), ""}, 2483 {TypeOf(int16(0)), ""}, 2484 {TypeOf(int32(0)), ""}, 2485 {TypeOf(int64(0)), ""}, 2486 {TypeOf(uint(0)), ""}, 2487 {TypeOf(uint8(0)), ""}, 2488 {TypeOf(uint16(0)), ""}, 2489 {TypeOf(uint32(0)), ""}, 2490 {TypeOf(uint64(0)), ""}, 2491 {TypeOf(uintptr(0)), ""}, 2492 {TypeOf(float32(0)), ""}, 2493 {TypeOf(float64(0)), ""}, 2494 {TypeOf(complex64(0)), ""}, 2495 {TypeOf(complex128(0)), ""}, 2496 {TypeOf(byte(0)), ""}, 2497 {TypeOf(rune(0)), ""}, 2498 {TypeOf([]byte(nil)), ""}, 2499 {TypeOf([]rune(nil)), ""}, 2500 {TypeOf(string("")), ""}, 2501 {TypeOf((*interface{})(nil)).Elem(), ""}, 2502 {TypeOf((*byte)(nil)), ""}, 2503 {TypeOf((*rune)(nil)), ""}, 2504 {TypeOf((*int64)(nil)), ""}, 2505 {TypeOf(map[string]int{}), ""}, 2506 {TypeOf((*error)(nil)).Elem(), ""}, 2507 {TypeOf((*Point)(nil)), ""}, 2508 {TypeOf((*Point)(nil)).Elem(), "reflect_test"}, 2509 } 2510 for _, test := range tests { 2511 if path := test.t.PkgPath(); path != test.path { 2512 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path) 2513 } 2514 } 2515 } 2516 2517 func TestFieldPkgPath(t *testing.T) { 2518 type x int 2519 typ := TypeOf(struct { 2520 Exported string 2521 unexported string 2522 OtherPkgFields 2523 int // issue 21702 2524 *x // issue 21122 2525 }{}) 2526 2527 type pkgpathTest struct { 2528 index []int 2529 pkgPath string 2530 anonymous bool 2531 } 2532 2533 checkPkgPath := func(name string, s []pkgpathTest) { 2534 for _, test := range s { 2535 f := typ.FieldByIndex(test.index) 2536 if got, want := f.PkgPath, test.pkgPath; got != want { 2537 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want) 2538 } 2539 if got, want := f.Anonymous, test.anonymous; got != want { 2540 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want) 2541 } 2542 } 2543 } 2544 2545 checkPkgPath("testStruct", []pkgpathTest{ 2546 {[]int{0}, "", false}, // Exported 2547 {[]int{1}, "reflect_test", false}, // unexported 2548 {[]int{2}, "", true}, // OtherPkgFields 2549 {[]int{2, 0}, "", false}, // OtherExported 2550 {[]int{2, 1}, "reflect", false}, // otherUnexported 2551 {[]int{3}, "reflect_test", true}, // int 2552 {[]int{4}, "reflect_test", true}, // *x 2553 }) 2554 2555 type localOtherPkgFields OtherPkgFields 2556 typ = TypeOf(localOtherPkgFields{}) 2557 checkPkgPath("localOtherPkgFields", []pkgpathTest{ 2558 {[]int{0}, "", false}, // OtherExported 2559 {[]int{1}, "reflect", false}, // otherUnexported 2560 }) 2561 } 2562 2563 func TestVariadicType(t *testing.T) { 2564 // Test example from Type documentation. 2565 var f func(x int, y ...float64) 2566 typ := TypeOf(f) 2567 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) { 2568 sl := typ.In(1) 2569 if sl.Kind() == Slice { 2570 if sl.Elem() == TypeOf(0.0) { 2571 // ok 2572 return 2573 } 2574 } 2575 } 2576 2577 // Failed 2578 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64") 2579 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn()) 2580 for i := 0; i < typ.NumIn(); i++ { 2581 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i)) 2582 } 2583 t.Error(s) 2584 } 2585 2586 type inner struct { 2587 x int 2588 } 2589 2590 type outer struct { 2591 y int 2592 inner 2593 } 2594 2595 func (*inner) M() {} 2596 func (*outer) M() {} 2597 2598 func TestNestedMethods(t *testing.T) { 2599 typ := TypeOf((*outer)(nil)) 2600 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() { 2601 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M) 2602 for i := 0; i < typ.NumMethod(); i++ { 2603 m := typ.Method(i) 2604 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer()) 2605 } 2606 } 2607 } 2608 2609 type unexp struct{} 2610 2611 func (*unexp) f() (int32, int8) { return 7, 7 } 2612 func (*unexp) g() (int64, int8) { return 8, 8 } 2613 2614 type unexpI interface { 2615 f() (int32, int8) 2616 } 2617 2618 var unexpi unexpI = new(unexp) 2619 2620 func TestUnexportedMethods(t *testing.T) { 2621 typ := TypeOf(unexpi) 2622 2623 if got := typ.NumMethod(); got != 0 { 2624 t.Errorf("NumMethod=%d, want 0 satisfied methods", got) 2625 } 2626 } 2627 2628 type InnerInt struct { 2629 X int 2630 } 2631 2632 type OuterInt struct { 2633 Y int 2634 InnerInt 2635 } 2636 2637 func (i *InnerInt) M() int { 2638 return i.X 2639 } 2640 2641 func TestEmbeddedMethods(t *testing.T) { 2642 typ := TypeOf((*OuterInt)(nil)) 2643 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() { 2644 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M) 2645 for i := 0; i < typ.NumMethod(); i++ { 2646 m := typ.Method(i) 2647 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer()) 2648 } 2649 } 2650 2651 i := &InnerInt{3} 2652 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 { 2653 t.Errorf("i.M() = %d, want 3", v) 2654 } 2655 2656 o := &OuterInt{1, InnerInt{2}} 2657 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 { 2658 t.Errorf("i.M() = %d, want 2", v) 2659 } 2660 2661 f := (*OuterInt).M 2662 if v := f(o); v != 2 { 2663 t.Errorf("f(o) = %d, want 2", v) 2664 } 2665 } 2666 2667 type FuncDDD func(...interface{}) error 2668 2669 func (f FuncDDD) M() {} 2670 2671 func TestNumMethodOnDDD(t *testing.T) { 2672 rv := ValueOf((FuncDDD)(nil)) 2673 if n := rv.NumMethod(); n != 1 { 2674 t.Fatalf("NumMethod()=%d, want 1", n) 2675 } 2676 } 2677 2678 func TestPtrTo(t *testing.T) { 2679 // This block of code means that the ptrToThis field of the 2680 // reflect data for *unsafe.Pointer is non zero, see 2681 // https://golang.org/issue/19003 2682 var x unsafe.Pointer 2683 var y = &x 2684 var z = &y 2685 2686 var i int 2687 2688 typ := TypeOf(z) 2689 for i = 0; i < 100; i++ { 2690 typ = PtrTo(typ) 2691 } 2692 for i = 0; i < 100; i++ { 2693 typ = typ.Elem() 2694 } 2695 if typ != TypeOf(z) { 2696 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z)) 2697 } 2698 } 2699 2700 func TestPtrToGC(t *testing.T) { 2701 type T *uintptr 2702 tt := TypeOf(T(nil)) 2703 pt := PtrTo(tt) 2704 const n = 100 2705 var x []interface{} 2706 for i := 0; i < n; i++ { 2707 v := New(pt) 2708 p := new(*uintptr) 2709 *p = new(uintptr) 2710 **p = uintptr(i) 2711 v.Elem().Set(ValueOf(p).Convert(pt)) 2712 x = append(x, v.Interface()) 2713 } 2714 runtime.GC() 2715 2716 for i, xi := range x { 2717 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr) 2718 if k != uintptr(i) { 2719 t.Errorf("lost x[%d] = %d, want %d", i, k, i) 2720 } 2721 } 2722 } 2723 2724 func BenchmarkPtrTo(b *testing.B) { 2725 // Construct a type with a zero ptrToThis. 2726 type T struct{ int } 2727 t := SliceOf(TypeOf(T{})) 2728 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis") 2729 if !ptrToThis.IsValid() { 2730 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t) 2731 } 2732 if ptrToThis.Int() != 0 { 2733 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t) 2734 } 2735 b.ResetTimer() 2736 2737 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on 2738 // every call. 2739 b.RunParallel(func(pb *testing.PB) { 2740 for pb.Next() { 2741 PtrTo(t) 2742 } 2743 }) 2744 } 2745 2746 func TestAddr(t *testing.T) { 2747 var p struct { 2748 X, Y int 2749 } 2750 2751 v := ValueOf(&p) 2752 v = v.Elem() 2753 v = v.Addr() 2754 v = v.Elem() 2755 v = v.Field(0) 2756 v.SetInt(2) 2757 if p.X != 2 { 2758 t.Errorf("Addr.Elem.Set failed to set value") 2759 } 2760 2761 // Again but take address of the ValueOf value. 2762 // Exercises generation of PtrTypes not present in the binary. 2763 q := &p 2764 v = ValueOf(&q).Elem() 2765 v = v.Addr() 2766 v = v.Elem() 2767 v = v.Elem() 2768 v = v.Addr() 2769 v = v.Elem() 2770 v = v.Field(0) 2771 v.SetInt(3) 2772 if p.X != 3 { 2773 t.Errorf("Addr.Elem.Set failed to set value") 2774 } 2775 2776 // Starting without pointer we should get changed value 2777 // in interface. 2778 qq := p 2779 v = ValueOf(&qq).Elem() 2780 v0 := v 2781 v = v.Addr() 2782 v = v.Elem() 2783 v = v.Field(0) 2784 v.SetInt(4) 2785 if p.X != 3 { // should be unchanged from last time 2786 t.Errorf("somehow value Set changed original p") 2787 } 2788 p = v0.Interface().(struct { 2789 X, Y int 2790 }) 2791 if p.X != 4 { 2792 t.Errorf("Addr.Elem.Set valued to set value in top value") 2793 } 2794 2795 // Verify that taking the address of a type gives us a pointer 2796 // which we can convert back using the usual interface 2797 // notation. 2798 var s struct { 2799 B *bool 2800 } 2801 ps := ValueOf(&s).Elem().Field(0).Addr().Interface() 2802 *(ps.(**bool)) = new(bool) 2803 if s.B == nil { 2804 t.Errorf("Addr.Interface direct assignment failed") 2805 } 2806 } 2807 2808 func noAlloc(t *testing.T, n int, f func(int)) { 2809 if testing.Short() { 2810 t.Skip("skipping malloc count in short mode") 2811 } 2812 if runtime.GOMAXPROCS(0) > 1 { 2813 t.Skip("skipping; GOMAXPROCS>1") 2814 } 2815 i := -1 2816 allocs := testing.AllocsPerRun(n, func() { 2817 f(i) 2818 i++ 2819 }) 2820 if allocs > 0 { 2821 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs) 2822 } 2823 } 2824 2825 func TestAllocations(t *testing.T) { 2826 noAlloc(t, 100, func(j int) { 2827 var i interface{} 2828 var v Value 2829 2830 // We can uncomment this when compiler escape analysis 2831 // is good enough to see that the integer assigned to i 2832 // does not escape and therefore need not be allocated. 2833 // 2834 // i = 42 + j 2835 // v = ValueOf(i) 2836 // if int(v.Int()) != 42+j { 2837 // panic("wrong int") 2838 // } 2839 2840 i = func(j int) int { return j } 2841 v = ValueOf(i) 2842 if v.Interface().(func(int) int)(j) != j { 2843 panic("wrong result") 2844 } 2845 }) 2846 } 2847 2848 func TestSmallNegativeInt(t *testing.T) { 2849 i := int16(-1) 2850 v := ValueOf(i) 2851 if v.Int() != -1 { 2852 t.Errorf("int16(-1).Int() returned %v", v.Int()) 2853 } 2854 } 2855 2856 func TestIndex(t *testing.T) { 2857 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8} 2858 v := ValueOf(xs).Index(3).Interface().(byte) 2859 if v != xs[3] { 2860 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3]) 2861 } 2862 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80} 2863 v = ValueOf(xa).Index(2).Interface().(byte) 2864 if v != xa[2] { 2865 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2]) 2866 } 2867 s := "0123456789" 2868 v = ValueOf(s).Index(3).Interface().(byte) 2869 if v != s[3] { 2870 t.Errorf("s.Index(3) = %v; expected %v", v, s[3]) 2871 } 2872 } 2873 2874 func TestSlice(t *testing.T) { 2875 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2876 v := ValueOf(xs).Slice(3, 5).Interface().([]int) 2877 if len(v) != 2 { 2878 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v)) 2879 } 2880 if cap(v) != 5 { 2881 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v)) 2882 } 2883 if !DeepEqual(v[0:5], xs[3:]) { 2884 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5]) 2885 } 2886 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2887 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int) 2888 if len(v) != 3 { 2889 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v)) 2890 } 2891 if cap(v) != 6 { 2892 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v)) 2893 } 2894 if !DeepEqual(v[0:6], xa[2:]) { 2895 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6]) 2896 } 2897 s := "0123456789" 2898 vs := ValueOf(s).Slice(3, 5).Interface().(string) 2899 if vs != s[3:5] { 2900 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5]) 2901 } 2902 2903 rv := ValueOf(&xs).Elem() 2904 rv = rv.Slice(3, 4) 2905 ptr2 := rv.Pointer() 2906 rv = rv.Slice(5, 5) 2907 ptr3 := rv.Pointer() 2908 if ptr3 != ptr2 { 2909 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2) 2910 } 2911 } 2912 2913 func TestSlice3(t *testing.T) { 2914 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2915 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int) 2916 if len(v) != 2 { 2917 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v)) 2918 } 2919 if cap(v) != 4 { 2920 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v)) 2921 } 2922 if !DeepEqual(v[0:4], xs[3:7:7]) { 2923 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4]) 2924 } 2925 rv := ValueOf(&xs).Elem() 2926 shouldPanic(func() { rv.Slice3(1, 2, 1) }) 2927 shouldPanic(func() { rv.Slice3(1, 1, 11) }) 2928 shouldPanic(func() { rv.Slice3(2, 2, 1) }) 2929 2930 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2931 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int) 2932 if len(v) != 3 { 2933 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v)) 2934 } 2935 if cap(v) != 4 { 2936 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v)) 2937 } 2938 if !DeepEqual(v[0:4], xa[2:6:6]) { 2939 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4]) 2940 } 2941 rv = ValueOf(&xa).Elem() 2942 shouldPanic(func() { rv.Slice3(1, 2, 1) }) 2943 shouldPanic(func() { rv.Slice3(1, 1, 11) }) 2944 shouldPanic(func() { rv.Slice3(2, 2, 1) }) 2945 2946 s := "hello world" 2947 rv = ValueOf(&s).Elem() 2948 shouldPanic(func() { rv.Slice3(1, 2, 3) }) 2949 2950 rv = ValueOf(&xs).Elem() 2951 rv = rv.Slice3(3, 5, 7) 2952 ptr2 := rv.Pointer() 2953 rv = rv.Slice3(4, 4, 4) 2954 ptr3 := rv.Pointer() 2955 if ptr3 != ptr2 { 2956 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2) 2957 } 2958 } 2959 2960 func TestSetLenCap(t *testing.T) { 2961 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2962 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2963 2964 vs := ValueOf(&xs).Elem() 2965 shouldPanic(func() { vs.SetLen(10) }) 2966 shouldPanic(func() { vs.SetCap(10) }) 2967 shouldPanic(func() { vs.SetLen(-1) }) 2968 shouldPanic(func() { vs.SetCap(-1) }) 2969 shouldPanic(func() { vs.SetCap(6) }) // smaller than len 2970 vs.SetLen(5) 2971 if len(xs) != 5 || cap(xs) != 8 { 2972 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs)) 2973 } 2974 vs.SetCap(6) 2975 if len(xs) != 5 || cap(xs) != 6 { 2976 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs)) 2977 } 2978 vs.SetCap(5) 2979 if len(xs) != 5 || cap(xs) != 5 { 2980 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs)) 2981 } 2982 shouldPanic(func() { vs.SetCap(4) }) // smaller than len 2983 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap 2984 2985 va := ValueOf(&xa).Elem() 2986 shouldPanic(func() { va.SetLen(8) }) 2987 shouldPanic(func() { va.SetCap(8) }) 2988 } 2989 2990 func TestVariadic(t *testing.T) { 2991 var b bytes.Buffer 2992 V := ValueOf 2993 2994 b.Reset() 2995 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)}) 2996 if b.String() != "hello, 42 world" { 2997 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world") 2998 } 2999 3000 b.Reset() 3001 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})}) 3002 if b.String() != "hello, 42 world" { 3003 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world") 3004 } 3005 } 3006 3007 func TestFuncArg(t *testing.T) { 3008 f1 := func(i int, f func(int) int) int { return f(i) } 3009 f2 := func(i int) int { return i + 1 } 3010 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)}) 3011 if r[0].Int() != 101 { 3012 t.Errorf("function returned %d, want 101", r[0].Int()) 3013 } 3014 } 3015 3016 func TestStructArg(t *testing.T) { 3017 type padded struct { 3018 B string 3019 C int32 3020 } 3021 var ( 3022 gotA padded 3023 gotB uint32 3024 wantA = padded{"3", 4} 3025 wantB = uint32(5) 3026 ) 3027 f := func(a padded, b uint32) { 3028 gotA, gotB = a, b 3029 } 3030 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)}) 3031 if gotA != wantA || gotB != wantB { 3032 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB) 3033 } 3034 } 3035 3036 var tagGetTests = []struct { 3037 Tag StructTag 3038 Key string 3039 Value string 3040 }{ 3041 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`}, 3042 {`protobuf:"PB(1,2)"`, `foo`, ``}, 3043 {`protobuf:"PB(1,2)"`, `rotobuf`, ``}, 3044 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`}, 3045 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`}, 3046 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"}, 3047 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"}, 3048 } 3049 3050 func TestTagGet(t *testing.T) { 3051 for _, tt := range tagGetTests { 3052 if v := tt.Tag.Get(tt.Key); v != tt.Value { 3053 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value) 3054 } 3055 } 3056 } 3057 3058 func TestBytes(t *testing.T) { 3059 type B []byte 3060 x := B{1, 2, 3, 4} 3061 y := ValueOf(x).Bytes() 3062 if !bytes.Equal(x, y) { 3063 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) 3064 } 3065 if &x[0] != &y[0] { 3066 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) 3067 } 3068 } 3069 3070 func TestSetBytes(t *testing.T) { 3071 type B []byte 3072 var x B 3073 y := []byte{1, 2, 3, 4} 3074 ValueOf(&x).Elem().SetBytes(y) 3075 if !bytes.Equal(x, y) { 3076 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) 3077 } 3078 if &x[0] != &y[0] { 3079 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) 3080 } 3081 } 3082 3083 type Private struct { 3084 x int 3085 y **int 3086 Z int 3087 } 3088 3089 func (p *Private) m() { 3090 } 3091 3092 type private struct { 3093 Z int 3094 z int 3095 S string 3096 A [1]Private 3097 T []Private 3098 } 3099 3100 func (p *private) P() { 3101 } 3102 3103 type Public struct { 3104 X int 3105 Y **int 3106 private 3107 } 3108 3109 func (p *Public) M() { 3110 } 3111 3112 func TestUnexported(t *testing.T) { 3113 var pub Public 3114 pub.S = "S" 3115 pub.T = pub.A[:] 3116 v := ValueOf(&pub) 3117 isValid(v.Elem().Field(0)) 3118 isValid(v.Elem().Field(1)) 3119 isValid(v.Elem().Field(2)) 3120 isValid(v.Elem().FieldByName("X")) 3121 isValid(v.Elem().FieldByName("Y")) 3122 isValid(v.Elem().FieldByName("Z")) 3123 isValid(v.Type().Method(0).Func) 3124 m, _ := v.Type().MethodByName("M") 3125 isValid(m.Func) 3126 m, _ = v.Type().MethodByName("P") 3127 isValid(m.Func) 3128 isNonNil(v.Elem().Field(0).Interface()) 3129 isNonNil(v.Elem().Field(1).Interface()) 3130 isNonNil(v.Elem().Field(2).Field(2).Index(0)) 3131 isNonNil(v.Elem().FieldByName("X").Interface()) 3132 isNonNil(v.Elem().FieldByName("Y").Interface()) 3133 isNonNil(v.Elem().FieldByName("Z").Interface()) 3134 isNonNil(v.Elem().FieldByName("S").Index(0).Interface()) 3135 isNonNil(v.Type().Method(0).Func.Interface()) 3136 m, _ = v.Type().MethodByName("P") 3137 isNonNil(m.Func.Interface()) 3138 3139 var priv Private 3140 v = ValueOf(&priv) 3141 isValid(v.Elem().Field(0)) 3142 isValid(v.Elem().Field(1)) 3143 isValid(v.Elem().FieldByName("x")) 3144 isValid(v.Elem().FieldByName("y")) 3145 shouldPanic(func() { v.Elem().Field(0).Interface() }) 3146 shouldPanic(func() { v.Elem().Field(1).Interface() }) 3147 shouldPanic(func() { v.Elem().FieldByName("x").Interface() }) 3148 shouldPanic(func() { v.Elem().FieldByName("y").Interface() }) 3149 shouldPanic(func() { v.Type().Method(0) }) 3150 } 3151 3152 func TestSetPanic(t *testing.T) { 3153 ok := func(f func()) { f() } 3154 bad := shouldPanic 3155 clear := func(v Value) { v.Set(Zero(v.Type())) } 3156 3157 type t0 struct { 3158 W int 3159 } 3160 3161 type t1 struct { 3162 Y int 3163 t0 3164 } 3165 3166 type T2 struct { 3167 Z int 3168 namedT0 t0 3169 } 3170 3171 type T struct { 3172 X int 3173 t1 3174 T2 3175 NamedT1 t1 3176 NamedT2 T2 3177 namedT1 t1 3178 namedT2 T2 3179 } 3180 3181 // not addressable 3182 v := ValueOf(T{}) 3183 bad(func() { clear(v.Field(0)) }) // .X 3184 bad(func() { clear(v.Field(1)) }) // .t1 3185 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y 3186 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 3187 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W 3188 bad(func() { clear(v.Field(2)) }) // .T2 3189 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z 3190 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 3191 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W 3192 bad(func() { clear(v.Field(3)) }) // .NamedT1 3193 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y 3194 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 3195 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W 3196 bad(func() { clear(v.Field(4)) }) // .NamedT2 3197 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z 3198 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 3199 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W 3200 bad(func() { clear(v.Field(5)) }) // .namedT1 3201 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y 3202 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 3203 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W 3204 bad(func() { clear(v.Field(6)) }) // .namedT2 3205 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z 3206 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 3207 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W 3208 3209 // addressable 3210 v = ValueOf(&T{}).Elem() 3211 ok(func() { clear(v.Field(0)) }) // .X 3212 bad(func() { clear(v.Field(1)) }) // .t1 3213 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y 3214 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 3215 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W 3216 ok(func() { clear(v.Field(2)) }) // .T2 3217 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z 3218 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 3219 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W 3220 ok(func() { clear(v.Field(3)) }) // .NamedT1 3221 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y 3222 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 3223 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W 3224 ok(func() { clear(v.Field(4)) }) // .NamedT2 3225 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z 3226 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 3227 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W 3228 bad(func() { clear(v.Field(5)) }) // .namedT1 3229 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y 3230 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 3231 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W 3232 bad(func() { clear(v.Field(6)) }) // .namedT2 3233 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z 3234 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 3235 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W 3236 } 3237 3238 type timp int 3239 3240 func (t timp) W() {} 3241 func (t timp) Y() {} 3242 func (t timp) w() {} 3243 func (t timp) y() {} 3244 3245 func TestCallPanic(t *testing.T) { 3246 type t0 interface { 3247 W() 3248 w() 3249 } 3250 type T1 interface { 3251 Y() 3252 y() 3253 } 3254 type T2 struct { 3255 T1 3256 t0 3257 } 3258 type T struct { 3259 t0 // 0 3260 T1 // 1 3261 3262 NamedT0 t0 // 2 3263 NamedT1 T1 // 3 3264 NamedT2 T2 // 4 3265 3266 namedT0 t0 // 5 3267 namedT1 T1 // 6 3268 namedT2 T2 // 7 3269 } 3270 ok := func(f func()) { f() } 3271 bad := shouldPanic 3272 call := func(v Value) { v.Call(nil) } 3273 3274 i := timp(0) 3275 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}}) 3276 ok(func() { call(v.Field(0).Method(0)) }) // .t0.W 3277 bad(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W 3278 bad(func() { call(v.Field(0).Method(1)) }) // .t0.w 3279 bad(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w 3280 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y 3281 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y 3282 bad(func() { call(v.Field(1).Method(1)) }) // .T1.y 3283 bad(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y 3284 3285 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W 3286 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W 3287 bad(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w 3288 bad(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w 3289 3290 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y 3291 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y 3292 bad(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y 3293 bad(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y 3294 3295 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y 3296 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W 3297 ok(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W 3298 bad(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W 3299 3300 bad(func() { call(v.Field(5).Method(0)) }) // .namedT0.W 3301 bad(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W 3302 bad(func() { call(v.Field(5).Method(1)) }) // .namedT0.w 3303 bad(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w 3304 3305 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y 3306 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y 3307 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.y 3308 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y 3309 3310 bad(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y 3311 bad(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W 3312 bad(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W 3313 bad(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W 3314 } 3315 3316 func shouldPanic(f func()) { 3317 defer func() { 3318 if recover() == nil { 3319 panic("did not panic") 3320 } 3321 }() 3322 f() 3323 } 3324 3325 func isNonNil(x interface{}) { 3326 if x == nil { 3327 panic("nil interface") 3328 } 3329 } 3330 3331 func isValid(v Value) { 3332 if !v.IsValid() { 3333 panic("zero Value") 3334 } 3335 } 3336 3337 func TestAlias(t *testing.T) { 3338 x := string("hello") 3339 v := ValueOf(&x).Elem() 3340 oldvalue := v.Interface() 3341 v.SetString("world") 3342 newvalue := v.Interface() 3343 3344 if oldvalue != "hello" || newvalue != "world" { 3345 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue) 3346 } 3347 } 3348 3349 var V = ValueOf 3350 3351 func EmptyInterfaceV(x interface{}) Value { 3352 return ValueOf(&x).Elem() 3353 } 3354 3355 func ReaderV(x io.Reader) Value { 3356 return ValueOf(&x).Elem() 3357 } 3358 3359 func ReadWriterV(x io.ReadWriter) Value { 3360 return ValueOf(&x).Elem() 3361 } 3362 3363 type Empty struct{} 3364 type MyStruct struct { 3365 x int `some:"tag"` 3366 } 3367 type MyString string 3368 type MyBytes []byte 3369 type MyRunes []int32 3370 type MyFunc func() 3371 type MyByte byte 3372 3373 var convertTests = []struct { 3374 in Value 3375 out Value 3376 }{ 3377 // numbers 3378 /* 3379 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go 3380 3381 package main 3382 3383 import "fmt" 3384 3385 var numbers = []string{ 3386 "int8", "uint8", "int16", "uint16", 3387 "int32", "uint32", "int64", "uint64", 3388 "int", "uint", "uintptr", 3389 "float32", "float64", 3390 } 3391 3392 func main() { 3393 // all pairs but in an unusual order, 3394 // to emit all the int8, uint8 cases 3395 // before n grows too big. 3396 n := 1 3397 for i, f := range numbers { 3398 for _, g := range numbers[i:] { 3399 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n) 3400 n++ 3401 if f != g { 3402 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n) 3403 n++ 3404 } 3405 } 3406 } 3407 } 3408 */ 3409 {V(int8(1)), V(int8(1))}, 3410 {V(int8(2)), V(uint8(2))}, 3411 {V(uint8(3)), V(int8(3))}, 3412 {V(int8(4)), V(int16(4))}, 3413 {V(int16(5)), V(int8(5))}, 3414 {V(int8(6)), V(uint16(6))}, 3415 {V(uint16(7)), V(int8(7))}, 3416 {V(int8(8)), V(int32(8))}, 3417 {V(int32(9)), V(int8(9))}, 3418 {V(int8(10)), V(uint32(10))}, 3419 {V(uint32(11)), V(int8(11))}, 3420 {V(int8(12)), V(int64(12))}, 3421 {V(int64(13)), V(int8(13))}, 3422 {V(int8(14)), V(uint64(14))}, 3423 {V(uint64(15)), V(int8(15))}, 3424 {V(int8(16)), V(int(16))}, 3425 {V(int(17)), V(int8(17))}, 3426 {V(int8(18)), V(uint(18))}, 3427 {V(uint(19)), V(int8(19))}, 3428 {V(int8(20)), V(uintptr(20))}, 3429 {V(uintptr(21)), V(int8(21))}, 3430 {V(int8(22)), V(float32(22))}, 3431 {V(float32(23)), V(int8(23))}, 3432 {V(int8(24)), V(float64(24))}, 3433 {V(float64(25)), V(int8(25))}, 3434 {V(uint8(26)), V(uint8(26))}, 3435 {V(uint8(27)), V(int16(27))}, 3436 {V(int16(28)), V(uint8(28))}, 3437 {V(uint8(29)), V(uint16(29))}, 3438 {V(uint16(30)), V(uint8(30))}, 3439 {V(uint8(31)), V(int32(31))}, 3440 {V(int32(32)), V(uint8(32))}, 3441 {V(uint8(33)), V(uint32(33))}, 3442 {V(uint32(34)), V(uint8(34))}, 3443 {V(uint8(35)), V(int64(35))}, 3444 {V(int64(36)), V(uint8(36))}, 3445 {V(uint8(37)), V(uint64(37))}, 3446 {V(uint64(38)), V(uint8(38))}, 3447 {V(uint8(39)), V(int(39))}, 3448 {V(int(40)), V(uint8(40))}, 3449 {V(uint8(41)), V(uint(41))}, 3450 {V(uint(42)), V(uint8(42))}, 3451 {V(uint8(43)), V(uintptr(43))}, 3452 {V(uintptr(44)), V(uint8(44))}, 3453 {V(uint8(45)), V(float32(45))}, 3454 {V(float32(46)), V(uint8(46))}, 3455 {V(uint8(47)), V(float64(47))}, 3456 {V(float64(48)), V(uint8(48))}, 3457 {V(int16(49)), V(int16(49))}, 3458 {V(int16(50)), V(uint16(50))}, 3459 {V(uint16(51)), V(int16(51))}, 3460 {V(int16(52)), V(int32(52))}, 3461 {V(int32(53)), V(int16(53))}, 3462 {V(int16(54)), V(uint32(54))}, 3463 {V(uint32(55)), V(int16(55))}, 3464 {V(int16(56)), V(int64(56))}, 3465 {V(int64(57)), V(int16(57))}, 3466 {V(int16(58)), V(uint64(58))}, 3467 {V(uint64(59)), V(int16(59))}, 3468 {V(int16(60)), V(int(60))}, 3469 {V(int(61)), V(int16(61))}, 3470 {V(int16(62)), V(uint(62))}, 3471 {V(uint(63)), V(int16(63))}, 3472 {V(int16(64)), V(uintptr(64))}, 3473 {V(uintptr(65)), V(int16(65))}, 3474 {V(int16(66)), V(float32(66))}, 3475 {V(float32(67)), V(int16(67))}, 3476 {V(int16(68)), V(float64(68))}, 3477 {V(float64(69)), V(int16(69))}, 3478 {V(uint16(70)), V(uint16(70))}, 3479 {V(uint16(71)), V(int32(71))}, 3480 {V(int32(72)), V(uint16(72))}, 3481 {V(uint16(73)), V(uint32(73))}, 3482 {V(uint32(74)), V(uint16(74))}, 3483 {V(uint16(75)), V(int64(75))}, 3484 {V(int64(76)), V(uint16(76))}, 3485 {V(uint16(77)), V(uint64(77))}, 3486 {V(uint64(78)), V(uint16(78))}, 3487 {V(uint16(79)), V(int(79))}, 3488 {V(int(80)), V(uint16(80))}, 3489 {V(uint16(81)), V(uint(81))}, 3490 {V(uint(82)), V(uint16(82))}, 3491 {V(uint16(83)), V(uintptr(83))}, 3492 {V(uintptr(84)), V(uint16(84))}, 3493 {V(uint16(85)), V(float32(85))}, 3494 {V(float32(86)), V(uint16(86))}, 3495 {V(uint16(87)), V(float64(87))}, 3496 {V(float64(88)), V(uint16(88))}, 3497 {V(int32(89)), V(int32(89))}, 3498 {V(int32(90)), V(uint32(90))}, 3499 {V(uint32(91)), V(int32(91))}, 3500 {V(int32(92)), V(int64(92))}, 3501 {V(int64(93)), V(int32(93))}, 3502 {V(int32(94)), V(uint64(94))}, 3503 {V(uint64(95)), V(int32(95))}, 3504 {V(int32(96)), V(int(96))}, 3505 {V(int(97)), V(int32(97))}, 3506 {V(int32(98)), V(uint(98))}, 3507 {V(uint(99)), V(int32(99))}, 3508 {V(int32(100)), V(uintptr(100))}, 3509 {V(uintptr(101)), V(int32(101))}, 3510 {V(int32(102)), V(float32(102))}, 3511 {V(float32(103)), V(int32(103))}, 3512 {V(int32(104)), V(float64(104))}, 3513 {V(float64(105)), V(int32(105))}, 3514 {V(uint32(106)), V(uint32(106))}, 3515 {V(uint32(107)), V(int64(107))}, 3516 {V(int64(108)), V(uint32(108))}, 3517 {V(uint32(109)), V(uint64(109))}, 3518 {V(uint64(110)), V(uint32(110))}, 3519 {V(uint32(111)), V(int(111))}, 3520 {V(int(112)), V(uint32(112))}, 3521 {V(uint32(113)), V(uint(113))}, 3522 {V(uint(114)), V(uint32(114))}, 3523 {V(uint32(115)), V(uintptr(115))}, 3524 {V(uintptr(116)), V(uint32(116))}, 3525 {V(uint32(117)), V(float32(117))}, 3526 {V(float32(118)), V(uint32(118))}, 3527 {V(uint32(119)), V(float64(119))}, 3528 {V(float64(120)), V(uint32(120))}, 3529 {V(int64(121)), V(int64(121))}, 3530 {V(int64(122)), V(uint64(122))}, 3531 {V(uint64(123)), V(int64(123))}, 3532 {V(int64(124)), V(int(124))}, 3533 {V(int(125)), V(int64(125))}, 3534 {V(int64(126)), V(uint(126))}, 3535 {V(uint(127)), V(int64(127))}, 3536 {V(int64(128)), V(uintptr(128))}, 3537 {V(uintptr(129)), V(int64(129))}, 3538 {V(int64(130)), V(float32(130))}, 3539 {V(float32(131)), V(int64(131))}, 3540 {V(int64(132)), V(float64(132))}, 3541 {V(float64(133)), V(int64(133))}, 3542 {V(uint64(134)), V(uint64(134))}, 3543 {V(uint64(135)), V(int(135))}, 3544 {V(int(136)), V(uint64(136))}, 3545 {V(uint64(137)), V(uint(137))}, 3546 {V(uint(138)), V(uint64(138))}, 3547 {V(uint64(139)), V(uintptr(139))}, 3548 {V(uintptr(140)), V(uint64(140))}, 3549 {V(uint64(141)), V(float32(141))}, 3550 {V(float32(142)), V(uint64(142))}, 3551 {V(uint64(143)), V(float64(143))}, 3552 {V(float64(144)), V(uint64(144))}, 3553 {V(int(145)), V(int(145))}, 3554 {V(int(146)), V(uint(146))}, 3555 {V(uint(147)), V(int(147))}, 3556 {V(int(148)), V(uintptr(148))}, 3557 {V(uintptr(149)), V(int(149))}, 3558 {V(int(150)), V(float32(150))}, 3559 {V(float32(151)), V(int(151))}, 3560 {V(int(152)), V(float64(152))}, 3561 {V(float64(153)), V(int(153))}, 3562 {V(uint(154)), V(uint(154))}, 3563 {V(uint(155)), V(uintptr(155))}, 3564 {V(uintptr(156)), V(uint(156))}, 3565 {V(uint(157)), V(float32(157))}, 3566 {V(float32(158)), V(uint(158))}, 3567 {V(uint(159)), V(float64(159))}, 3568 {V(float64(160)), V(uint(160))}, 3569 {V(uintptr(161)), V(uintptr(161))}, 3570 {V(uintptr(162)), V(float32(162))}, 3571 {V(float32(163)), V(uintptr(163))}, 3572 {V(uintptr(164)), V(float64(164))}, 3573 {V(float64(165)), V(uintptr(165))}, 3574 {V(float32(166)), V(float32(166))}, 3575 {V(float32(167)), V(float64(167))}, 3576 {V(float64(168)), V(float32(168))}, 3577 {V(float64(169)), V(float64(169))}, 3578 3579 // truncation 3580 {V(float64(1.5)), V(int(1))}, 3581 3582 // complex 3583 {V(complex64(1i)), V(complex64(1i))}, 3584 {V(complex64(2i)), V(complex128(2i))}, 3585 {V(complex128(3i)), V(complex64(3i))}, 3586 {V(complex128(4i)), V(complex128(4i))}, 3587 3588 // string 3589 {V(string("hello")), V(string("hello"))}, 3590 {V(string("bytes1")), V([]byte("bytes1"))}, 3591 {V([]byte("bytes2")), V(string("bytes2"))}, 3592 {V([]byte("bytes3")), V([]byte("bytes3"))}, 3593 {V(string("runes♝")), V([]rune("runes♝"))}, 3594 {V([]rune("runes♕")), V(string("runes♕"))}, 3595 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, 3596 {V(int('a')), V(string("a"))}, 3597 {V(int8('a')), V(string("a"))}, 3598 {V(int16('a')), V(string("a"))}, 3599 {V(int32('a')), V(string("a"))}, 3600 {V(int64('a')), V(string("a"))}, 3601 {V(uint('a')), V(string("a"))}, 3602 {V(uint8('a')), V(string("a"))}, 3603 {V(uint16('a')), V(string("a"))}, 3604 {V(uint32('a')), V(string("a"))}, 3605 {V(uint64('a')), V(string("a"))}, 3606 {V(uintptr('a')), V(string("a"))}, 3607 {V(int(-1)), V(string("\uFFFD"))}, 3608 {V(int8(-2)), V(string("\uFFFD"))}, 3609 {V(int16(-3)), V(string("\uFFFD"))}, 3610 {V(int32(-4)), V(string("\uFFFD"))}, 3611 {V(int64(-5)), V(string("\uFFFD"))}, 3612 {V(uint(0x110001)), V(string("\uFFFD"))}, 3613 {V(uint32(0x110002)), V(string("\uFFFD"))}, 3614 {V(uint64(0x110003)), V(string("\uFFFD"))}, 3615 {V(uintptr(0x110004)), V(string("\uFFFD"))}, 3616 3617 // named string 3618 {V(MyString("hello")), V(string("hello"))}, 3619 {V(string("hello")), V(MyString("hello"))}, 3620 {V(string("hello")), V(string("hello"))}, 3621 {V(MyString("hello")), V(MyString("hello"))}, 3622 {V(MyString("bytes1")), V([]byte("bytes1"))}, 3623 {V([]byte("bytes2")), V(MyString("bytes2"))}, 3624 {V([]byte("bytes3")), V([]byte("bytes3"))}, 3625 {V(MyString("runes♝")), V([]rune("runes♝"))}, 3626 {V([]rune("runes♕")), V(MyString("runes♕"))}, 3627 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, 3628 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))}, 3629 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, 3630 {V(int('a')), V(MyString("a"))}, 3631 {V(int8('a')), V(MyString("a"))}, 3632 {V(int16('a')), V(MyString("a"))}, 3633 {V(int32('a')), V(MyString("a"))}, 3634 {V(int64('a')), V(MyString("a"))}, 3635 {V(uint('a')), V(MyString("a"))}, 3636 {V(uint8('a')), V(MyString("a"))}, 3637 {V(uint16('a')), V(MyString("a"))}, 3638 {V(uint32('a')), V(MyString("a"))}, 3639 {V(uint64('a')), V(MyString("a"))}, 3640 {V(uintptr('a')), V(MyString("a"))}, 3641 {V(int(-1)), V(MyString("\uFFFD"))}, 3642 {V(int8(-2)), V(MyString("\uFFFD"))}, 3643 {V(int16(-3)), V(MyString("\uFFFD"))}, 3644 {V(int32(-4)), V(MyString("\uFFFD"))}, 3645 {V(int64(-5)), V(MyString("\uFFFD"))}, 3646 {V(uint(0x110001)), V(MyString("\uFFFD"))}, 3647 {V(uint32(0x110002)), V(MyString("\uFFFD"))}, 3648 {V(uint64(0x110003)), V(MyString("\uFFFD"))}, 3649 {V(uintptr(0x110004)), V(MyString("\uFFFD"))}, 3650 3651 // named []byte 3652 {V(string("bytes1")), V(MyBytes("bytes1"))}, 3653 {V(MyBytes("bytes2")), V(string("bytes2"))}, 3654 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))}, 3655 {V(MyString("bytes1")), V(MyBytes("bytes1"))}, 3656 {V(MyBytes("bytes2")), V(MyString("bytes2"))}, 3657 3658 // named []rune 3659 {V(string("runes♝")), V(MyRunes("runes♝"))}, 3660 {V(MyRunes("runes♕")), V(string("runes♕"))}, 3661 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))}, 3662 {V(MyString("runes♝")), V(MyRunes("runes♝"))}, 3663 {V(MyRunes("runes♕")), V(MyString("runes♕"))}, 3664 3665 // named types and equal underlying types 3666 {V(new(int)), V(new(integer))}, 3667 {V(new(integer)), V(new(int))}, 3668 {V(Empty{}), V(struct{}{})}, 3669 {V(new(Empty)), V(new(struct{}))}, 3670 {V(struct{}{}), V(Empty{})}, 3671 {V(new(struct{})), V(new(Empty))}, 3672 {V(Empty{}), V(Empty{})}, 3673 {V(MyBytes{}), V([]byte{})}, 3674 {V([]byte{}), V(MyBytes{})}, 3675 {V((func())(nil)), V(MyFunc(nil))}, 3676 {V((MyFunc)(nil)), V((func())(nil))}, 3677 3678 // structs with different tags 3679 {V(struct { 3680 x int `some:"foo"` 3681 }{}), V(struct { 3682 x int `some:"bar"` 3683 }{})}, 3684 3685 {V(struct { 3686 x int `some:"bar"` 3687 }{}), V(struct { 3688 x int `some:"foo"` 3689 }{})}, 3690 3691 {V(MyStruct{}), V(struct { 3692 x int `some:"foo"` 3693 }{})}, 3694 3695 {V(struct { 3696 x int `some:"foo"` 3697 }{}), V(MyStruct{})}, 3698 3699 {V(MyStruct{}), V(struct { 3700 x int `some:"bar"` 3701 }{})}, 3702 3703 {V(struct { 3704 x int `some:"bar"` 3705 }{}), V(MyStruct{})}, 3706 3707 // can convert *byte and *MyByte 3708 {V((*byte)(nil)), V((*MyByte)(nil))}, 3709 {V((*MyByte)(nil)), V((*byte)(nil))}, 3710 3711 // cannot convert mismatched array sizes 3712 {V([2]byte{}), V([2]byte{})}, 3713 {V([3]byte{}), V([3]byte{})}, 3714 3715 // cannot convert other instances 3716 {V((**byte)(nil)), V((**byte)(nil))}, 3717 {V((**MyByte)(nil)), V((**MyByte)(nil))}, 3718 {V((chan byte)(nil)), V((chan byte)(nil))}, 3719 {V((chan MyByte)(nil)), V((chan MyByte)(nil))}, 3720 {V(([]byte)(nil)), V(([]byte)(nil))}, 3721 {V(([]MyByte)(nil)), V(([]MyByte)(nil))}, 3722 {V((map[int]byte)(nil)), V((map[int]byte)(nil))}, 3723 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))}, 3724 {V((map[byte]int)(nil)), V((map[byte]int)(nil))}, 3725 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))}, 3726 {V([2]byte{}), V([2]byte{})}, 3727 {V([2]MyByte{}), V([2]MyByte{})}, 3728 3729 // other 3730 {V((***int)(nil)), V((***int)(nil))}, 3731 {V((***byte)(nil)), V((***byte)(nil))}, 3732 {V((***int32)(nil)), V((***int32)(nil))}, 3733 {V((***int64)(nil)), V((***int64)(nil))}, 3734 {V((chan int)(nil)), V((<-chan int)(nil))}, 3735 {V((chan int)(nil)), V((chan<- int)(nil))}, 3736 {V((chan string)(nil)), V((<-chan string)(nil))}, 3737 {V((chan string)(nil)), V((chan<- string)(nil))}, 3738 {V((chan byte)(nil)), V((chan byte)(nil))}, 3739 {V((chan MyByte)(nil)), V((chan MyByte)(nil))}, 3740 {V((map[int]bool)(nil)), V((map[int]bool)(nil))}, 3741 {V((map[int]byte)(nil)), V((map[int]byte)(nil))}, 3742 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))}, 3743 {V([]uint(nil)), V([]uint(nil))}, 3744 {V([]int(nil)), V([]int(nil))}, 3745 {V(new(interface{})), V(new(interface{}))}, 3746 {V(new(io.Reader)), V(new(io.Reader))}, 3747 {V(new(io.Writer)), V(new(io.Writer))}, 3748 3749 // interfaces 3750 {V(int(1)), EmptyInterfaceV(int(1))}, 3751 {V(string("hello")), EmptyInterfaceV(string("hello"))}, 3752 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, 3753 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, 3754 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))}, 3755 } 3756 3757 func TestConvert(t *testing.T) { 3758 canConvert := map[[2]Type]bool{} 3759 all := map[Type]bool{} 3760 3761 for _, tt := range convertTests { 3762 t1 := tt.in.Type() 3763 if !t1.ConvertibleTo(t1) { 3764 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1) 3765 continue 3766 } 3767 3768 t2 := tt.out.Type() 3769 if !t1.ConvertibleTo(t2) { 3770 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2) 3771 continue 3772 } 3773 3774 all[t1] = true 3775 all[t2] = true 3776 canConvert[[2]Type{t1, t2}] = true 3777 3778 // vout1 represents the in value converted to the in type. 3779 v1 := tt.in 3780 vout1 := v1.Convert(t1) 3781 out1 := vout1.Interface() 3782 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) { 3783 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface()) 3784 } 3785 3786 // vout2 represents the in value converted to the out type. 3787 vout2 := v1.Convert(t2) 3788 out2 := vout2.Interface() 3789 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) { 3790 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface()) 3791 } 3792 3793 // vout3 represents a new value of the out type, set to vout2. This makes 3794 // sure the converted value vout2 is really usable as a regular value. 3795 vout3 := New(t2).Elem() 3796 vout3.Set(vout2) 3797 out3 := vout3.Interface() 3798 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) { 3799 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface()) 3800 } 3801 3802 if IsRO(v1) { 3803 t.Errorf("table entry %v is RO, should not be", v1) 3804 } 3805 if IsRO(vout1) { 3806 t.Errorf("self-conversion output %v is RO, should not be", vout1) 3807 } 3808 if IsRO(vout2) { 3809 t.Errorf("conversion output %v is RO, should not be", vout2) 3810 } 3811 if IsRO(vout3) { 3812 t.Errorf("set(conversion output) %v is RO, should not be", vout3) 3813 } 3814 if !IsRO(MakeRO(v1).Convert(t1)) { 3815 t.Errorf("RO self-conversion output %v is not RO, should be", v1) 3816 } 3817 if !IsRO(MakeRO(v1).Convert(t2)) { 3818 t.Errorf("RO conversion output %v is not RO, should be", v1) 3819 } 3820 } 3821 3822 // Assume that of all the types we saw during the tests, 3823 // if there wasn't an explicit entry for a conversion between 3824 // a pair of types, then it's not to be allowed. This checks for 3825 // things like 'int64' converting to '*int'. 3826 for t1 := range all { 3827 for t2 := range all { 3828 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0 3829 if ok := t1.ConvertibleTo(t2); ok != expectOK { 3830 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK) 3831 } 3832 } 3833 } 3834 } 3835 3836 type ComparableStruct struct { 3837 X int 3838 } 3839 3840 type NonComparableStruct struct { 3841 X int 3842 Y map[string]int 3843 } 3844 3845 var comparableTests = []struct { 3846 typ Type 3847 ok bool 3848 }{ 3849 {TypeOf(1), true}, 3850 {TypeOf("hello"), true}, 3851 {TypeOf(new(byte)), true}, 3852 {TypeOf((func())(nil)), false}, 3853 {TypeOf([]byte{}), false}, 3854 {TypeOf(map[string]int{}), false}, 3855 {TypeOf(make(chan int)), true}, 3856 {TypeOf(1.5), true}, 3857 {TypeOf(false), true}, 3858 {TypeOf(1i), true}, 3859 {TypeOf(ComparableStruct{}), true}, 3860 {TypeOf(NonComparableStruct{}), false}, 3861 {TypeOf([10]map[string]int{}), false}, 3862 {TypeOf([10]string{}), true}, 3863 {TypeOf(new(interface{})).Elem(), true}, 3864 } 3865 3866 func TestComparable(t *testing.T) { 3867 for _, tt := range comparableTests { 3868 if ok := tt.typ.Comparable(); ok != tt.ok { 3869 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok) 3870 } 3871 } 3872 } 3873 3874 func TestOverflow(t *testing.T) { 3875 if ovf := V(float64(0)).OverflowFloat(1e300); ovf { 3876 t.Errorf("%v wrongly overflows float64", 1e300) 3877 } 3878 3879 maxFloat32 := float64((1<<24 - 1) << (127 - 23)) 3880 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf { 3881 t.Errorf("%v wrongly overflows float32", maxFloat32) 3882 } 3883 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52)) 3884 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf { 3885 t.Errorf("%v should overflow float32", ovfFloat32) 3886 } 3887 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf { 3888 t.Errorf("%v should overflow float32", -ovfFloat32) 3889 } 3890 3891 maxInt32 := int64(0x7fffffff) 3892 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf { 3893 t.Errorf("%v wrongly overflows int32", maxInt32) 3894 } 3895 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf { 3896 t.Errorf("%v wrongly overflows int32", -int64(1)<<31) 3897 } 3898 ovfInt32 := int64(1 << 31) 3899 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf { 3900 t.Errorf("%v should overflow int32", ovfInt32) 3901 } 3902 3903 maxUint32 := uint64(0xffffffff) 3904 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf { 3905 t.Errorf("%v wrongly overflows uint32", maxUint32) 3906 } 3907 ovfUint32 := uint64(1 << 32) 3908 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf { 3909 t.Errorf("%v should overflow uint32", ovfUint32) 3910 } 3911 } 3912 3913 func checkSameType(t *testing.T, x, y interface{}) { 3914 if TypeOf(x) != TypeOf(y) { 3915 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y)) 3916 } 3917 } 3918 3919 func TestArrayOf(t *testing.T) { 3920 // check construction and use of type not in binary 3921 tests := []struct { 3922 n int 3923 value func(i int) interface{} 3924 comparable bool 3925 want string 3926 }{ 3927 { 3928 n: 0, 3929 value: func(i int) interface{} { type Tint int; return Tint(i) }, 3930 comparable: true, 3931 want: "[]", 3932 }, 3933 { 3934 n: 10, 3935 value: func(i int) interface{} { type Tint int; return Tint(i) }, 3936 comparable: true, 3937 want: "[0 1 2 3 4 5 6 7 8 9]", 3938 }, 3939 { 3940 n: 10, 3941 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) }, 3942 comparable: true, 3943 want: "[0 1 2 3 4 5 6 7 8 9]", 3944 }, 3945 { 3946 n: 10, 3947 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) }, 3948 comparable: true, 3949 want: "[0 1 2 3 4 5 6 7 8 9]", 3950 }, 3951 { 3952 n: 10, 3953 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} }, 3954 comparable: true, 3955 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]", 3956 }, 3957 { 3958 n: 10, 3959 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} }, 3960 comparable: false, 3961 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", 3962 }, 3963 { 3964 n: 10, 3965 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} }, 3966 comparable: true, 3967 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", 3968 }, 3969 { 3970 n: 10, 3971 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} }, 3972 comparable: true, 3973 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", 3974 }, 3975 { 3976 n: 10, 3977 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} }, 3978 comparable: false, 3979 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", 3980 }, 3981 { 3982 n: 10, 3983 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} }, 3984 comparable: true, 3985 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", 3986 }, 3987 { 3988 n: 10, 3989 value: func(i int) interface{} { 3990 type TstructUV struct { 3991 U int 3992 V float64 3993 } 3994 return TstructUV{i, float64(i)} 3995 }, 3996 comparable: true, 3997 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", 3998 }, 3999 } 4000 4001 for _, table := range tests { 4002 at := ArrayOf(table.n, TypeOf(table.value(0))) 4003 v := New(at).Elem() 4004 vok := New(at).Elem() 4005 vnot := New(at).Elem() 4006 for i := 0; i < v.Len(); i++ { 4007 v.Index(i).Set(ValueOf(table.value(i))) 4008 vok.Index(i).Set(ValueOf(table.value(i))) 4009 j := i 4010 if i+1 == v.Len() { 4011 j = i + 1 4012 } 4013 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element 4014 } 4015 s := fmt.Sprint(v.Interface()) 4016 if s != table.want { 4017 t.Errorf("constructed array = %s, want %s", s, table.want) 4018 } 4019 4020 if table.comparable != at.Comparable() { 4021 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable) 4022 } 4023 if table.comparable { 4024 if table.n > 0 { 4025 if DeepEqual(vnot.Interface(), v.Interface()) { 4026 t.Errorf( 4027 "arrays (%#v) compare ok (but should not)", 4028 v.Interface(), 4029 ) 4030 } 4031 } 4032 if !DeepEqual(vok.Interface(), v.Interface()) { 4033 t.Errorf( 4034 "arrays (%#v) compare NOT-ok (but should)", 4035 v.Interface(), 4036 ) 4037 } 4038 } 4039 } 4040 4041 // check that type already in binary is found 4042 type T int 4043 checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{}) 4044 } 4045 4046 func TestArrayOfGC(t *testing.T) { 4047 type T *uintptr 4048 tt := TypeOf(T(nil)) 4049 const n = 100 4050 var x []interface{} 4051 for i := 0; i < n; i++ { 4052 v := New(ArrayOf(n, tt)).Elem() 4053 for j := 0; j < v.Len(); j++ { 4054 p := new(uintptr) 4055 *p = uintptr(i*n + j) 4056 v.Index(j).Set(ValueOf(p).Convert(tt)) 4057 } 4058 x = append(x, v.Interface()) 4059 } 4060 runtime.GC() 4061 4062 for i, xi := range x { 4063 v := ValueOf(xi) 4064 for j := 0; j < v.Len(); j++ { 4065 k := v.Index(j).Elem().Interface() 4066 if k != uintptr(i*n+j) { 4067 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 4068 } 4069 } 4070 } 4071 } 4072 4073 func TestArrayOfAlg(t *testing.T) { 4074 at := ArrayOf(6, TypeOf(byte(0))) 4075 v1 := New(at).Elem() 4076 v2 := New(at).Elem() 4077 if v1.Interface() != v1.Interface() { 4078 t.Errorf("constructed array %v not equal to itself", v1.Interface()) 4079 } 4080 v1.Index(5).Set(ValueOf(byte(1))) 4081 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { 4082 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) 4083 } 4084 4085 at = ArrayOf(6, TypeOf([]int(nil))) 4086 v1 = New(at).Elem() 4087 shouldPanic(func() { _ = v1.Interface() == v1.Interface() }) 4088 } 4089 4090 func TestArrayOfGenericAlg(t *testing.T) { 4091 at1 := ArrayOf(5, TypeOf(string(""))) 4092 at := ArrayOf(6, at1) 4093 v1 := New(at).Elem() 4094 v2 := New(at).Elem() 4095 if v1.Interface() != v1.Interface() { 4096 t.Errorf("constructed array %v not equal to itself", v1.Interface()) 4097 } 4098 4099 v1.Index(0).Index(0).Set(ValueOf("abc")) 4100 v2.Index(0).Index(0).Set(ValueOf("efg")) 4101 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { 4102 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) 4103 } 4104 4105 v1.Index(0).Index(0).Set(ValueOf("abc")) 4106 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3])) 4107 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 { 4108 t.Errorf("constructed arrays %v and %v should be equal", i1, i2) 4109 } 4110 4111 // Test hash 4112 m := MakeMap(MapOf(at, TypeOf(int(0)))) 4113 m.SetMapIndex(v1, ValueOf(1)) 4114 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4115 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2) 4116 } 4117 } 4118 4119 func TestArrayOfDirectIface(t *testing.T) { 4120 { 4121 type T [1]*byte 4122 i1 := Zero(TypeOf(T{})).Interface() 4123 v1 := ValueOf(&i1).Elem() 4124 p1 := v1.InterfaceData()[1] 4125 4126 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface() 4127 v2 := ValueOf(&i2).Elem() 4128 p2 := v2.InterfaceData()[1] 4129 4130 if p1 != 0 { 4131 t.Errorf("got p1=%v. want=%v", p1, nil) 4132 } 4133 4134 if p2 != 0 { 4135 t.Errorf("got p2=%v. want=%v", p2, nil) 4136 } 4137 } 4138 { 4139 type T [0]*byte 4140 i1 := Zero(TypeOf(T{})).Interface() 4141 v1 := ValueOf(&i1).Elem() 4142 p1 := v1.InterfaceData()[1] 4143 4144 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface() 4145 v2 := ValueOf(&i2).Elem() 4146 p2 := v2.InterfaceData()[1] 4147 4148 if p1 == 0 { 4149 t.Errorf("got p1=%v. want=not-%v", p1, nil) 4150 } 4151 4152 if p2 == 0 { 4153 t.Errorf("got p2=%v. want=not-%v", p2, nil) 4154 } 4155 } 4156 } 4157 4158 func TestSliceOf(t *testing.T) { 4159 // check construction and use of type not in binary 4160 type T int 4161 st := SliceOf(TypeOf(T(1))) 4162 if got, want := st.String(), "[]reflect_test.T"; got != want { 4163 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want) 4164 } 4165 v := MakeSlice(st, 10, 10) 4166 runtime.GC() 4167 for i := 0; i < v.Len(); i++ { 4168 v.Index(i).Set(ValueOf(T(i))) 4169 runtime.GC() 4170 } 4171 s := fmt.Sprint(v.Interface()) 4172 want := "[0 1 2 3 4 5 6 7 8 9]" 4173 if s != want { 4174 t.Errorf("constructed slice = %s, want %s", s, want) 4175 } 4176 4177 // check that type already in binary is found 4178 type T1 int 4179 checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{}) 4180 } 4181 4182 func TestSliceOverflow(t *testing.T) { 4183 // check that MakeSlice panics when size of slice overflows uint 4184 const S = 1e6 4185 s := uint(S) 4186 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1 4187 if l*s >= s { 4188 t.Fatal("slice size does not overflow") 4189 } 4190 var x [S]byte 4191 st := SliceOf(TypeOf(x)) 4192 defer func() { 4193 err := recover() 4194 if err == nil { 4195 t.Fatal("slice overflow does not panic") 4196 } 4197 }() 4198 MakeSlice(st, int(l), int(l)) 4199 } 4200 4201 func TestSliceOfGC(t *testing.T) { 4202 type T *uintptr 4203 tt := TypeOf(T(nil)) 4204 st := SliceOf(tt) 4205 const n = 100 4206 var x []interface{} 4207 for i := 0; i < n; i++ { 4208 v := MakeSlice(st, n, n) 4209 for j := 0; j < v.Len(); j++ { 4210 p := new(uintptr) 4211 *p = uintptr(i*n + j) 4212 v.Index(j).Set(ValueOf(p).Convert(tt)) 4213 } 4214 x = append(x, v.Interface()) 4215 } 4216 runtime.GC() 4217 4218 for i, xi := range x { 4219 v := ValueOf(xi) 4220 for j := 0; j < v.Len(); j++ { 4221 k := v.Index(j).Elem().Interface() 4222 if k != uintptr(i*n+j) { 4223 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 4224 } 4225 } 4226 } 4227 } 4228 4229 func TestStructOfFieldName(t *testing.T) { 4230 // invalid field name "1nvalid" 4231 shouldPanic(func() { 4232 StructOf([]StructField{ 4233 StructField{Name: "valid", Type: TypeOf("")}, 4234 StructField{Name: "1nvalid", Type: TypeOf("")}, 4235 }) 4236 }) 4237 4238 // invalid field name "+" 4239 shouldPanic(func() { 4240 StructOf([]StructField{ 4241 StructField{Name: "val1d", Type: TypeOf("")}, 4242 StructField{Name: "+", Type: TypeOf("")}, 4243 }) 4244 }) 4245 4246 // no field name 4247 shouldPanic(func() { 4248 StructOf([]StructField{ 4249 StructField{Name: "", Type: TypeOf("")}, 4250 }) 4251 }) 4252 4253 // verify creation of a struct with valid struct fields 4254 validFields := []StructField{ 4255 StructField{ 4256 Name: "φ", 4257 Type: TypeOf(""), 4258 }, 4259 StructField{ 4260 Name: "ValidName", 4261 Type: TypeOf(""), 4262 }, 4263 StructField{ 4264 Name: "Val1dNam5", 4265 Type: TypeOf(""), 4266 }, 4267 } 4268 4269 validStruct := StructOf(validFields) 4270 4271 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }` 4272 if got, want := validStruct.String(), structStr; got != want { 4273 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want) 4274 } 4275 } 4276 4277 func TestStructOf(t *testing.T) { 4278 // check construction and use of type not in binary 4279 fields := []StructField{ 4280 StructField{ 4281 Name: "S", 4282 Tag: "s", 4283 Type: TypeOf(""), 4284 }, 4285 StructField{ 4286 Name: "X", 4287 Tag: "x", 4288 Type: TypeOf(byte(0)), 4289 }, 4290 StructField{ 4291 Name: "Y", 4292 Type: TypeOf(uint64(0)), 4293 }, 4294 StructField{ 4295 Name: "Z", 4296 Type: TypeOf([3]uint16{}), 4297 }, 4298 } 4299 4300 st := StructOf(fields) 4301 v := New(st).Elem() 4302 runtime.GC() 4303 v.FieldByName("X").Set(ValueOf(byte(2))) 4304 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1))) 4305 runtime.GC() 4306 4307 s := fmt.Sprint(v.Interface()) 4308 want := `{ 1 0 [0 0 0]}` 4309 if s != want { 4310 t.Errorf("constructed struct = %s, want %s", s, want) 4311 } 4312 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }` 4313 if got, want := st.String(), stStr; got != want { 4314 t.Errorf("StructOf(fields).String()=%q, want %q", got, want) 4315 } 4316 4317 // check the size, alignment and field offsets 4318 stt := TypeOf(struct { 4319 String string 4320 X byte 4321 Y uint64 4322 Z [3]uint16 4323 }{}) 4324 if st.Size() != stt.Size() { 4325 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size()) 4326 } 4327 if st.Align() != stt.Align() { 4328 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align()) 4329 } 4330 if st.FieldAlign() != stt.FieldAlign() { 4331 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign()) 4332 } 4333 for i := 0; i < st.NumField(); i++ { 4334 o1 := st.Field(i).Offset 4335 o2 := stt.Field(i).Offset 4336 if o1 != o2 { 4337 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2) 4338 } 4339 } 4340 4341 // Check size and alignment with a trailing zero-sized field. 4342 st = StructOf([]StructField{ 4343 { 4344 Name: "F1", 4345 Type: TypeOf(byte(0)), 4346 }, 4347 { 4348 Name: "F2", 4349 Type: TypeOf([0]*byte{}), 4350 }, 4351 }) 4352 stt = TypeOf(struct { 4353 G1 byte 4354 G2 [0]*byte 4355 }{}) 4356 if st.Size() != stt.Size() { 4357 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size()) 4358 } 4359 if st.Align() != stt.Align() { 4360 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align()) 4361 } 4362 if st.FieldAlign() != stt.FieldAlign() { 4363 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign()) 4364 } 4365 for i := 0; i < st.NumField(); i++ { 4366 o1 := st.Field(i).Offset 4367 o2 := stt.Field(i).Offset 4368 if o1 != o2 { 4369 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2) 4370 } 4371 } 4372 4373 // check duplicate names 4374 shouldPanic(func() { 4375 StructOf([]StructField{ 4376 StructField{Name: "string", Type: TypeOf("")}, 4377 StructField{Name: "string", Type: TypeOf("")}, 4378 }) 4379 }) 4380 shouldPanic(func() { 4381 StructOf([]StructField{ 4382 StructField{Type: TypeOf("")}, 4383 StructField{Name: "string", Type: TypeOf("")}, 4384 }) 4385 }) 4386 shouldPanic(func() { 4387 StructOf([]StructField{ 4388 StructField{Type: TypeOf("")}, 4389 StructField{Type: TypeOf("")}, 4390 }) 4391 }) 4392 // check that type already in binary is found 4393 checkSameType(t, Zero(StructOf(fields[2:3])).Interface(), struct{ Y uint64 }{}) 4394 } 4395 4396 func TestStructOfExportRules(t *testing.T) { 4397 type S1 struct{} 4398 type s2 struct{} 4399 type ΦType struct{} 4400 type φType struct{} 4401 4402 testPanic := func(i int, mustPanic bool, f func()) { 4403 defer func() { 4404 err := recover() 4405 if err == nil && mustPanic { 4406 t.Errorf("test-%d did not panic", i) 4407 } 4408 if err != nil && !mustPanic { 4409 t.Errorf("test-%d panicked: %v\n", i, err) 4410 } 4411 }() 4412 f() 4413 } 4414 4415 tests := []struct { 4416 field StructField 4417 mustPanic bool 4418 exported bool 4419 }{ 4420 { 4421 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})}, 4422 exported: true, 4423 }, 4424 { 4425 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))}, 4426 exported: true, 4427 }, 4428 { 4429 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})}, 4430 mustPanic: true, 4431 }, 4432 { 4433 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))}, 4434 mustPanic: true, 4435 }, 4436 { 4437 field: StructField{Name: "Name", Type: nil, PkgPath: ""}, 4438 mustPanic: true, 4439 }, 4440 { 4441 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""}, 4442 mustPanic: true, 4443 }, 4444 { 4445 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"}, 4446 mustPanic: true, 4447 }, 4448 { 4449 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, 4450 mustPanic: true, 4451 }, 4452 { 4453 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"}, 4454 mustPanic: true, 4455 }, 4456 { 4457 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, 4458 mustPanic: true, 4459 }, 4460 { 4461 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"}, 4462 mustPanic: true, 4463 }, 4464 { 4465 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"}, 4466 mustPanic: true, 4467 }, 4468 { 4469 field: StructField{Name: "S", Type: TypeOf(S1{})}, 4470 mustPanic: false, 4471 exported: true, 4472 }, 4473 { 4474 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))}, 4475 exported: true, 4476 }, 4477 { 4478 field: StructField{Name: "S", Type: TypeOf(s2{})}, 4479 exported: true, 4480 }, 4481 { 4482 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))}, 4483 exported: true, 4484 }, 4485 { 4486 field: StructField{Name: "s", Type: TypeOf(S1{})}, 4487 mustPanic: true, 4488 }, 4489 { 4490 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))}, 4491 mustPanic: true, 4492 }, 4493 { 4494 field: StructField{Name: "s", Type: TypeOf(s2{})}, 4495 mustPanic: true, 4496 }, 4497 { 4498 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))}, 4499 mustPanic: true, 4500 }, 4501 { 4502 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"}, 4503 mustPanic: true, // TODO(sbinet): creating a name with a package path 4504 }, 4505 { 4506 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, 4507 mustPanic: true, // TODO(sbinet): creating a name with a package path 4508 }, 4509 { 4510 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"}, 4511 mustPanic: true, // TODO(sbinet): creating a name with a package path 4512 }, 4513 { 4514 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, 4515 mustPanic: true, // TODO(sbinet): creating a name with a package path 4516 }, 4517 { 4518 field: StructField{Name: "", Type: TypeOf(ΦType{})}, 4519 mustPanic: true, 4520 }, 4521 { 4522 field: StructField{Name: "", Type: TypeOf(φType{})}, 4523 mustPanic: true, 4524 }, 4525 { 4526 field: StructField{Name: "Φ", Type: TypeOf(0)}, 4527 exported: true, 4528 }, 4529 { 4530 field: StructField{Name: "φ", Type: TypeOf(0)}, 4531 exported: false, 4532 }, 4533 } 4534 4535 for i, test := range tests { 4536 testPanic(i, test.mustPanic, func() { 4537 typ := StructOf([]StructField{test.field}) 4538 if typ == nil { 4539 t.Errorf("test-%d: error creating struct type", i) 4540 return 4541 } 4542 field := typ.Field(0) 4543 n := field.Name 4544 if n == "" { 4545 panic("field.Name must not be empty") 4546 } 4547 exported := isExported(n) 4548 if exported != test.exported { 4549 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported) 4550 } 4551 }) 4552 } 4553 } 4554 4555 // isExported reports whether name is an exported Go symbol 4556 // (that is, whether it begins with an upper-case letter). 4557 // 4558 func isExported(name string) bool { 4559 ch, _ := utf8.DecodeRuneInString(name) 4560 return unicode.IsUpper(ch) 4561 } 4562 4563 func TestStructOfGC(t *testing.T) { 4564 type T *uintptr 4565 tt := TypeOf(T(nil)) 4566 fields := []StructField{ 4567 {Name: "X", Type: tt}, 4568 {Name: "Y", Type: tt}, 4569 } 4570 st := StructOf(fields) 4571 4572 const n = 10000 4573 var x []interface{} 4574 for i := 0; i < n; i++ { 4575 v := New(st).Elem() 4576 for j := 0; j < v.NumField(); j++ { 4577 p := new(uintptr) 4578 *p = uintptr(i*n + j) 4579 v.Field(j).Set(ValueOf(p).Convert(tt)) 4580 } 4581 x = append(x, v.Interface()) 4582 } 4583 runtime.GC() 4584 4585 for i, xi := range x { 4586 v := ValueOf(xi) 4587 for j := 0; j < v.NumField(); j++ { 4588 k := v.Field(j).Elem().Interface() 4589 if k != uintptr(i*n+j) { 4590 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j) 4591 } 4592 } 4593 } 4594 } 4595 4596 func TestStructOfAlg(t *testing.T) { 4597 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}}) 4598 v1 := New(st).Elem() 4599 v2 := New(st).Elem() 4600 if !DeepEqual(v1.Interface(), v1.Interface()) { 4601 t.Errorf("constructed struct %v not equal to itself", v1.Interface()) 4602 } 4603 v1.FieldByName("X").Set(ValueOf(int(1))) 4604 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { 4605 t.Errorf("constructed structs %v and %v should not be equal", i1, i2) 4606 } 4607 4608 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}}) 4609 v1 = New(st).Elem() 4610 shouldPanic(func() { _ = v1.Interface() == v1.Interface() }) 4611 } 4612 4613 func TestStructOfGenericAlg(t *testing.T) { 4614 st1 := StructOf([]StructField{ 4615 {Name: "X", Tag: "x", Type: TypeOf(int64(0))}, 4616 {Name: "Y", Type: TypeOf(string(""))}, 4617 }) 4618 st := StructOf([]StructField{ 4619 {Name: "S0", Type: st1}, 4620 {Name: "S1", Type: st1}, 4621 }) 4622 4623 tests := []struct { 4624 rt Type 4625 idx []int 4626 }{ 4627 { 4628 rt: st, 4629 idx: []int{0, 1}, 4630 }, 4631 { 4632 rt: st1, 4633 idx: []int{1}, 4634 }, 4635 { 4636 rt: StructOf( 4637 []StructField{ 4638 {Name: "XX", Type: TypeOf([0]int{})}, 4639 {Name: "YY", Type: TypeOf("")}, 4640 }, 4641 ), 4642 idx: []int{1}, 4643 }, 4644 { 4645 rt: StructOf( 4646 []StructField{ 4647 {Name: "XX", Type: TypeOf([0]int{})}, 4648 {Name: "YY", Type: TypeOf("")}, 4649 {Name: "ZZ", Type: TypeOf([2]int{})}, 4650 }, 4651 ), 4652 idx: []int{1}, 4653 }, 4654 { 4655 rt: StructOf( 4656 []StructField{ 4657 {Name: "XX", Type: TypeOf([1]int{})}, 4658 {Name: "YY", Type: TypeOf("")}, 4659 }, 4660 ), 4661 idx: []int{1}, 4662 }, 4663 { 4664 rt: StructOf( 4665 []StructField{ 4666 {Name: "XX", Type: TypeOf([1]int{})}, 4667 {Name: "YY", Type: TypeOf("")}, 4668 {Name: "ZZ", Type: TypeOf([1]int{})}, 4669 }, 4670 ), 4671 idx: []int{1}, 4672 }, 4673 { 4674 rt: StructOf( 4675 []StructField{ 4676 {Name: "XX", Type: TypeOf([2]int{})}, 4677 {Name: "YY", Type: TypeOf("")}, 4678 {Name: "ZZ", Type: TypeOf([2]int{})}, 4679 }, 4680 ), 4681 idx: []int{1}, 4682 }, 4683 { 4684 rt: StructOf( 4685 []StructField{ 4686 {Name: "XX", Type: TypeOf(int64(0))}, 4687 {Name: "YY", Type: TypeOf(byte(0))}, 4688 {Name: "ZZ", Type: TypeOf("")}, 4689 }, 4690 ), 4691 idx: []int{2}, 4692 }, 4693 { 4694 rt: StructOf( 4695 []StructField{ 4696 {Name: "XX", Type: TypeOf(int64(0))}, 4697 {Name: "YY", Type: TypeOf(int64(0))}, 4698 {Name: "ZZ", Type: TypeOf("")}, 4699 {Name: "AA", Type: TypeOf([1]int64{})}, 4700 }, 4701 ), 4702 idx: []int{2}, 4703 }, 4704 } 4705 4706 for _, table := range tests { 4707 v1 := New(table.rt).Elem() 4708 v2 := New(table.rt).Elem() 4709 4710 if !DeepEqual(v1.Interface(), v1.Interface()) { 4711 t.Errorf("constructed struct %v not equal to itself", v1.Interface()) 4712 } 4713 4714 v1.FieldByIndex(table.idx).Set(ValueOf("abc")) 4715 v2.FieldByIndex(table.idx).Set(ValueOf("def")) 4716 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { 4717 t.Errorf("constructed structs %v and %v should not be equal", i1, i2) 4718 } 4719 4720 abc := "abc" 4721 v1.FieldByIndex(table.idx).Set(ValueOf(abc)) 4722 val := "+" + abc + "-" 4723 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4])) 4724 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { 4725 t.Errorf("constructed structs %v and %v should be equal", i1, i2) 4726 } 4727 4728 // Test hash 4729 m := MakeMap(MapOf(table.rt, TypeOf(int(0)))) 4730 m.SetMapIndex(v1, ValueOf(1)) 4731 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4732 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2) 4733 } 4734 4735 v2.FieldByIndex(table.idx).Set(ValueOf("abc")) 4736 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { 4737 t.Errorf("constructed structs %v and %v should be equal", i1, i2) 4738 } 4739 4740 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4741 t.Errorf("constructed structs %v and %v have different hashes", i1, i2) 4742 } 4743 } 4744 } 4745 4746 func TestStructOfDirectIface(t *testing.T) { 4747 { 4748 type T struct{ X [1]*byte } 4749 i1 := Zero(TypeOf(T{})).Interface() 4750 v1 := ValueOf(&i1).Elem() 4751 p1 := v1.InterfaceData()[1] 4752 4753 i2 := Zero(StructOf([]StructField{ 4754 { 4755 Name: "X", 4756 Type: ArrayOf(1, TypeOf((*int8)(nil))), 4757 }, 4758 })).Interface() 4759 v2 := ValueOf(&i2).Elem() 4760 p2 := v2.InterfaceData()[1] 4761 4762 if p1 != 0 { 4763 t.Errorf("got p1=%v. want=%v", p1, nil) 4764 } 4765 4766 if p2 != 0 { 4767 t.Errorf("got p2=%v. want=%v", p2, nil) 4768 } 4769 } 4770 { 4771 type T struct{ X [0]*byte } 4772 i1 := Zero(TypeOf(T{})).Interface() 4773 v1 := ValueOf(&i1).Elem() 4774 p1 := v1.InterfaceData()[1] 4775 4776 i2 := Zero(StructOf([]StructField{ 4777 { 4778 Name: "X", 4779 Type: ArrayOf(0, TypeOf((*int8)(nil))), 4780 }, 4781 })).Interface() 4782 v2 := ValueOf(&i2).Elem() 4783 p2 := v2.InterfaceData()[1] 4784 4785 if p1 == 0 { 4786 t.Errorf("got p1=%v. want=not-%v", p1, nil) 4787 } 4788 4789 if p2 == 0 { 4790 t.Errorf("got p2=%v. want=not-%v", p2, nil) 4791 } 4792 } 4793 } 4794 4795 type StructI int 4796 4797 func (i StructI) Get() int { return int(i) } 4798 4799 type StructIPtr int 4800 4801 func (i *StructIPtr) Get() int { return int(*i) } 4802 4803 func TestStructOfWithInterface(t *testing.T) { 4804 const want = 42 4805 type Iface interface { 4806 Get() int 4807 } 4808 tests := []struct { 4809 name string 4810 typ Type 4811 val Value 4812 impl bool 4813 }{ 4814 { 4815 name: "StructI", 4816 typ: TypeOf(StructI(want)), 4817 val: ValueOf(StructI(want)), 4818 impl: true, 4819 }, 4820 { 4821 name: "StructI", 4822 typ: PtrTo(TypeOf(StructI(want))), 4823 val: ValueOf(func() interface{} { 4824 v := StructI(want) 4825 return &v 4826 }()), 4827 impl: true, 4828 }, 4829 { 4830 name: "StructIPtr", 4831 typ: PtrTo(TypeOf(StructIPtr(want))), 4832 val: ValueOf(func() interface{} { 4833 v := StructIPtr(want) 4834 return &v 4835 }()), 4836 impl: true, 4837 }, 4838 { 4839 name: "StructIPtr", 4840 typ: TypeOf(StructIPtr(want)), 4841 val: ValueOf(StructIPtr(want)), 4842 impl: false, 4843 }, 4844 // { 4845 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn 4846 // val: ValueOf(StructI(want)), 4847 // impl: true, 4848 // }, 4849 } 4850 4851 for i, table := range tests { 4852 for j := 0; j < 2; j++ { 4853 var fields []StructField 4854 if j == 1 { 4855 fields = append(fields, StructField{ 4856 Name: "Dummy", 4857 PkgPath: "", 4858 Type: TypeOf(int(0)), 4859 }) 4860 } 4861 fields = append(fields, StructField{ 4862 Name: table.name, 4863 Anonymous: true, 4864 PkgPath: "", 4865 Type: table.typ, 4866 }) 4867 4868 // We currently do not correctly implement methods 4869 // for anonymous fields other than the first. 4870 // Therefore, for now, we expect those methods 4871 // to not exist. See issues 15924 and 20824. 4872 // When those issues are fixed, this test of panic 4873 // should be removed. 4874 if j == 1 && table.impl { 4875 func() { 4876 defer func() { 4877 if err := recover(); err == nil { 4878 t.Errorf("test-%d-%d did not panic", i, j) 4879 } 4880 }() 4881 _ = StructOf(fields) 4882 }() 4883 continue 4884 } 4885 4886 rt := StructOf(fields) 4887 rv := New(rt).Elem() 4888 rv.Field(j).Set(table.val) 4889 4890 if _, ok := rv.Interface().(Iface); ok != table.impl { 4891 if table.impl { 4892 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ) 4893 } else { 4894 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ) 4895 } 4896 continue 4897 } 4898 4899 if !table.impl { 4900 continue 4901 } 4902 4903 v := rv.Interface().(Iface).Get() 4904 if v != want { 4905 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want) 4906 } 4907 4908 fct := rv.MethodByName("Get") 4909 out := fct.Call(nil) 4910 if !DeepEqual(out[0].Interface(), want) { 4911 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want) 4912 } 4913 } 4914 } 4915 } 4916 4917 func TestChanOf(t *testing.T) { 4918 // check construction and use of type not in binary 4919 type T string 4920 ct := ChanOf(BothDir, TypeOf(T(""))) 4921 v := MakeChan(ct, 2) 4922 runtime.GC() 4923 v.Send(ValueOf(T("hello"))) 4924 runtime.GC() 4925 v.Send(ValueOf(T("world"))) 4926 runtime.GC() 4927 4928 sv1, _ := v.Recv() 4929 sv2, _ := v.Recv() 4930 s1 := sv1.String() 4931 s2 := sv2.String() 4932 if s1 != "hello" || s2 != "world" { 4933 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world") 4934 } 4935 4936 // check that type already in binary is found 4937 type T1 int 4938 checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil)) 4939 } 4940 4941 func TestChanOfDir(t *testing.T) { 4942 // check construction and use of type not in binary 4943 type T string 4944 crt := ChanOf(RecvDir, TypeOf(T(""))) 4945 cst := ChanOf(SendDir, TypeOf(T(""))) 4946 4947 // check that type already in binary is found 4948 type T1 int 4949 checkSameType(t, Zero(ChanOf(RecvDir, TypeOf(T1(1)))).Interface(), (<-chan T1)(nil)) 4950 checkSameType(t, Zero(ChanOf(SendDir, TypeOf(T1(1)))).Interface(), (chan<- T1)(nil)) 4951 4952 // check String form of ChanDir 4953 if crt.ChanDir().String() != "<-chan" { 4954 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan") 4955 } 4956 if cst.ChanDir().String() != "chan<-" { 4957 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-") 4958 } 4959 } 4960 4961 func TestChanOfGC(t *testing.T) { 4962 done := make(chan bool, 1) 4963 go func() { 4964 select { 4965 case <-done: 4966 case <-time.After(5 * time.Second): 4967 panic("deadlock in TestChanOfGC") 4968 } 4969 }() 4970 4971 defer func() { 4972 done <- true 4973 }() 4974 4975 type T *uintptr 4976 tt := TypeOf(T(nil)) 4977 ct := ChanOf(BothDir, tt) 4978 4979 // NOTE: The garbage collector handles allocated channels specially, 4980 // so we have to save pointers to channels in x; the pointer code will 4981 // use the gc info in the newly constructed chan type. 4982 const n = 100 4983 var x []interface{} 4984 for i := 0; i < n; i++ { 4985 v := MakeChan(ct, n) 4986 for j := 0; j < n; j++ { 4987 p := new(uintptr) 4988 *p = uintptr(i*n + j) 4989 v.Send(ValueOf(p).Convert(tt)) 4990 } 4991 pv := New(ct) 4992 pv.Elem().Set(v) 4993 x = append(x, pv.Interface()) 4994 } 4995 runtime.GC() 4996 4997 for i, xi := range x { 4998 v := ValueOf(xi).Elem() 4999 for j := 0; j < n; j++ { 5000 pv, _ := v.Recv() 5001 k := pv.Elem().Interface() 5002 if k != uintptr(i*n+j) { 5003 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 5004 } 5005 } 5006 } 5007 } 5008 5009 func TestMapOf(t *testing.T) { 5010 // check construction and use of type not in binary 5011 type K string 5012 type V float64 5013 5014 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0)))) 5015 runtime.GC() 5016 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1))) 5017 runtime.GC() 5018 5019 s := fmt.Sprint(v.Interface()) 5020 want := "map[a:1]" 5021 if s != want { 5022 t.Errorf("constructed map = %s, want %s", s, want) 5023 } 5024 5025 // check that type already in binary is found 5026 checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil)) 5027 5028 // check that invalid key type panics 5029 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) }) 5030 } 5031 5032 func TestMapOfGCKeys(t *testing.T) { 5033 type T *uintptr 5034 tt := TypeOf(T(nil)) 5035 mt := MapOf(tt, TypeOf(false)) 5036 5037 // NOTE: The garbage collector handles allocated maps specially, 5038 // so we have to save pointers to maps in x; the pointer code will 5039 // use the gc info in the newly constructed map type. 5040 const n = 100 5041 var x []interface{} 5042 for i := 0; i < n; i++ { 5043 v := MakeMap(mt) 5044 for j := 0; j < n; j++ { 5045 p := new(uintptr) 5046 *p = uintptr(i*n + j) 5047 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true)) 5048 } 5049 pv := New(mt) 5050 pv.Elem().Set(v) 5051 x = append(x, pv.Interface()) 5052 } 5053 runtime.GC() 5054 5055 for i, xi := range x { 5056 v := ValueOf(xi).Elem() 5057 var out []int 5058 for _, kv := range v.MapKeys() { 5059 out = append(out, int(kv.Elem().Interface().(uintptr))) 5060 } 5061 sort.Ints(out) 5062 for j, k := range out { 5063 if k != i*n+j { 5064 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 5065 } 5066 } 5067 } 5068 } 5069 5070 func TestMapOfGCValues(t *testing.T) { 5071 type T *uintptr 5072 tt := TypeOf(T(nil)) 5073 mt := MapOf(TypeOf(1), tt) 5074 5075 // NOTE: The garbage collector handles allocated maps specially, 5076 // so we have to save pointers to maps in x; the pointer code will 5077 // use the gc info in the newly constructed map type. 5078 const n = 100 5079 var x []interface{} 5080 for i := 0; i < n; i++ { 5081 v := MakeMap(mt) 5082 for j := 0; j < n; j++ { 5083 p := new(uintptr) 5084 *p = uintptr(i*n + j) 5085 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt)) 5086 } 5087 pv := New(mt) 5088 pv.Elem().Set(v) 5089 x = append(x, pv.Interface()) 5090 } 5091 runtime.GC() 5092 5093 for i, xi := range x { 5094 v := ValueOf(xi).Elem() 5095 for j := 0; j < n; j++ { 5096 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr) 5097 if k != uintptr(i*n+j) { 5098 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 5099 } 5100 } 5101 } 5102 } 5103 5104 func TestTypelinksSorted(t *testing.T) { 5105 var last string 5106 for i, n := range TypeLinks() { 5107 if n < last { 5108 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i) 5109 } 5110 last = n 5111 } 5112 } 5113 5114 func TestFuncOf(t *testing.T) { 5115 // check construction and use of type not in binary 5116 type K string 5117 type V float64 5118 5119 fn := func(args []Value) []Value { 5120 if len(args) != 1 { 5121 t.Errorf("args == %v, want exactly one arg", args) 5122 } else if args[0].Type() != TypeOf(K("")) { 5123 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K(""))) 5124 } else if args[0].String() != "gopher" { 5125 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher") 5126 } 5127 return []Value{ValueOf(V(3.14))} 5128 } 5129 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn) 5130 5131 outs := v.Call([]Value{ValueOf(K("gopher"))}) 5132 if len(outs) != 1 { 5133 t.Fatalf("v.Call returned %v, want exactly one result", outs) 5134 } else if outs[0].Type() != TypeOf(V(0)) { 5135 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0))) 5136 } 5137 f := outs[0].Float() 5138 if f != 3.14 { 5139 t.Errorf("constructed func returned %f, want %f", f, 3.14) 5140 } 5141 5142 // check that types already in binary are found 5143 type T1 int 5144 testCases := []struct { 5145 in, out []Type 5146 variadic bool 5147 want interface{} 5148 }{ 5149 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)}, 5150 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)}, 5151 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)}, 5152 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)}, 5153 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)}, 5154 } 5155 for _, tt := range testCases { 5156 checkSameType(t, Zero(FuncOf(tt.in, tt.out, tt.variadic)).Interface(), tt.want) 5157 } 5158 5159 // check that variadic requires last element be a slice. 5160 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true) 5161 shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) }) 5162 shouldPanic(func() { FuncOf(nil, nil, true) }) 5163 } 5164 5165 type B1 struct { 5166 X int 5167 Y int 5168 Z int 5169 } 5170 5171 func BenchmarkFieldByName1(b *testing.B) { 5172 t := TypeOf(B1{}) 5173 b.RunParallel(func(pb *testing.PB) { 5174 for pb.Next() { 5175 t.FieldByName("Z") 5176 } 5177 }) 5178 } 5179 5180 func BenchmarkFieldByName2(b *testing.B) { 5181 t := TypeOf(S3{}) 5182 b.RunParallel(func(pb *testing.PB) { 5183 for pb.Next() { 5184 t.FieldByName("B") 5185 } 5186 }) 5187 } 5188 5189 type R0 struct { 5190 *R1 5191 *R2 5192 *R3 5193 *R4 5194 } 5195 5196 type R1 struct { 5197 *R5 5198 *R6 5199 *R7 5200 *R8 5201 } 5202 5203 type R2 R1 5204 type R3 R1 5205 type R4 R1 5206 5207 type R5 struct { 5208 *R9 5209 *R10 5210 *R11 5211 *R12 5212 } 5213 5214 type R6 R5 5215 type R7 R5 5216 type R8 R5 5217 5218 type R9 struct { 5219 *R13 5220 *R14 5221 *R15 5222 *R16 5223 } 5224 5225 type R10 R9 5226 type R11 R9 5227 type R12 R9 5228 5229 type R13 struct { 5230 *R17 5231 *R18 5232 *R19 5233 *R20 5234 } 5235 5236 type R14 R13 5237 type R15 R13 5238 type R16 R13 5239 5240 type R17 struct { 5241 *R21 5242 *R22 5243 *R23 5244 *R24 5245 } 5246 5247 type R18 R17 5248 type R19 R17 5249 type R20 R17 5250 5251 type R21 struct { 5252 X int 5253 } 5254 5255 type R22 R21 5256 type R23 R21 5257 type R24 R21 5258 5259 func TestEmbed(t *testing.T) { 5260 typ := TypeOf(R0{}) 5261 f, ok := typ.FieldByName("X") 5262 if ok { 5263 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index) 5264 } 5265 } 5266 5267 func BenchmarkFieldByName3(b *testing.B) { 5268 t := TypeOf(R0{}) 5269 b.RunParallel(func(pb *testing.PB) { 5270 for pb.Next() { 5271 t.FieldByName("X") 5272 } 5273 }) 5274 } 5275 5276 type S struct { 5277 i1 int64 5278 i2 int64 5279 } 5280 5281 func BenchmarkInterfaceBig(b *testing.B) { 5282 v := ValueOf(S{}) 5283 b.RunParallel(func(pb *testing.PB) { 5284 for pb.Next() { 5285 v.Interface() 5286 } 5287 }) 5288 b.StopTimer() 5289 } 5290 5291 func TestAllocsInterfaceBig(t *testing.T) { 5292 if testing.Short() { 5293 t.Skip("skipping malloc count in short mode") 5294 } 5295 v := ValueOf(S{}) 5296 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { 5297 t.Error("allocs:", allocs) 5298 } 5299 } 5300 5301 func BenchmarkInterfaceSmall(b *testing.B) { 5302 v := ValueOf(int64(0)) 5303 b.RunParallel(func(pb *testing.PB) { 5304 for pb.Next() { 5305 v.Interface() 5306 } 5307 }) 5308 } 5309 5310 func TestAllocsInterfaceSmall(t *testing.T) { 5311 if testing.Short() { 5312 t.Skip("skipping malloc count in short mode") 5313 } 5314 v := ValueOf(int64(0)) 5315 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { 5316 t.Error("allocs:", allocs) 5317 } 5318 } 5319 5320 // An exhaustive is a mechanism for writing exhaustive or stochastic tests. 5321 // The basic usage is: 5322 // 5323 // for x.Next() { 5324 // ... code using x.Maybe() or x.Choice(n) to create test cases ... 5325 // } 5326 // 5327 // Each iteration of the loop returns a different set of results, until all 5328 // possible result sets have been explored. It is okay for different code paths 5329 // to make different method call sequences on x, but there must be no 5330 // other source of non-determinism in the call sequences. 5331 // 5332 // When faced with a new decision, x chooses randomly. Future explorations 5333 // of that path will choose successive values for the result. Thus, stopping 5334 // the loop after a fixed number of iterations gives somewhat stochastic 5335 // testing. 5336 // 5337 // Example: 5338 // 5339 // for x.Next() { 5340 // v := make([]bool, x.Choose(4)) 5341 // for i := range v { 5342 // v[i] = x.Maybe() 5343 // } 5344 // fmt.Println(v) 5345 // } 5346 // 5347 // prints (in some order): 5348 // 5349 // [] 5350 // [false] 5351 // [true] 5352 // [false false] 5353 // [false true] 5354 // ... 5355 // [true true] 5356 // [false false false] 5357 // ... 5358 // [true true true] 5359 // [false false false false] 5360 // ... 5361 // [true true true true] 5362 // 5363 type exhaustive struct { 5364 r *rand.Rand 5365 pos int 5366 last []choice 5367 } 5368 5369 type choice struct { 5370 off int 5371 n int 5372 max int 5373 } 5374 5375 func (x *exhaustive) Next() bool { 5376 if x.r == nil { 5377 x.r = rand.New(rand.NewSource(time.Now().UnixNano())) 5378 } 5379 x.pos = 0 5380 if x.last == nil { 5381 x.last = []choice{} 5382 return true 5383 } 5384 for i := len(x.last) - 1; i >= 0; i-- { 5385 c := &x.last[i] 5386 if c.n+1 < c.max { 5387 c.n++ 5388 x.last = x.last[:i+1] 5389 return true 5390 } 5391 } 5392 return false 5393 } 5394 5395 func (x *exhaustive) Choose(max int) int { 5396 if x.pos >= len(x.last) { 5397 x.last = append(x.last, choice{x.r.Intn(max), 0, max}) 5398 } 5399 c := &x.last[x.pos] 5400 x.pos++ 5401 if c.max != max { 5402 panic("inconsistent use of exhaustive tester") 5403 } 5404 return (c.n + c.off) % max 5405 } 5406 5407 func (x *exhaustive) Maybe() bool { 5408 return x.Choose(2) == 1 5409 } 5410 5411 func GCFunc(args []Value) []Value { 5412 runtime.GC() 5413 return []Value{} 5414 } 5415 5416 func TestReflectFuncTraceback(t *testing.T) { 5417 f := MakeFunc(TypeOf(func() {}), GCFunc) 5418 f.Call([]Value{}) 5419 } 5420 5421 func TestReflectMethodTraceback(t *testing.T) { 5422 p := Point{3, 4} 5423 m := ValueOf(p).MethodByName("GCMethod") 5424 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int() 5425 if i != 8 { 5426 t.Errorf("Call returned %d; want 8", i) 5427 } 5428 } 5429 5430 func TestBigZero(t *testing.T) { 5431 const size = 1 << 10 5432 var v [size]byte 5433 z := Zero(ValueOf(v).Type()).Interface().([size]byte) 5434 for i := 0; i < size; i++ { 5435 if z[i] != 0 { 5436 t.Fatalf("Zero object not all zero, index %d", i) 5437 } 5438 } 5439 } 5440 5441 func TestFieldByIndexNil(t *testing.T) { 5442 type P struct { 5443 F int 5444 } 5445 type T struct { 5446 *P 5447 } 5448 v := ValueOf(T{}) 5449 5450 v.FieldByName("P") // should be fine 5451 5452 defer func() { 5453 if err := recover(); err == nil { 5454 t.Fatalf("no error") 5455 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") { 5456 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err) 5457 } 5458 }() 5459 v.FieldByName("F") // should panic 5460 5461 t.Fatalf("did not panic") 5462 } 5463 5464 // Given 5465 // type Outer struct { 5466 // *Inner 5467 // ... 5468 // } 5469 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner. 5470 // The implementation is logically: 5471 // func (p *Outer) M() { 5472 // (p.Inner).M() 5473 // } 5474 // but since the only change here is the replacement of one pointer receiver with another, 5475 // the actual generated code overwrites the original receiver with the p.Inner pointer and 5476 // then jumps to the M method expecting the *Inner receiver. 5477 // 5478 // During reflect.Value.Call, we create an argument frame and the associated data structures 5479 // to describe it to the garbage collector, populate the frame, call reflect.call to 5480 // run a function call using that frame, and then copy the results back out of the frame. 5481 // The reflect.call function does a memmove of the frame structure onto the 5482 // stack (to set up the inputs), runs the call, and the memmoves the stack back to 5483 // the frame structure (to preserve the outputs). 5484 // 5485 // Originally reflect.call did not distinguish inputs from outputs: both memmoves 5486 // were for the full stack frame. However, in the case where the called function was 5487 // one of these wrappers, the rewritten receiver is almost certainly a different type 5488 // than the original receiver. This is not a problem on the stack, where we use the 5489 // program counter to determine the type information and understand that 5490 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same 5491 // memory word is now an *Inner. But in the statically typed argument frame created 5492 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer 5493 // off the stack into the frame will store an *Inner there, and then if a garbage collection 5494 // happens to scan that argument frame before it is discarded, it will scan the *Inner 5495 // memory as if it were an *Outer. If the two have different memory layouts, the 5496 // collection will interpret the memory incorrectly. 5497 // 5498 // One such possible incorrect interpretation is to treat two arbitrary memory words 5499 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting 5500 // an interface requires dereferencing the itab word, the misinterpretation will try to 5501 // deference Inner.P1, causing a crash during garbage collection. 5502 // 5503 // This came up in a real program in issue 7725. 5504 5505 type Outer struct { 5506 *Inner 5507 R io.Reader 5508 } 5509 5510 type Inner struct { 5511 X *Outer 5512 P1 uintptr 5513 P2 uintptr 5514 } 5515 5516 func (pi *Inner) M() { 5517 // Clear references to pi so that the only way the 5518 // garbage collection will find the pointer is in the 5519 // argument frame, typed as a *Outer. 5520 pi.X.Inner = nil 5521 5522 // Set up an interface value that will cause a crash. 5523 // P1 = 1 is a non-zero, so the interface looks non-nil. 5524 // P2 = pi ensures that the data word points into the 5525 // allocated heap; if not the collection skips the interface 5526 // value as irrelevant, without dereferencing P1. 5527 pi.P1 = 1 5528 pi.P2 = uintptr(unsafe.Pointer(pi)) 5529 } 5530 5531 func TestCallMethodJump(t *testing.T) { 5532 // In reflect.Value.Call, trigger a garbage collection after reflect.call 5533 // returns but before the args frame has been discarded. 5534 // This is a little clumsy but makes the failure repeatable. 5535 *CallGC = true 5536 5537 p := &Outer{Inner: new(Inner)} 5538 p.Inner.X = p 5539 ValueOf(p).Method(0).Call(nil) 5540 5541 // Stop garbage collecting during reflect.call. 5542 *CallGC = false 5543 } 5544 5545 func TestMakeFuncStackCopy(t *testing.T) { 5546 target := func(in []Value) []Value { 5547 runtime.GC() 5548 useStack(16) 5549 return []Value{ValueOf(9)} 5550 } 5551 5552 var concrete func(*int, int) int 5553 fn := MakeFunc(ValueOf(concrete).Type(), target) 5554 ValueOf(&concrete).Elem().Set(fn) 5555 x := concrete(nil, 7) 5556 if x != 9 { 5557 t.Errorf("have %#q want 9", x) 5558 } 5559 } 5560 5561 // use about n KB of stack 5562 func useStack(n int) { 5563 if n == 0 { 5564 return 5565 } 5566 var b [1024]byte // makes frame about 1KB 5567 useStack(n - 1 + int(b[99])) 5568 } 5569 5570 type Impl struct{} 5571 5572 func (Impl) F() {} 5573 5574 func TestValueString(t *testing.T) { 5575 rv := ValueOf(Impl{}) 5576 if rv.String() != "<reflect_test.Impl Value>" { 5577 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>") 5578 } 5579 5580 method := rv.Method(0) 5581 if method.String() != "<func() Value>" { 5582 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>") 5583 } 5584 } 5585 5586 func TestInvalid(t *testing.T) { 5587 // Used to have inconsistency between IsValid() and Kind() != Invalid. 5588 type T struct{ v interface{} } 5589 5590 v := ValueOf(T{}).Field(0) 5591 if v.IsValid() != true || v.Kind() != Interface { 5592 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind()) 5593 } 5594 v = v.Elem() 5595 if v.IsValid() != false || v.Kind() != Invalid { 5596 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind()) 5597 } 5598 } 5599 5600 // Issue 8917. 5601 func TestLargeGCProg(t *testing.T) { 5602 fv := ValueOf(func([256]*byte) {}) 5603 fv.Call([]Value{ValueOf([256]*byte{})}) 5604 } 5605 5606 func fieldIndexRecover(t Type, i int) (recovered interface{}) { 5607 defer func() { 5608 recovered = recover() 5609 }() 5610 5611 t.Field(i) 5612 return 5613 } 5614 5615 // Issue 15046. 5616 func TestTypeFieldOutOfRangePanic(t *testing.T) { 5617 typ := TypeOf(struct{ X int }{10}) 5618 testIndices := [...]struct { 5619 i int 5620 mustPanic bool 5621 }{ 5622 0: {-2, true}, 5623 1: {0, false}, 5624 2: {1, true}, 5625 3: {1 << 10, true}, 5626 } 5627 for i, tt := range testIndices { 5628 recoveredErr := fieldIndexRecover(typ, tt.i) 5629 if tt.mustPanic { 5630 if recoveredErr == nil { 5631 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i) 5632 } 5633 } else { 5634 if recoveredErr != nil { 5635 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr) 5636 } 5637 } 5638 } 5639 } 5640 5641 // Issue 9179. 5642 func TestCallGC(t *testing.T) { 5643 f := func(a, b, c, d, e string) { 5644 } 5645 g := func(in []Value) []Value { 5646 runtime.GC() 5647 return nil 5648 } 5649 typ := ValueOf(f).Type() 5650 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string)) 5651 f2("four", "five5", "six666", "seven77", "eight888") 5652 } 5653 5654 // Issue 18635 (function version). 5655 func TestKeepFuncLive(t *testing.T) { 5656 // Test that we keep makeFuncImpl live as long as it is 5657 // referenced on the stack. 5658 typ := TypeOf(func(i int) {}) 5659 var f, g func(in []Value) []Value 5660 f = func(in []Value) []Value { 5661 clobber() 5662 i := int(in[0].Int()) 5663 if i > 0 { 5664 // We can't use Value.Call here because 5665 // runtime.call* will keep the makeFuncImpl 5666 // alive. However, by converting it to an 5667 // interface value and calling that, 5668 // reflect.callReflect is the only thing that 5669 // can keep the makeFuncImpl live. 5670 // 5671 // Alternate between f and g so that if we do 5672 // reuse the memory prematurely it's more 5673 // likely to get obviously corrupted. 5674 MakeFunc(typ, g).Interface().(func(i int))(i - 1) 5675 } 5676 return nil 5677 } 5678 g = func(in []Value) []Value { 5679 clobber() 5680 i := int(in[0].Int()) 5681 MakeFunc(typ, f).Interface().(func(i int))(i) 5682 return nil 5683 } 5684 MakeFunc(typ, f).Call([]Value{ValueOf(10)}) 5685 } 5686 5687 type UnExportedFirst int 5688 5689 func (i UnExportedFirst) ΦExported() {} 5690 func (i UnExportedFirst) unexported() {} 5691 5692 // Issue 21177 5693 func TestMethodByNameUnExportedFirst(t *testing.T) { 5694 defer func() { 5695 if recover() != nil { 5696 t.Errorf("should not panic") 5697 } 5698 }() 5699 typ := TypeOf(UnExportedFirst(0)) 5700 m, _ := typ.MethodByName("ΦExported") 5701 if m.Name != "ΦExported" { 5702 t.Errorf("got %s, expected ΦExported", m.Name) 5703 } 5704 } 5705 5706 // Issue 18635 (method version). 5707 type KeepMethodLive struct{} 5708 5709 func (k KeepMethodLive) Method1(i int) { 5710 clobber() 5711 if i > 0 { 5712 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1) 5713 } 5714 } 5715 5716 func (k KeepMethodLive) Method2(i int) { 5717 clobber() 5718 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i) 5719 } 5720 5721 func TestKeepMethodLive(t *testing.T) { 5722 // Test that we keep methodValue live as long as it is 5723 // referenced on the stack. 5724 KeepMethodLive{}.Method1(10) 5725 } 5726 5727 // clobber tries to clobber unreachable memory. 5728 func clobber() { 5729 runtime.GC() 5730 for i := 1; i < 32; i++ { 5731 for j := 0; j < 10; j++ { 5732 obj := make([]*byte, i) 5733 sink = obj 5734 } 5735 } 5736 runtime.GC() 5737 } 5738 5739 type funcLayoutTest struct { 5740 rcvr, t Type 5741 size, argsize, retOffset uintptr 5742 stack []byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized) 5743 gc []byte 5744 } 5745 5746 var funcLayoutTests []funcLayoutTest 5747 5748 func init() { 5749 var argAlign uintptr = PtrSize 5750 if runtime.GOARCH == "amd64p32" { 5751 argAlign = 2 * PtrSize 5752 } 5753 roundup := func(x uintptr, a uintptr) uintptr { 5754 return (x + a - 1) / a * a 5755 } 5756 5757 funcLayoutTests = append(funcLayoutTests, 5758 funcLayoutTest{ 5759 nil, 5760 ValueOf(func(a, b string) string { return "" }).Type(), 5761 6 * PtrSize, 5762 4 * PtrSize, 5763 4 * PtrSize, 5764 []byte{1, 0, 1}, 5765 []byte{1, 0, 1, 0, 1}, 5766 }) 5767 5768 var r []byte 5769 if PtrSize == 4 { 5770 r = []byte{0, 0, 0, 1} 5771 } else { 5772 r = []byte{0, 0, 1} 5773 } 5774 funcLayoutTests = append(funcLayoutTests, 5775 funcLayoutTest{ 5776 nil, 5777 ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(), 5778 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign), 5779 roundup(3*4, PtrSize) + PtrSize + 2, 5780 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign), 5781 r, 5782 r, 5783 }) 5784 5785 funcLayoutTests = append(funcLayoutTests, 5786 funcLayoutTest{ 5787 nil, 5788 ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(), 5789 4 * PtrSize, 5790 4 * PtrSize, 5791 4 * PtrSize, 5792 []byte{1, 0, 1, 1}, 5793 []byte{1, 0, 1, 1}, 5794 }) 5795 5796 type S struct { 5797 a, b uintptr 5798 c, d *byte 5799 } 5800 funcLayoutTests = append(funcLayoutTests, 5801 funcLayoutTest{ 5802 nil, 5803 ValueOf(func(a S) {}).Type(), 5804 4 * PtrSize, 5805 4 * PtrSize, 5806 4 * PtrSize, 5807 []byte{0, 0, 1, 1}, 5808 []byte{0, 0, 1, 1}, 5809 }) 5810 5811 funcLayoutTests = append(funcLayoutTests, 5812 funcLayoutTest{ 5813 ValueOf((*byte)(nil)).Type(), 5814 ValueOf(func(a uintptr, b *int) {}).Type(), 5815 roundup(3*PtrSize, argAlign), 5816 3 * PtrSize, 5817 roundup(3*PtrSize, argAlign), 5818 []byte{1, 0, 1}, 5819 []byte{1, 0, 1}, 5820 }) 5821 5822 funcLayoutTests = append(funcLayoutTests, 5823 funcLayoutTest{ 5824 nil, 5825 ValueOf(func(a uintptr) {}).Type(), 5826 roundup(PtrSize, argAlign), 5827 PtrSize, 5828 roundup(PtrSize, argAlign), 5829 []byte{}, 5830 []byte{}, 5831 }) 5832 5833 funcLayoutTests = append(funcLayoutTests, 5834 funcLayoutTest{ 5835 nil, 5836 ValueOf(func() uintptr { return 0 }).Type(), 5837 PtrSize, 5838 0, 5839 0, 5840 []byte{}, 5841 []byte{}, 5842 }) 5843 5844 funcLayoutTests = append(funcLayoutTests, 5845 funcLayoutTest{ 5846 ValueOf(uintptr(0)).Type(), 5847 ValueOf(func(a uintptr) {}).Type(), 5848 2 * PtrSize, 5849 2 * PtrSize, 5850 2 * PtrSize, 5851 []byte{1}, 5852 []byte{1}, 5853 // Note: this one is tricky, as the receiver is not a pointer. But we 5854 // pass the receiver by reference to the autogenerated pointer-receiver 5855 // version of the function. 5856 }) 5857 } 5858 5859 func TestFuncLayout(t *testing.T) { 5860 for _, lt := range funcLayoutTests { 5861 typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr) 5862 if typ.Size() != lt.size { 5863 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size) 5864 } 5865 if argsize != lt.argsize { 5866 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize) 5867 } 5868 if retOffset != lt.retOffset { 5869 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset) 5870 } 5871 if !bytes.Equal(stack, lt.stack) { 5872 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack) 5873 } 5874 if !bytes.Equal(gc, lt.gc) { 5875 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc) 5876 } 5877 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 { 5878 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs) 5879 } 5880 } 5881 } 5882 5883 func verifyGCBits(t *testing.T, typ Type, bits []byte) { 5884 heapBits := GCBits(New(typ).Interface()) 5885 if !bytes.Equal(heapBits, bits) { 5886 t.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ, heapBits, bits) 5887 } 5888 } 5889 5890 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) { 5891 // Creating a slice causes the runtime to repeat a bitmap, 5892 // which exercises a different path from making the compiler 5893 // repeat a bitmap for a small array or executing a repeat in 5894 // a GC program. 5895 val := MakeSlice(typ, 0, cap) 5896 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer())) 5897 heapBits := GCBits(data.Interface()) 5898 // Repeat the bitmap for the slice size, trimming scalars in 5899 // the last element. 5900 bits = rep(cap, bits) 5901 for len(bits) > 2 && bits[len(bits)-1] == 0 { 5902 bits = bits[:len(bits)-1] 5903 } 5904 if len(bits) == 2 && bits[0] == 0 && bits[1] == 0 { 5905 bits = bits[:0] 5906 } 5907 if !bytes.Equal(heapBits, bits) { 5908 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits) 5909 } 5910 } 5911 5912 func TestGCBits(t *testing.T) { 5913 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1}) 5914 5915 // Building blocks for types seen by the compiler (like [2]Xscalar). 5916 // The compiler will create the type structures for the derived types, 5917 // including their GC metadata. 5918 type Xscalar struct{ x uintptr } 5919 type Xptr struct{ x *byte } 5920 type Xptrscalar struct { 5921 *byte 5922 uintptr 5923 } 5924 type Xscalarptr struct { 5925 uintptr 5926 *byte 5927 } 5928 type Xbigptrscalar struct { 5929 _ [100]*byte 5930 _ [100]uintptr 5931 } 5932 5933 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type 5934 { 5935 // Building blocks for types constructed by reflect. 5936 // This code is in a separate block so that code below 5937 // cannot accidentally refer to these. 5938 // The compiler must NOT see types derived from these 5939 // (for example, [2]Scalar must NOT appear in the program), 5940 // or else reflect will use it instead of having to construct one. 5941 // The goal is to test the construction. 5942 type Scalar struct{ x uintptr } 5943 type Ptr struct{ x *byte } 5944 type Ptrscalar struct { 5945 *byte 5946 uintptr 5947 } 5948 type Scalarptr struct { 5949 uintptr 5950 *byte 5951 } 5952 type Bigptrscalar struct { 5953 _ [100]*byte 5954 _ [100]uintptr 5955 } 5956 type Int64 int64 5957 Tscalar = TypeOf(Scalar{}) 5958 Tint64 = TypeOf(Int64(0)) 5959 Tptr = TypeOf(Ptr{}) 5960 Tscalarptr = TypeOf(Scalarptr{}) 5961 Tptrscalar = TypeOf(Ptrscalar{}) 5962 Tbigptrscalar = TypeOf(Bigptrscalar{}) 5963 } 5964 5965 empty := []byte{} 5966 5967 verifyGCBits(t, TypeOf(Xscalar{}), empty) 5968 verifyGCBits(t, Tscalar, empty) 5969 verifyGCBits(t, TypeOf(Xptr{}), lit(1)) 5970 verifyGCBits(t, Tptr, lit(1)) 5971 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1)) 5972 verifyGCBits(t, Tscalarptr, lit(0, 1)) 5973 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1)) 5974 verifyGCBits(t, Tptrscalar, lit(1)) 5975 5976 verifyGCBits(t, TypeOf([0]Xptr{}), empty) 5977 verifyGCBits(t, ArrayOf(0, Tptr), empty) 5978 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1)) 5979 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1)) 5980 verifyGCBits(t, TypeOf([2]Xscalar{}), empty) 5981 verifyGCBits(t, ArrayOf(2, Tscalar), empty) 5982 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty) 5983 verifyGCBits(t, ArrayOf(10000, Tscalar), empty) 5984 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1)) 5985 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1)) 5986 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1))) 5987 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1))) 5988 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1)) 5989 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1)) 5990 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1))) 5991 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1))) 5992 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1)) 5993 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1)) 5994 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0))) 5995 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0))) 5996 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0))) 5997 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0))) 5998 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0))) 5999 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0))) 6000 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) 6001 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) 6002 6003 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty) 6004 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty) 6005 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1)) 6006 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1)) 6007 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0)) 6008 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0)) 6009 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0)) 6010 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0)) 6011 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1)) 6012 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1)) 6013 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1)) 6014 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1)) 6015 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1)) 6016 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1)) 6017 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1)) 6018 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1)) 6019 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0)) 6020 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0)) 6021 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0)) 6022 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0)) 6023 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0))) 6024 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0))) 6025 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0))) 6026 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0))) 6027 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0)))) 6028 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0)))) 6029 6030 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1)) 6031 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1)) 6032 6033 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1)) 6034 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1)) 6035 6036 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1)) 6037 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1)) 6038 6039 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1)) 6040 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1)) 6041 6042 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1)) 6043 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1)) 6044 6045 hdr := make([]byte, 8/PtrSize) 6046 6047 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) { 6048 verifyGCBits(t, MapBucketOf(k, e), want) 6049 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want) 6050 } 6051 verifyMapBucket(t, 6052 Tscalar, Tptr, 6053 map[Xscalar]Xptr(nil), 6054 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1))) 6055 verifyMapBucket(t, 6056 Tscalarptr, Tptr, 6057 map[Xscalarptr]Xptr(nil), 6058 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1))) 6059 verifyMapBucket(t, Tint64, Tptr, 6060 map[int64]Xptr(nil), 6061 join(hdr, rep(8, rep(8/PtrSize, lit(0))), rep(8, lit(1)), naclpad(), lit(1))) 6062 verifyMapBucket(t, 6063 Tscalar, Tscalar, 6064 map[Xscalar]Xscalar(nil), 6065 empty) 6066 verifyMapBucket(t, 6067 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar), 6068 map[[2]Xscalarptr][3]Xptrscalar(nil), 6069 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1))) 6070 verifyMapBucket(t, 6071 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar), 6072 map[[64 / PtrSize]Xscalarptr][64 / PtrSize]Xptrscalar(nil), 6073 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8*64/PtrSize, lit(1, 0)), lit(1))) 6074 verifyMapBucket(t, 6075 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar), 6076 map[[64/PtrSize + 1]Xscalarptr][64 / PtrSize]Xptrscalar(nil), 6077 join(hdr, rep(8, lit(1)), rep(8*64/PtrSize, lit(1, 0)), lit(1))) 6078 verifyMapBucket(t, 6079 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar), 6080 map[[64 / PtrSize]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil), 6081 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1))) 6082 verifyMapBucket(t, 6083 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar), 6084 map[[64/PtrSize + 1]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil), 6085 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1))) 6086 } 6087 6088 func naclpad() []byte { 6089 if runtime.GOARCH == "amd64p32" { 6090 return lit(0) 6091 } 6092 return nil 6093 } 6094 6095 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) } 6096 func join(b ...[]byte) []byte { return bytes.Join(b, nil) } 6097 func lit(x ...byte) []byte { return x } 6098 6099 func TestTypeOfTypeOf(t *testing.T) { 6100 // Check that all the type constructors return concrete *rtype implementations. 6101 // It's difficult to test directly because the reflect package is only at arm's length. 6102 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype. 6103 check := func(name string, typ Type) { 6104 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" { 6105 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying) 6106 } 6107 } 6108 6109 type T struct{ int } 6110 check("TypeOf", TypeOf(T{})) 6111 6112 check("ArrayOf", ArrayOf(10, TypeOf(T{}))) 6113 check("ChanOf", ChanOf(BothDir, TypeOf(T{}))) 6114 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false)) 6115 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{}))) 6116 check("PtrTo", PtrTo(TypeOf(T{}))) 6117 check("SliceOf", SliceOf(TypeOf(T{}))) 6118 } 6119 6120 type XM struct{ _ bool } 6121 6122 func (*XM) String() string { return "" } 6123 6124 func TestPtrToMethods(t *testing.T) { 6125 var y struct{ XM } 6126 yp := New(TypeOf(y)).Interface() 6127 _, ok := yp.(fmt.Stringer) 6128 if !ok { 6129 t.Fatal("does not implement Stringer, but should") 6130 } 6131 } 6132 6133 func TestMapAlloc(t *testing.T) { 6134 m := ValueOf(make(map[int]int, 10)) 6135 k := ValueOf(5) 6136 v := ValueOf(7) 6137 allocs := testing.AllocsPerRun(100, func() { 6138 m.SetMapIndex(k, v) 6139 }) 6140 if allocs > 0.5 { 6141 t.Errorf("allocs per map assignment: want 0 got %f", allocs) 6142 } 6143 6144 const size = 1000 6145 tmp := 0 6146 val := ValueOf(&tmp).Elem() 6147 allocs = testing.AllocsPerRun(100, func() { 6148 mv := MakeMapWithSize(TypeOf(map[int]int{}), size) 6149 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets. 6150 for i := 0; i < size/2; i++ { 6151 val.SetInt(int64(i)) 6152 mv.SetMapIndex(val, val) 6153 } 6154 }) 6155 if allocs > 10 { 6156 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs) 6157 } 6158 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set 6159 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the 6160 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added. 6161 } 6162 6163 func TestChanAlloc(t *testing.T) { 6164 // Note: for a chan int, the return Value must be allocated, so we 6165 // use a chan *int instead. 6166 c := ValueOf(make(chan *int, 1)) 6167 v := ValueOf(new(int)) 6168 allocs := testing.AllocsPerRun(100, func() { 6169 c.Send(v) 6170 _, _ = c.Recv() 6171 }) 6172 if allocs < 0.5 || allocs > 1.5 { 6173 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs) 6174 } 6175 // Note: there is one allocation in reflect.recv which seems to be 6176 // a limitation of escape analysis. If that is ever fixed the 6177 // allocs < 0.5 condition will trigger and this test should be fixed. 6178 } 6179 6180 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int 6181 6182 type nameTest struct { 6183 v interface{} 6184 want string 6185 } 6186 6187 var nameTests = []nameTest{ 6188 {(*int32)(nil), "int32"}, 6189 {(*D1)(nil), "D1"}, 6190 {(*[]D1)(nil), ""}, 6191 {(*chan D1)(nil), ""}, 6192 {(*func() D1)(nil), ""}, 6193 {(*<-chan D1)(nil), ""}, 6194 {(*chan<- D1)(nil), ""}, 6195 {(*interface{})(nil), ""}, 6196 {(*interface { 6197 F() 6198 })(nil), ""}, 6199 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"}, 6200 } 6201 6202 func TestNames(t *testing.T) { 6203 for _, test := range nameTests { 6204 typ := TypeOf(test.v).Elem() 6205 if got := typ.Name(); got != test.want { 6206 t.Errorf("%v Name()=%q, want %q", typ, got, test.want) 6207 } 6208 } 6209 } 6210 6211 func TestExported(t *testing.T) { 6212 type ΦExported struct{} 6213 type φUnexported struct{} 6214 type BigP *big 6215 type P int 6216 type p *P 6217 type P2 p 6218 type p3 p 6219 6220 type exportTest struct { 6221 v interface{} 6222 want bool 6223 } 6224 exportTests := []exportTest{ 6225 {D1{}, true}, 6226 {(*D1)(nil), true}, 6227 {big{}, false}, 6228 {(*big)(nil), false}, 6229 {(BigP)(nil), true}, 6230 {(*BigP)(nil), true}, 6231 {ΦExported{}, true}, 6232 {φUnexported{}, false}, 6233 {P(0), true}, 6234 {(p)(nil), false}, 6235 {(P2)(nil), true}, 6236 {(p3)(nil), false}, 6237 } 6238 6239 for i, test := range exportTests { 6240 typ := TypeOf(test.v) 6241 if got := IsExported(typ); got != test.want { 6242 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want) 6243 } 6244 } 6245 } 6246 6247 type embed struct { 6248 EmbedWithUnexpMeth 6249 } 6250 6251 func TestNameBytesAreAligned(t *testing.T) { 6252 typ := TypeOf(embed{}) 6253 b := FirstMethodNameBytes(typ) 6254 v := uintptr(unsafe.Pointer(b)) 6255 if v%unsafe.Alignof((*byte)(nil)) != 0 { 6256 t.Errorf("reflect.name.bytes pointer is not aligned: %x", v) 6257 } 6258 } 6259 6260 func TestTypeStrings(t *testing.T) { 6261 type stringTest struct { 6262 typ Type 6263 want string 6264 } 6265 stringTests := []stringTest{ 6266 {TypeOf(func(int) {}), "func(int)"}, 6267 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"}, 6268 {TypeOf(XM{}), "reflect_test.XM"}, 6269 {TypeOf(new(XM)), "*reflect_test.XM"}, 6270 {TypeOf(new(XM).String), "func() string"}, 6271 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"}, 6272 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"}, 6273 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"}, 6274 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"}, 6275 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"}, 6276 } 6277 6278 for i, test := range stringTests { 6279 if got, want := test.typ.String(), test.want; got != want { 6280 t.Errorf("type %d String()=%q, want %q", i, got, want) 6281 } 6282 } 6283 } 6284 6285 func TestOffsetLock(t *testing.T) { 6286 var wg sync.WaitGroup 6287 for i := 0; i < 4; i++ { 6288 i := i 6289 wg.Add(1) 6290 go func() { 6291 for j := 0; j < 50; j++ { 6292 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j)) 6293 } 6294 wg.Done() 6295 }() 6296 } 6297 wg.Wait() 6298 } 6299 6300 func BenchmarkNew(b *testing.B) { 6301 v := TypeOf(XM{}) 6302 b.RunParallel(func(pb *testing.PB) { 6303 for pb.Next() { 6304 New(v) 6305 } 6306 }) 6307 } 6308 6309 func TestSwapper(t *testing.T) { 6310 type I int 6311 var a, b, c I 6312 type pair struct { 6313 x, y int 6314 } 6315 type pairPtr struct { 6316 x, y int 6317 p *I 6318 } 6319 type S string 6320 6321 tests := []struct { 6322 in interface{} 6323 i, j int 6324 want interface{} 6325 }{ 6326 { 6327 in: []int{1, 20, 300}, 6328 i: 0, 6329 j: 2, 6330 want: []int{300, 20, 1}, 6331 }, 6332 { 6333 in: []uintptr{1, 20, 300}, 6334 i: 0, 6335 j: 2, 6336 want: []uintptr{300, 20, 1}, 6337 }, 6338 { 6339 in: []int16{1, 20, 300}, 6340 i: 0, 6341 j: 2, 6342 want: []int16{300, 20, 1}, 6343 }, 6344 { 6345 in: []int8{1, 20, 100}, 6346 i: 0, 6347 j: 2, 6348 want: []int8{100, 20, 1}, 6349 }, 6350 { 6351 in: []*I{&a, &b, &c}, 6352 i: 0, 6353 j: 2, 6354 want: []*I{&c, &b, &a}, 6355 }, 6356 { 6357 in: []string{"eric", "sergey", "larry"}, 6358 i: 0, 6359 j: 2, 6360 want: []string{"larry", "sergey", "eric"}, 6361 }, 6362 { 6363 in: []S{"eric", "sergey", "larry"}, 6364 i: 0, 6365 j: 2, 6366 want: []S{"larry", "sergey", "eric"}, 6367 }, 6368 { 6369 in: []pair{{1, 2}, {3, 4}, {5, 6}}, 6370 i: 0, 6371 j: 2, 6372 want: []pair{{5, 6}, {3, 4}, {1, 2}}, 6373 }, 6374 { 6375 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}}, 6376 i: 0, 6377 j: 2, 6378 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}}, 6379 }, 6380 } 6381 6382 for i, tt := range tests { 6383 inStr := fmt.Sprint(tt.in) 6384 Swapper(tt.in)(tt.i, tt.j) 6385 if !DeepEqual(tt.in, tt.want) { 6386 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want) 6387 } 6388 } 6389 } 6390 6391 // TestUnaddressableField tests that the reflect package will not allow 6392 // a type from another package to be used as a named type with an 6393 // unexported field. 6394 // 6395 // This ensures that unexported fields cannot be modified by other packages. 6396 func TestUnaddressableField(t *testing.T) { 6397 var b Buffer // type defined in reflect, a different package 6398 var localBuffer struct { 6399 buf []byte 6400 } 6401 lv := ValueOf(&localBuffer).Elem() 6402 rv := ValueOf(b) 6403 shouldPanic(func() { 6404 lv.Set(rv) 6405 }) 6406 } 6407 6408 type Tint int 6409 6410 type Tint2 = Tint 6411 6412 type Talias1 struct { 6413 byte 6414 uint8 6415 int 6416 int32 6417 rune 6418 } 6419 6420 type Talias2 struct { 6421 Tint 6422 Tint2 6423 } 6424 6425 func TestAliasNames(t *testing.T) { 6426 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5} 6427 out := fmt.Sprintf("%#v", t1) 6428 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}" 6429 if out != want { 6430 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want) 6431 } 6432 6433 t2 := Talias2{Tint: 1, Tint2: 2} 6434 out = fmt.Sprintf("%#v", t2) 6435 want = "reflect_test.Talias2{Tint:1, Tint2:2}" 6436 if out != want { 6437 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want) 6438 } 6439 } 6440 6441 func TestIssue22031(t *testing.T) { 6442 type s []struct{ C int } 6443 6444 type t1 struct{ s } 6445 type t2 struct{ f s } 6446 6447 tests := []Value{ 6448 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0), 6449 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0), 6450 } 6451 6452 for i, test := range tests { 6453 if test.CanSet() { 6454 t.Errorf("%d: CanSet: got true, want false", i) 6455 } 6456 } 6457 } 6458 6459 type NonExportedFirst int 6460 6461 func (i NonExportedFirst) ΦExported() {} 6462 func (i NonExportedFirst) nonexported() int { panic("wrong") } 6463 6464 func TestIssue22073(t *testing.T) { 6465 m := ValueOf(NonExportedFirst(0)).Method(0) 6466 6467 if got := m.Type().NumOut(); got != 0 { 6468 t.Errorf("NumOut: got %v, want 0", got) 6469 } 6470 6471 // Shouldn't panic. 6472 m.Call(nil) 6473 }