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