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