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