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