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