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