github.com/mh-cbon/go@v0.0.0-20160603070303-9e112a3fe4c0/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 } 2265 for _, test := range tests { 2266 if path := test.t.PkgPath(); path != test.path { 2267 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path) 2268 } 2269 } 2270 } 2271 2272 func TestFieldPkgPath(t *testing.T) { 2273 typ := TypeOf(struct { 2274 Exported string 2275 unexported string 2276 OtherPkgFields 2277 }{}) 2278 for _, test := range []struct { 2279 index []int 2280 pkgPath string 2281 anonymous bool 2282 }{ 2283 {[]int{0}, "", false}, // Exported 2284 {[]int{1}, "reflect_test", false}, // unexported 2285 {[]int{2}, "", true}, // OtherPkgFields 2286 {[]int{2, 0}, "", false}, // OtherExported 2287 {[]int{2, 1}, "reflect", false}, // otherUnexported 2288 } { 2289 f := typ.FieldByIndex(test.index) 2290 if got, want := f.PkgPath, test.pkgPath; got != want { 2291 t.Errorf("Field(%d).PkgPath = %q, want %q", test.index, got, want) 2292 } 2293 if got, want := f.Anonymous, test.anonymous; got != want { 2294 t.Errorf("Field(%d).Anonymous = %v, want %v", test.index, got, want) 2295 } 2296 } 2297 } 2298 2299 func TestVariadicType(t *testing.T) { 2300 // Test example from Type documentation. 2301 var f func(x int, y ...float64) 2302 typ := TypeOf(f) 2303 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) { 2304 sl := typ.In(1) 2305 if sl.Kind() == Slice { 2306 if sl.Elem() == TypeOf(0.0) { 2307 // ok 2308 return 2309 } 2310 } 2311 } 2312 2313 // Failed 2314 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64") 2315 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn()) 2316 for i := 0; i < typ.NumIn(); i++ { 2317 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i)) 2318 } 2319 t.Error(s) 2320 } 2321 2322 type inner struct { 2323 x int 2324 } 2325 2326 type outer struct { 2327 y int 2328 inner 2329 } 2330 2331 func (*inner) M() {} 2332 func (*outer) M() {} 2333 2334 func TestNestedMethods(t *testing.T) { 2335 typ := TypeOf((*outer)(nil)) 2336 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() { 2337 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M) 2338 for i := 0; i < typ.NumMethod(); i++ { 2339 m := typ.Method(i) 2340 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer()) 2341 } 2342 } 2343 } 2344 2345 type unexp struct{} 2346 2347 func (*unexp) f() (int32, int8) { return 7, 7 } 2348 func (*unexp) g() (int64, int8) { return 8, 8 } 2349 2350 type unexpI interface { 2351 f() (int32, int8) 2352 } 2353 2354 var unexpi unexpI = new(unexp) 2355 2356 func TestUnexportedMethods(t *testing.T) { 2357 typ := TypeOf(unexpi) 2358 2359 if got := typ.NumMethod(); got != 0 { 2360 t.Errorf("NumMethod=%d, want 0 satisfied methods", got) 2361 } 2362 } 2363 2364 type InnerInt struct { 2365 X int 2366 } 2367 2368 type OuterInt struct { 2369 Y int 2370 InnerInt 2371 } 2372 2373 func (i *InnerInt) M() int { 2374 return i.X 2375 } 2376 2377 func TestEmbeddedMethods(t *testing.T) { 2378 typ := TypeOf((*OuterInt)(nil)) 2379 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() { 2380 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M) 2381 for i := 0; i < typ.NumMethod(); i++ { 2382 m := typ.Method(i) 2383 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer()) 2384 } 2385 } 2386 2387 i := &InnerInt{3} 2388 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 { 2389 t.Errorf("i.M() = %d, want 3", v) 2390 } 2391 2392 o := &OuterInt{1, InnerInt{2}} 2393 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 { 2394 t.Errorf("i.M() = %d, want 2", v) 2395 } 2396 2397 f := (*OuterInt).M 2398 if v := f(o); v != 2 { 2399 t.Errorf("f(o) = %d, want 2", v) 2400 } 2401 } 2402 2403 type FuncDDD func(...interface{}) error 2404 2405 func (f FuncDDD) M() {} 2406 2407 func TestNumMethodOnDDD(t *testing.T) { 2408 rv := ValueOf((FuncDDD)(nil)) 2409 if n := rv.NumMethod(); n != 1 { 2410 t.Fatalf("NumMethod()=%d, want 1", n) 2411 } 2412 } 2413 2414 func TestPtrTo(t *testing.T) { 2415 var i int 2416 2417 typ := TypeOf(i) 2418 for i = 0; i < 100; i++ { 2419 typ = PtrTo(typ) 2420 } 2421 for i = 0; i < 100; i++ { 2422 typ = typ.Elem() 2423 } 2424 if typ != TypeOf(i) { 2425 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i)) 2426 } 2427 } 2428 2429 func TestPtrToGC(t *testing.T) { 2430 type T *uintptr 2431 tt := TypeOf(T(nil)) 2432 pt := PtrTo(tt) 2433 const n = 100 2434 var x []interface{} 2435 for i := 0; i < n; i++ { 2436 v := New(pt) 2437 p := new(*uintptr) 2438 *p = new(uintptr) 2439 **p = uintptr(i) 2440 v.Elem().Set(ValueOf(p).Convert(pt)) 2441 x = append(x, v.Interface()) 2442 } 2443 runtime.GC() 2444 2445 for i, xi := range x { 2446 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr) 2447 if k != uintptr(i) { 2448 t.Errorf("lost x[%d] = %d, want %d", i, k, i) 2449 } 2450 } 2451 } 2452 2453 func TestAddr(t *testing.T) { 2454 var p struct { 2455 X, Y int 2456 } 2457 2458 v := ValueOf(&p) 2459 v = v.Elem() 2460 v = v.Addr() 2461 v = v.Elem() 2462 v = v.Field(0) 2463 v.SetInt(2) 2464 if p.X != 2 { 2465 t.Errorf("Addr.Elem.Set failed to set value") 2466 } 2467 2468 // Again but take address of the ValueOf value. 2469 // Exercises generation of PtrTypes not present in the binary. 2470 q := &p 2471 v = ValueOf(&q).Elem() 2472 v = v.Addr() 2473 v = v.Elem() 2474 v = v.Elem() 2475 v = v.Addr() 2476 v = v.Elem() 2477 v = v.Field(0) 2478 v.SetInt(3) 2479 if p.X != 3 { 2480 t.Errorf("Addr.Elem.Set failed to set value") 2481 } 2482 2483 // Starting without pointer we should get changed value 2484 // in interface. 2485 qq := p 2486 v = ValueOf(&qq).Elem() 2487 v0 := v 2488 v = v.Addr() 2489 v = v.Elem() 2490 v = v.Field(0) 2491 v.SetInt(4) 2492 if p.X != 3 { // should be unchanged from last time 2493 t.Errorf("somehow value Set changed original p") 2494 } 2495 p = v0.Interface().(struct { 2496 X, Y int 2497 }) 2498 if p.X != 4 { 2499 t.Errorf("Addr.Elem.Set valued to set value in top value") 2500 } 2501 2502 // Verify that taking the address of a type gives us a pointer 2503 // which we can convert back using the usual interface 2504 // notation. 2505 var s struct { 2506 B *bool 2507 } 2508 ps := ValueOf(&s).Elem().Field(0).Addr().Interface() 2509 *(ps.(**bool)) = new(bool) 2510 if s.B == nil { 2511 t.Errorf("Addr.Interface direct assignment failed") 2512 } 2513 } 2514 2515 func noAlloc(t *testing.T, n int, f func(int)) { 2516 if testing.Short() { 2517 t.Skip("skipping malloc count in short mode") 2518 } 2519 if runtime.GOMAXPROCS(0) > 1 { 2520 t.Skip("skipping; GOMAXPROCS>1") 2521 } 2522 i := -1 2523 allocs := testing.AllocsPerRun(n, func() { 2524 f(i) 2525 i++ 2526 }) 2527 if allocs > 0 { 2528 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs) 2529 } 2530 } 2531 2532 func TestAllocations(t *testing.T) { 2533 noAlloc(t, 100, func(j int) { 2534 var i interface{} 2535 var v Value 2536 2537 // We can uncomment this when compiler escape analysis 2538 // is good enough to see that the integer assigned to i 2539 // does not escape and therefore need not be allocated. 2540 // 2541 // i = 42 + j 2542 // v = ValueOf(i) 2543 // if int(v.Int()) != 42+j { 2544 // panic("wrong int") 2545 // } 2546 2547 i = func(j int) int { return j } 2548 v = ValueOf(i) 2549 if v.Interface().(func(int) int)(j) != j { 2550 panic("wrong result") 2551 } 2552 }) 2553 } 2554 2555 func TestSmallNegativeInt(t *testing.T) { 2556 i := int16(-1) 2557 v := ValueOf(i) 2558 if v.Int() != -1 { 2559 t.Errorf("int16(-1).Int() returned %v", v.Int()) 2560 } 2561 } 2562 2563 func TestIndex(t *testing.T) { 2564 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8} 2565 v := ValueOf(xs).Index(3).Interface().(byte) 2566 if v != xs[3] { 2567 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3]) 2568 } 2569 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80} 2570 v = ValueOf(xa).Index(2).Interface().(byte) 2571 if v != xa[2] { 2572 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2]) 2573 } 2574 s := "0123456789" 2575 v = ValueOf(s).Index(3).Interface().(byte) 2576 if v != s[3] { 2577 t.Errorf("s.Index(3) = %v; expected %v", v, s[3]) 2578 } 2579 } 2580 2581 func TestSlice(t *testing.T) { 2582 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2583 v := ValueOf(xs).Slice(3, 5).Interface().([]int) 2584 if len(v) != 2 { 2585 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v)) 2586 } 2587 if cap(v) != 5 { 2588 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v)) 2589 } 2590 if !DeepEqual(v[0:5], xs[3:]) { 2591 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5]) 2592 } 2593 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2594 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int) 2595 if len(v) != 3 { 2596 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v)) 2597 } 2598 if cap(v) != 6 { 2599 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v)) 2600 } 2601 if !DeepEqual(v[0:6], xa[2:]) { 2602 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6]) 2603 } 2604 s := "0123456789" 2605 vs := ValueOf(s).Slice(3, 5).Interface().(string) 2606 if vs != s[3:5] { 2607 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5]) 2608 } 2609 2610 rv := ValueOf(&xs).Elem() 2611 rv = rv.Slice(3, 4) 2612 ptr2 := rv.Pointer() 2613 rv = rv.Slice(5, 5) 2614 ptr3 := rv.Pointer() 2615 if ptr3 != ptr2 { 2616 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2) 2617 } 2618 } 2619 2620 func TestSlice3(t *testing.T) { 2621 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2622 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int) 2623 if len(v) != 2 { 2624 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v)) 2625 } 2626 if cap(v) != 4 { 2627 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v)) 2628 } 2629 if !DeepEqual(v[0:4], xs[3:7:7]) { 2630 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4]) 2631 } 2632 rv := ValueOf(&xs).Elem() 2633 shouldPanic(func() { rv.Slice3(1, 2, 1) }) 2634 shouldPanic(func() { rv.Slice3(1, 1, 11) }) 2635 shouldPanic(func() { rv.Slice3(2, 2, 1) }) 2636 2637 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2638 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int) 2639 if len(v) != 3 { 2640 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v)) 2641 } 2642 if cap(v) != 4 { 2643 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v)) 2644 } 2645 if !DeepEqual(v[0:4], xa[2:6:6]) { 2646 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4]) 2647 } 2648 rv = ValueOf(&xa).Elem() 2649 shouldPanic(func() { rv.Slice3(1, 2, 1) }) 2650 shouldPanic(func() { rv.Slice3(1, 1, 11) }) 2651 shouldPanic(func() { rv.Slice3(2, 2, 1) }) 2652 2653 s := "hello world" 2654 rv = ValueOf(&s).Elem() 2655 shouldPanic(func() { rv.Slice3(1, 2, 3) }) 2656 2657 rv = ValueOf(&xs).Elem() 2658 rv = rv.Slice3(3, 5, 7) 2659 ptr2 := rv.Pointer() 2660 rv = rv.Slice3(4, 4, 4) 2661 ptr3 := rv.Pointer() 2662 if ptr3 != ptr2 { 2663 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2) 2664 } 2665 } 2666 2667 func TestSetLenCap(t *testing.T) { 2668 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2669 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2670 2671 vs := ValueOf(&xs).Elem() 2672 shouldPanic(func() { vs.SetLen(10) }) 2673 shouldPanic(func() { vs.SetCap(10) }) 2674 shouldPanic(func() { vs.SetLen(-1) }) 2675 shouldPanic(func() { vs.SetCap(-1) }) 2676 shouldPanic(func() { vs.SetCap(6) }) // smaller than len 2677 vs.SetLen(5) 2678 if len(xs) != 5 || cap(xs) != 8 { 2679 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs)) 2680 } 2681 vs.SetCap(6) 2682 if len(xs) != 5 || cap(xs) != 6 { 2683 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs)) 2684 } 2685 vs.SetCap(5) 2686 if len(xs) != 5 || cap(xs) != 5 { 2687 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs)) 2688 } 2689 shouldPanic(func() { vs.SetCap(4) }) // smaller than len 2690 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap 2691 2692 va := ValueOf(&xa).Elem() 2693 shouldPanic(func() { va.SetLen(8) }) 2694 shouldPanic(func() { va.SetCap(8) }) 2695 } 2696 2697 func TestVariadic(t *testing.T) { 2698 var b bytes.Buffer 2699 V := ValueOf 2700 2701 b.Reset() 2702 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)}) 2703 if b.String() != "hello, 42 world" { 2704 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world") 2705 } 2706 2707 b.Reset() 2708 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})}) 2709 if b.String() != "hello, 42 world" { 2710 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world") 2711 } 2712 } 2713 2714 func TestFuncArg(t *testing.T) { 2715 f1 := func(i int, f func(int) int) int { return f(i) } 2716 f2 := func(i int) int { return i + 1 } 2717 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)}) 2718 if r[0].Int() != 101 { 2719 t.Errorf("function returned %d, want 101", r[0].Int()) 2720 } 2721 } 2722 2723 func TestStructArg(t *testing.T) { 2724 type padded struct { 2725 B string 2726 C int32 2727 } 2728 var ( 2729 gotA padded 2730 gotB uint32 2731 wantA = padded{"3", 4} 2732 wantB = uint32(5) 2733 ) 2734 f := func(a padded, b uint32) { 2735 gotA, gotB = a, b 2736 } 2737 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)}) 2738 if gotA != wantA || gotB != wantB { 2739 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB) 2740 } 2741 } 2742 2743 var tagGetTests = []struct { 2744 Tag StructTag 2745 Key string 2746 Value string 2747 }{ 2748 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`}, 2749 {`protobuf:"PB(1,2)"`, `foo`, ``}, 2750 {`protobuf:"PB(1,2)"`, `rotobuf`, ``}, 2751 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`}, 2752 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`}, 2753 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"}, 2754 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"}, 2755 } 2756 2757 func TestTagGet(t *testing.T) { 2758 for _, tt := range tagGetTests { 2759 if v := tt.Tag.Get(tt.Key); v != tt.Value { 2760 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value) 2761 } 2762 } 2763 } 2764 2765 func TestBytes(t *testing.T) { 2766 type B []byte 2767 x := B{1, 2, 3, 4} 2768 y := ValueOf(x).Bytes() 2769 if !bytes.Equal(x, y) { 2770 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) 2771 } 2772 if &x[0] != &y[0] { 2773 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) 2774 } 2775 } 2776 2777 func TestSetBytes(t *testing.T) { 2778 type B []byte 2779 var x B 2780 y := []byte{1, 2, 3, 4} 2781 ValueOf(&x).Elem().SetBytes(y) 2782 if !bytes.Equal(x, y) { 2783 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) 2784 } 2785 if &x[0] != &y[0] { 2786 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) 2787 } 2788 } 2789 2790 type Private struct { 2791 x int 2792 y **int 2793 Z int 2794 } 2795 2796 func (p *Private) m() { 2797 } 2798 2799 type private struct { 2800 Z int 2801 z int 2802 S string 2803 A [1]Private 2804 T []Private 2805 } 2806 2807 func (p *private) P() { 2808 } 2809 2810 type Public struct { 2811 X int 2812 Y **int 2813 private 2814 } 2815 2816 func (p *Public) M() { 2817 } 2818 2819 func TestUnexported(t *testing.T) { 2820 var pub Public 2821 pub.S = "S" 2822 pub.T = pub.A[:] 2823 v := ValueOf(&pub) 2824 isValid(v.Elem().Field(0)) 2825 isValid(v.Elem().Field(1)) 2826 isValid(v.Elem().Field(2)) 2827 isValid(v.Elem().FieldByName("X")) 2828 isValid(v.Elem().FieldByName("Y")) 2829 isValid(v.Elem().FieldByName("Z")) 2830 isValid(v.Type().Method(0).Func) 2831 m, _ := v.Type().MethodByName("M") 2832 isValid(m.Func) 2833 m, _ = v.Type().MethodByName("P") 2834 isValid(m.Func) 2835 isNonNil(v.Elem().Field(0).Interface()) 2836 isNonNil(v.Elem().Field(1).Interface()) 2837 isNonNil(v.Elem().Field(2).Field(2).Index(0)) 2838 isNonNil(v.Elem().FieldByName("X").Interface()) 2839 isNonNil(v.Elem().FieldByName("Y").Interface()) 2840 isNonNil(v.Elem().FieldByName("Z").Interface()) 2841 isNonNil(v.Elem().FieldByName("S").Index(0).Interface()) 2842 isNonNil(v.Type().Method(0).Func.Interface()) 2843 m, _ = v.Type().MethodByName("P") 2844 isNonNil(m.Func.Interface()) 2845 2846 var priv Private 2847 v = ValueOf(&priv) 2848 isValid(v.Elem().Field(0)) 2849 isValid(v.Elem().Field(1)) 2850 isValid(v.Elem().FieldByName("x")) 2851 isValid(v.Elem().FieldByName("y")) 2852 shouldPanic(func() { v.Elem().Field(0).Interface() }) 2853 shouldPanic(func() { v.Elem().Field(1).Interface() }) 2854 shouldPanic(func() { v.Elem().FieldByName("x").Interface() }) 2855 shouldPanic(func() { v.Elem().FieldByName("y").Interface() }) 2856 shouldPanic(func() { v.Type().Method(0) }) 2857 } 2858 2859 func TestSetPanic(t *testing.T) { 2860 ok := func(f func()) { f() } 2861 bad := shouldPanic 2862 clear := func(v Value) { v.Set(Zero(v.Type())) } 2863 2864 type t0 struct { 2865 W int 2866 } 2867 2868 type t1 struct { 2869 Y int 2870 t0 2871 } 2872 2873 type T2 struct { 2874 Z int 2875 namedT0 t0 2876 } 2877 2878 type T struct { 2879 X int 2880 t1 2881 T2 2882 NamedT1 t1 2883 NamedT2 T2 2884 namedT1 t1 2885 namedT2 T2 2886 } 2887 2888 // not addressable 2889 v := ValueOf(T{}) 2890 bad(func() { clear(v.Field(0)) }) // .X 2891 bad(func() { clear(v.Field(1)) }) // .t1 2892 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y 2893 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 2894 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W 2895 bad(func() { clear(v.Field(2)) }) // .T2 2896 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z 2897 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 2898 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W 2899 bad(func() { clear(v.Field(3)) }) // .NamedT1 2900 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y 2901 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 2902 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W 2903 bad(func() { clear(v.Field(4)) }) // .NamedT2 2904 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z 2905 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 2906 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W 2907 bad(func() { clear(v.Field(5)) }) // .namedT1 2908 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y 2909 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 2910 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W 2911 bad(func() { clear(v.Field(6)) }) // .namedT2 2912 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z 2913 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 2914 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W 2915 2916 // addressable 2917 v = ValueOf(&T{}).Elem() 2918 ok(func() { clear(v.Field(0)) }) // .X 2919 bad(func() { clear(v.Field(1)) }) // .t1 2920 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y 2921 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 2922 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W 2923 ok(func() { clear(v.Field(2)) }) // .T2 2924 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z 2925 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 2926 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W 2927 ok(func() { clear(v.Field(3)) }) // .NamedT1 2928 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y 2929 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 2930 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W 2931 ok(func() { clear(v.Field(4)) }) // .NamedT2 2932 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z 2933 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 2934 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W 2935 bad(func() { clear(v.Field(5)) }) // .namedT1 2936 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y 2937 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 2938 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W 2939 bad(func() { clear(v.Field(6)) }) // .namedT2 2940 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z 2941 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 2942 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W 2943 } 2944 2945 type timp int 2946 2947 func (t timp) W() {} 2948 func (t timp) Y() {} 2949 func (t timp) w() {} 2950 func (t timp) y() {} 2951 2952 func TestCallPanic(t *testing.T) { 2953 type t0 interface { 2954 W() 2955 w() 2956 } 2957 type T1 interface { 2958 Y() 2959 y() 2960 } 2961 type T2 struct { 2962 T1 2963 t0 2964 } 2965 type T struct { 2966 t0 // 0 2967 T1 // 1 2968 2969 NamedT0 t0 // 2 2970 NamedT1 T1 // 3 2971 NamedT2 T2 // 4 2972 2973 namedT0 t0 // 5 2974 namedT1 T1 // 6 2975 namedT2 T2 // 7 2976 } 2977 ok := func(f func()) { f() } 2978 bad := shouldPanic 2979 call := func(v Value) { v.Call(nil) } 2980 2981 i := timp(0) 2982 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}}) 2983 ok(func() { call(v.Field(0).Method(0)) }) // .t0.W 2984 ok(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W 2985 bad(func() { call(v.Field(0).Method(1)) }) // .t0.w 2986 bad(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w 2987 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y 2988 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y 2989 bad(func() { call(v.Field(1).Method(1)) }) // .T1.y 2990 bad(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y 2991 2992 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W 2993 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W 2994 bad(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w 2995 bad(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w 2996 2997 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y 2998 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y 2999 bad(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y 3000 bad(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y 3001 3002 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y 3003 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W 3004 ok(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W 3005 ok(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W 3006 3007 bad(func() { call(v.Field(5).Method(0)) }) // .namedT0.W 3008 bad(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W 3009 bad(func() { call(v.Field(5).Method(1)) }) // .namedT0.w 3010 bad(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w 3011 3012 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y 3013 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y 3014 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.y 3015 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y 3016 3017 bad(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y 3018 bad(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W 3019 bad(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W 3020 bad(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W 3021 } 3022 3023 func shouldPanic(f func()) { 3024 defer func() { 3025 if recover() == nil { 3026 panic("did not panic") 3027 } 3028 }() 3029 f() 3030 } 3031 3032 func isNonNil(x interface{}) { 3033 if x == nil { 3034 panic("nil interface") 3035 } 3036 } 3037 3038 func isValid(v Value) { 3039 if !v.IsValid() { 3040 panic("zero Value") 3041 } 3042 } 3043 3044 func TestAlias(t *testing.T) { 3045 x := string("hello") 3046 v := ValueOf(&x).Elem() 3047 oldvalue := v.Interface() 3048 v.SetString("world") 3049 newvalue := v.Interface() 3050 3051 if oldvalue != "hello" || newvalue != "world" { 3052 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue) 3053 } 3054 } 3055 3056 var V = ValueOf 3057 3058 func EmptyInterfaceV(x interface{}) Value { 3059 return ValueOf(&x).Elem() 3060 } 3061 3062 func ReaderV(x io.Reader) Value { 3063 return ValueOf(&x).Elem() 3064 } 3065 3066 func ReadWriterV(x io.ReadWriter) Value { 3067 return ValueOf(&x).Elem() 3068 } 3069 3070 type Empty struct{} 3071 type MyString string 3072 type MyBytes []byte 3073 type MyRunes []int32 3074 type MyFunc func() 3075 type MyByte byte 3076 3077 var convertTests = []struct { 3078 in Value 3079 out Value 3080 }{ 3081 // numbers 3082 /* 3083 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go 3084 3085 package main 3086 3087 import "fmt" 3088 3089 var numbers = []string{ 3090 "int8", "uint8", "int16", "uint16", 3091 "int32", "uint32", "int64", "uint64", 3092 "int", "uint", "uintptr", 3093 "float32", "float64", 3094 } 3095 3096 func main() { 3097 // all pairs but in an unusual order, 3098 // to emit all the int8, uint8 cases 3099 // before n grows too big. 3100 n := 1 3101 for i, f := range numbers { 3102 for _, g := range numbers[i:] { 3103 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n) 3104 n++ 3105 if f != g { 3106 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n) 3107 n++ 3108 } 3109 } 3110 } 3111 } 3112 */ 3113 {V(int8(1)), V(int8(1))}, 3114 {V(int8(2)), V(uint8(2))}, 3115 {V(uint8(3)), V(int8(3))}, 3116 {V(int8(4)), V(int16(4))}, 3117 {V(int16(5)), V(int8(5))}, 3118 {V(int8(6)), V(uint16(6))}, 3119 {V(uint16(7)), V(int8(7))}, 3120 {V(int8(8)), V(int32(8))}, 3121 {V(int32(9)), V(int8(9))}, 3122 {V(int8(10)), V(uint32(10))}, 3123 {V(uint32(11)), V(int8(11))}, 3124 {V(int8(12)), V(int64(12))}, 3125 {V(int64(13)), V(int8(13))}, 3126 {V(int8(14)), V(uint64(14))}, 3127 {V(uint64(15)), V(int8(15))}, 3128 {V(int8(16)), V(int(16))}, 3129 {V(int(17)), V(int8(17))}, 3130 {V(int8(18)), V(uint(18))}, 3131 {V(uint(19)), V(int8(19))}, 3132 {V(int8(20)), V(uintptr(20))}, 3133 {V(uintptr(21)), V(int8(21))}, 3134 {V(int8(22)), V(float32(22))}, 3135 {V(float32(23)), V(int8(23))}, 3136 {V(int8(24)), V(float64(24))}, 3137 {V(float64(25)), V(int8(25))}, 3138 {V(uint8(26)), V(uint8(26))}, 3139 {V(uint8(27)), V(int16(27))}, 3140 {V(int16(28)), V(uint8(28))}, 3141 {V(uint8(29)), V(uint16(29))}, 3142 {V(uint16(30)), V(uint8(30))}, 3143 {V(uint8(31)), V(int32(31))}, 3144 {V(int32(32)), V(uint8(32))}, 3145 {V(uint8(33)), V(uint32(33))}, 3146 {V(uint32(34)), V(uint8(34))}, 3147 {V(uint8(35)), V(int64(35))}, 3148 {V(int64(36)), V(uint8(36))}, 3149 {V(uint8(37)), V(uint64(37))}, 3150 {V(uint64(38)), V(uint8(38))}, 3151 {V(uint8(39)), V(int(39))}, 3152 {V(int(40)), V(uint8(40))}, 3153 {V(uint8(41)), V(uint(41))}, 3154 {V(uint(42)), V(uint8(42))}, 3155 {V(uint8(43)), V(uintptr(43))}, 3156 {V(uintptr(44)), V(uint8(44))}, 3157 {V(uint8(45)), V(float32(45))}, 3158 {V(float32(46)), V(uint8(46))}, 3159 {V(uint8(47)), V(float64(47))}, 3160 {V(float64(48)), V(uint8(48))}, 3161 {V(int16(49)), V(int16(49))}, 3162 {V(int16(50)), V(uint16(50))}, 3163 {V(uint16(51)), V(int16(51))}, 3164 {V(int16(52)), V(int32(52))}, 3165 {V(int32(53)), V(int16(53))}, 3166 {V(int16(54)), V(uint32(54))}, 3167 {V(uint32(55)), V(int16(55))}, 3168 {V(int16(56)), V(int64(56))}, 3169 {V(int64(57)), V(int16(57))}, 3170 {V(int16(58)), V(uint64(58))}, 3171 {V(uint64(59)), V(int16(59))}, 3172 {V(int16(60)), V(int(60))}, 3173 {V(int(61)), V(int16(61))}, 3174 {V(int16(62)), V(uint(62))}, 3175 {V(uint(63)), V(int16(63))}, 3176 {V(int16(64)), V(uintptr(64))}, 3177 {V(uintptr(65)), V(int16(65))}, 3178 {V(int16(66)), V(float32(66))}, 3179 {V(float32(67)), V(int16(67))}, 3180 {V(int16(68)), V(float64(68))}, 3181 {V(float64(69)), V(int16(69))}, 3182 {V(uint16(70)), V(uint16(70))}, 3183 {V(uint16(71)), V(int32(71))}, 3184 {V(int32(72)), V(uint16(72))}, 3185 {V(uint16(73)), V(uint32(73))}, 3186 {V(uint32(74)), V(uint16(74))}, 3187 {V(uint16(75)), V(int64(75))}, 3188 {V(int64(76)), V(uint16(76))}, 3189 {V(uint16(77)), V(uint64(77))}, 3190 {V(uint64(78)), V(uint16(78))}, 3191 {V(uint16(79)), V(int(79))}, 3192 {V(int(80)), V(uint16(80))}, 3193 {V(uint16(81)), V(uint(81))}, 3194 {V(uint(82)), V(uint16(82))}, 3195 {V(uint16(83)), V(uintptr(83))}, 3196 {V(uintptr(84)), V(uint16(84))}, 3197 {V(uint16(85)), V(float32(85))}, 3198 {V(float32(86)), V(uint16(86))}, 3199 {V(uint16(87)), V(float64(87))}, 3200 {V(float64(88)), V(uint16(88))}, 3201 {V(int32(89)), V(int32(89))}, 3202 {V(int32(90)), V(uint32(90))}, 3203 {V(uint32(91)), V(int32(91))}, 3204 {V(int32(92)), V(int64(92))}, 3205 {V(int64(93)), V(int32(93))}, 3206 {V(int32(94)), V(uint64(94))}, 3207 {V(uint64(95)), V(int32(95))}, 3208 {V(int32(96)), V(int(96))}, 3209 {V(int(97)), V(int32(97))}, 3210 {V(int32(98)), V(uint(98))}, 3211 {V(uint(99)), V(int32(99))}, 3212 {V(int32(100)), V(uintptr(100))}, 3213 {V(uintptr(101)), V(int32(101))}, 3214 {V(int32(102)), V(float32(102))}, 3215 {V(float32(103)), V(int32(103))}, 3216 {V(int32(104)), V(float64(104))}, 3217 {V(float64(105)), V(int32(105))}, 3218 {V(uint32(106)), V(uint32(106))}, 3219 {V(uint32(107)), V(int64(107))}, 3220 {V(int64(108)), V(uint32(108))}, 3221 {V(uint32(109)), V(uint64(109))}, 3222 {V(uint64(110)), V(uint32(110))}, 3223 {V(uint32(111)), V(int(111))}, 3224 {V(int(112)), V(uint32(112))}, 3225 {V(uint32(113)), V(uint(113))}, 3226 {V(uint(114)), V(uint32(114))}, 3227 {V(uint32(115)), V(uintptr(115))}, 3228 {V(uintptr(116)), V(uint32(116))}, 3229 {V(uint32(117)), V(float32(117))}, 3230 {V(float32(118)), V(uint32(118))}, 3231 {V(uint32(119)), V(float64(119))}, 3232 {V(float64(120)), V(uint32(120))}, 3233 {V(int64(121)), V(int64(121))}, 3234 {V(int64(122)), V(uint64(122))}, 3235 {V(uint64(123)), V(int64(123))}, 3236 {V(int64(124)), V(int(124))}, 3237 {V(int(125)), V(int64(125))}, 3238 {V(int64(126)), V(uint(126))}, 3239 {V(uint(127)), V(int64(127))}, 3240 {V(int64(128)), V(uintptr(128))}, 3241 {V(uintptr(129)), V(int64(129))}, 3242 {V(int64(130)), V(float32(130))}, 3243 {V(float32(131)), V(int64(131))}, 3244 {V(int64(132)), V(float64(132))}, 3245 {V(float64(133)), V(int64(133))}, 3246 {V(uint64(134)), V(uint64(134))}, 3247 {V(uint64(135)), V(int(135))}, 3248 {V(int(136)), V(uint64(136))}, 3249 {V(uint64(137)), V(uint(137))}, 3250 {V(uint(138)), V(uint64(138))}, 3251 {V(uint64(139)), V(uintptr(139))}, 3252 {V(uintptr(140)), V(uint64(140))}, 3253 {V(uint64(141)), V(float32(141))}, 3254 {V(float32(142)), V(uint64(142))}, 3255 {V(uint64(143)), V(float64(143))}, 3256 {V(float64(144)), V(uint64(144))}, 3257 {V(int(145)), V(int(145))}, 3258 {V(int(146)), V(uint(146))}, 3259 {V(uint(147)), V(int(147))}, 3260 {V(int(148)), V(uintptr(148))}, 3261 {V(uintptr(149)), V(int(149))}, 3262 {V(int(150)), V(float32(150))}, 3263 {V(float32(151)), V(int(151))}, 3264 {V(int(152)), V(float64(152))}, 3265 {V(float64(153)), V(int(153))}, 3266 {V(uint(154)), V(uint(154))}, 3267 {V(uint(155)), V(uintptr(155))}, 3268 {V(uintptr(156)), V(uint(156))}, 3269 {V(uint(157)), V(float32(157))}, 3270 {V(float32(158)), V(uint(158))}, 3271 {V(uint(159)), V(float64(159))}, 3272 {V(float64(160)), V(uint(160))}, 3273 {V(uintptr(161)), V(uintptr(161))}, 3274 {V(uintptr(162)), V(float32(162))}, 3275 {V(float32(163)), V(uintptr(163))}, 3276 {V(uintptr(164)), V(float64(164))}, 3277 {V(float64(165)), V(uintptr(165))}, 3278 {V(float32(166)), V(float32(166))}, 3279 {V(float32(167)), V(float64(167))}, 3280 {V(float64(168)), V(float32(168))}, 3281 {V(float64(169)), V(float64(169))}, 3282 3283 // truncation 3284 {V(float64(1.5)), V(int(1))}, 3285 3286 // complex 3287 {V(complex64(1i)), V(complex64(1i))}, 3288 {V(complex64(2i)), V(complex128(2i))}, 3289 {V(complex128(3i)), V(complex64(3i))}, 3290 {V(complex128(4i)), V(complex128(4i))}, 3291 3292 // string 3293 {V(string("hello")), V(string("hello"))}, 3294 {V(string("bytes1")), V([]byte("bytes1"))}, 3295 {V([]byte("bytes2")), V(string("bytes2"))}, 3296 {V([]byte("bytes3")), V([]byte("bytes3"))}, 3297 {V(string("runes♝")), V([]rune("runes♝"))}, 3298 {V([]rune("runes♕")), V(string("runes♕"))}, 3299 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, 3300 {V(int('a')), V(string("a"))}, 3301 {V(int8('a')), V(string("a"))}, 3302 {V(int16('a')), V(string("a"))}, 3303 {V(int32('a')), V(string("a"))}, 3304 {V(int64('a')), V(string("a"))}, 3305 {V(uint('a')), V(string("a"))}, 3306 {V(uint8('a')), V(string("a"))}, 3307 {V(uint16('a')), V(string("a"))}, 3308 {V(uint32('a')), V(string("a"))}, 3309 {V(uint64('a')), V(string("a"))}, 3310 {V(uintptr('a')), V(string("a"))}, 3311 {V(int(-1)), V(string("\uFFFD"))}, 3312 {V(int8(-2)), V(string("\uFFFD"))}, 3313 {V(int16(-3)), V(string("\uFFFD"))}, 3314 {V(int32(-4)), V(string("\uFFFD"))}, 3315 {V(int64(-5)), V(string("\uFFFD"))}, 3316 {V(uint(0x110001)), V(string("\uFFFD"))}, 3317 {V(uint32(0x110002)), V(string("\uFFFD"))}, 3318 {V(uint64(0x110003)), V(string("\uFFFD"))}, 3319 {V(uintptr(0x110004)), V(string("\uFFFD"))}, 3320 3321 // named string 3322 {V(MyString("hello")), V(string("hello"))}, 3323 {V(string("hello")), V(MyString("hello"))}, 3324 {V(string("hello")), V(string("hello"))}, 3325 {V(MyString("hello")), V(MyString("hello"))}, 3326 {V(MyString("bytes1")), V([]byte("bytes1"))}, 3327 {V([]byte("bytes2")), V(MyString("bytes2"))}, 3328 {V([]byte("bytes3")), V([]byte("bytes3"))}, 3329 {V(MyString("runes♝")), V([]rune("runes♝"))}, 3330 {V([]rune("runes♕")), V(MyString("runes♕"))}, 3331 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, 3332 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))}, 3333 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, 3334 {V(int('a')), V(MyString("a"))}, 3335 {V(int8('a')), V(MyString("a"))}, 3336 {V(int16('a')), V(MyString("a"))}, 3337 {V(int32('a')), V(MyString("a"))}, 3338 {V(int64('a')), V(MyString("a"))}, 3339 {V(uint('a')), V(MyString("a"))}, 3340 {V(uint8('a')), V(MyString("a"))}, 3341 {V(uint16('a')), V(MyString("a"))}, 3342 {V(uint32('a')), V(MyString("a"))}, 3343 {V(uint64('a')), V(MyString("a"))}, 3344 {V(uintptr('a')), V(MyString("a"))}, 3345 {V(int(-1)), V(MyString("\uFFFD"))}, 3346 {V(int8(-2)), V(MyString("\uFFFD"))}, 3347 {V(int16(-3)), V(MyString("\uFFFD"))}, 3348 {V(int32(-4)), V(MyString("\uFFFD"))}, 3349 {V(int64(-5)), V(MyString("\uFFFD"))}, 3350 {V(uint(0x110001)), V(MyString("\uFFFD"))}, 3351 {V(uint32(0x110002)), V(MyString("\uFFFD"))}, 3352 {V(uint64(0x110003)), V(MyString("\uFFFD"))}, 3353 {V(uintptr(0x110004)), V(MyString("\uFFFD"))}, 3354 3355 // named []byte 3356 {V(string("bytes1")), V(MyBytes("bytes1"))}, 3357 {V(MyBytes("bytes2")), V(string("bytes2"))}, 3358 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))}, 3359 {V(MyString("bytes1")), V(MyBytes("bytes1"))}, 3360 {V(MyBytes("bytes2")), V(MyString("bytes2"))}, 3361 3362 // named []rune 3363 {V(string("runes♝")), V(MyRunes("runes♝"))}, 3364 {V(MyRunes("runes♕")), V(string("runes♕"))}, 3365 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))}, 3366 {V(MyString("runes♝")), V(MyRunes("runes♝"))}, 3367 {V(MyRunes("runes♕")), V(MyString("runes♕"))}, 3368 3369 // named types and equal underlying types 3370 {V(new(int)), V(new(integer))}, 3371 {V(new(integer)), V(new(int))}, 3372 {V(Empty{}), V(struct{}{})}, 3373 {V(new(Empty)), V(new(struct{}))}, 3374 {V(struct{}{}), V(Empty{})}, 3375 {V(new(struct{})), V(new(Empty))}, 3376 {V(Empty{}), V(Empty{})}, 3377 {V(MyBytes{}), V([]byte{})}, 3378 {V([]byte{}), V(MyBytes{})}, 3379 {V((func())(nil)), V(MyFunc(nil))}, 3380 {V((MyFunc)(nil)), V((func())(nil))}, 3381 3382 // can convert *byte and *MyByte 3383 {V((*byte)(nil)), V((*MyByte)(nil))}, 3384 {V((*MyByte)(nil)), V((*byte)(nil))}, 3385 3386 // cannot convert mismatched array sizes 3387 {V([2]byte{}), V([2]byte{})}, 3388 {V([3]byte{}), V([3]byte{})}, 3389 3390 // cannot convert other instances 3391 {V((**byte)(nil)), V((**byte)(nil))}, 3392 {V((**MyByte)(nil)), V((**MyByte)(nil))}, 3393 {V((chan byte)(nil)), V((chan byte)(nil))}, 3394 {V((chan MyByte)(nil)), V((chan MyByte)(nil))}, 3395 {V(([]byte)(nil)), V(([]byte)(nil))}, 3396 {V(([]MyByte)(nil)), V(([]MyByte)(nil))}, 3397 {V((map[int]byte)(nil)), V((map[int]byte)(nil))}, 3398 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))}, 3399 {V((map[byte]int)(nil)), V((map[byte]int)(nil))}, 3400 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))}, 3401 {V([2]byte{}), V([2]byte{})}, 3402 {V([2]MyByte{}), V([2]MyByte{})}, 3403 3404 // other 3405 {V((***int)(nil)), V((***int)(nil))}, 3406 {V((***byte)(nil)), V((***byte)(nil))}, 3407 {V((***int32)(nil)), V((***int32)(nil))}, 3408 {V((***int64)(nil)), V((***int64)(nil))}, 3409 {V((chan int)(nil)), V((<-chan int)(nil))}, 3410 {V((chan int)(nil)), V((chan<- int)(nil))}, 3411 {V((chan string)(nil)), V((<-chan string)(nil))}, 3412 {V((chan string)(nil)), V((chan<- string)(nil))}, 3413 {V((chan byte)(nil)), V((chan byte)(nil))}, 3414 {V((chan MyByte)(nil)), V((chan MyByte)(nil))}, 3415 {V((map[int]bool)(nil)), V((map[int]bool)(nil))}, 3416 {V((map[int]byte)(nil)), V((map[int]byte)(nil))}, 3417 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))}, 3418 {V([]uint(nil)), V([]uint(nil))}, 3419 {V([]int(nil)), V([]int(nil))}, 3420 {V(new(interface{})), V(new(interface{}))}, 3421 {V(new(io.Reader)), V(new(io.Reader))}, 3422 {V(new(io.Writer)), V(new(io.Writer))}, 3423 3424 // interfaces 3425 {V(int(1)), EmptyInterfaceV(int(1))}, 3426 {V(string("hello")), EmptyInterfaceV(string("hello"))}, 3427 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, 3428 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, 3429 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))}, 3430 } 3431 3432 func TestConvert(t *testing.T) { 3433 canConvert := map[[2]Type]bool{} 3434 all := map[Type]bool{} 3435 3436 for _, tt := range convertTests { 3437 t1 := tt.in.Type() 3438 if !t1.ConvertibleTo(t1) { 3439 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1) 3440 continue 3441 } 3442 3443 t2 := tt.out.Type() 3444 if !t1.ConvertibleTo(t2) { 3445 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2) 3446 continue 3447 } 3448 3449 all[t1] = true 3450 all[t2] = true 3451 canConvert[[2]Type{t1, t2}] = true 3452 3453 // vout1 represents the in value converted to the in type. 3454 v1 := tt.in 3455 vout1 := v1.Convert(t1) 3456 out1 := vout1.Interface() 3457 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) { 3458 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface()) 3459 } 3460 3461 // vout2 represents the in value converted to the out type. 3462 vout2 := v1.Convert(t2) 3463 out2 := vout2.Interface() 3464 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) { 3465 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface()) 3466 } 3467 3468 // vout3 represents a new value of the out type, set to vout2. This makes 3469 // sure the converted value vout2 is really usable as a regular value. 3470 vout3 := New(t2).Elem() 3471 vout3.Set(vout2) 3472 out3 := vout3.Interface() 3473 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) { 3474 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface()) 3475 } 3476 3477 if IsRO(v1) { 3478 t.Errorf("table entry %v is RO, should not be", v1) 3479 } 3480 if IsRO(vout1) { 3481 t.Errorf("self-conversion output %v is RO, should not be", vout1) 3482 } 3483 if IsRO(vout2) { 3484 t.Errorf("conversion output %v is RO, should not be", vout2) 3485 } 3486 if IsRO(vout3) { 3487 t.Errorf("set(conversion output) %v is RO, should not be", vout3) 3488 } 3489 if !IsRO(MakeRO(v1).Convert(t1)) { 3490 t.Errorf("RO self-conversion output %v is not RO, should be", v1) 3491 } 3492 if !IsRO(MakeRO(v1).Convert(t2)) { 3493 t.Errorf("RO conversion output %v is not RO, should be", v1) 3494 } 3495 } 3496 3497 // Assume that of all the types we saw during the tests, 3498 // if there wasn't an explicit entry for a conversion between 3499 // a pair of types, then it's not to be allowed. This checks for 3500 // things like 'int64' converting to '*int'. 3501 for t1 := range all { 3502 for t2 := range all { 3503 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0 3504 if ok := t1.ConvertibleTo(t2); ok != expectOK { 3505 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK) 3506 } 3507 } 3508 } 3509 } 3510 3511 type ComparableStruct struct { 3512 X int 3513 } 3514 3515 type NonComparableStruct struct { 3516 X int 3517 Y map[string]int 3518 } 3519 3520 var comparableTests = []struct { 3521 typ Type 3522 ok bool 3523 }{ 3524 {TypeOf(1), true}, 3525 {TypeOf("hello"), true}, 3526 {TypeOf(new(byte)), true}, 3527 {TypeOf((func())(nil)), false}, 3528 {TypeOf([]byte{}), false}, 3529 {TypeOf(map[string]int{}), false}, 3530 {TypeOf(make(chan int)), true}, 3531 {TypeOf(1.5), true}, 3532 {TypeOf(false), true}, 3533 {TypeOf(1i), true}, 3534 {TypeOf(ComparableStruct{}), true}, 3535 {TypeOf(NonComparableStruct{}), false}, 3536 {TypeOf([10]map[string]int{}), false}, 3537 {TypeOf([10]string{}), true}, 3538 {TypeOf(new(interface{})).Elem(), true}, 3539 } 3540 3541 func TestComparable(t *testing.T) { 3542 for _, tt := range comparableTests { 3543 if ok := tt.typ.Comparable(); ok != tt.ok { 3544 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok) 3545 } 3546 } 3547 } 3548 3549 func TestOverflow(t *testing.T) { 3550 if ovf := V(float64(0)).OverflowFloat(1e300); ovf { 3551 t.Errorf("%v wrongly overflows float64", 1e300) 3552 } 3553 3554 maxFloat32 := float64((1<<24 - 1) << (127 - 23)) 3555 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf { 3556 t.Errorf("%v wrongly overflows float32", maxFloat32) 3557 } 3558 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52)) 3559 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf { 3560 t.Errorf("%v should overflow float32", ovfFloat32) 3561 } 3562 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf { 3563 t.Errorf("%v should overflow float32", -ovfFloat32) 3564 } 3565 3566 maxInt32 := int64(0x7fffffff) 3567 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf { 3568 t.Errorf("%v wrongly overflows int32", maxInt32) 3569 } 3570 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf { 3571 t.Errorf("%v wrongly overflows int32", -int64(1)<<31) 3572 } 3573 ovfInt32 := int64(1 << 31) 3574 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf { 3575 t.Errorf("%v should overflow int32", ovfInt32) 3576 } 3577 3578 maxUint32 := uint64(0xffffffff) 3579 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf { 3580 t.Errorf("%v wrongly overflows uint32", maxUint32) 3581 } 3582 ovfUint32 := uint64(1 << 32) 3583 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf { 3584 t.Errorf("%v should overflow uint32", ovfUint32) 3585 } 3586 } 3587 3588 func checkSameType(t *testing.T, x, y interface{}) { 3589 if TypeOf(x) != TypeOf(y) { 3590 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y)) 3591 } 3592 } 3593 3594 func TestArrayOf(t *testing.T) { 3595 // check construction and use of type not in binary 3596 for _, table := range []struct { 3597 n int 3598 value func(i int) interface{} 3599 comparable bool 3600 want string 3601 }{ 3602 { 3603 n: 0, 3604 value: func(i int) interface{} { type Tint int; return Tint(i) }, 3605 comparable: true, 3606 want: "[]", 3607 }, 3608 { 3609 n: 10, 3610 value: func(i int) interface{} { type Tint int; return Tint(i) }, 3611 comparable: true, 3612 want: "[0 1 2 3 4 5 6 7 8 9]", 3613 }, 3614 { 3615 n: 10, 3616 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) }, 3617 comparable: true, 3618 want: "[0 1 2 3 4 5 6 7 8 9]", 3619 }, 3620 { 3621 n: 10, 3622 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) }, 3623 comparable: true, 3624 want: "[0 1 2 3 4 5 6 7 8 9]", 3625 }, 3626 { 3627 n: 10, 3628 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} }, 3629 comparable: true, 3630 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]", 3631 }, 3632 { 3633 n: 10, 3634 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} }, 3635 comparable: false, 3636 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", 3637 }, 3638 { 3639 n: 10, 3640 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} }, 3641 comparable: true, 3642 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", 3643 }, 3644 { 3645 n: 10, 3646 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} }, 3647 comparable: true, 3648 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", 3649 }, 3650 { 3651 n: 10, 3652 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} }, 3653 comparable: false, 3654 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", 3655 }, 3656 { 3657 n: 10, 3658 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} }, 3659 comparable: true, 3660 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", 3661 }, 3662 { 3663 n: 10, 3664 value: func(i int) interface{} { 3665 type TstructUV struct { 3666 U int 3667 V float64 3668 } 3669 return TstructUV{i, float64(i)} 3670 }, 3671 comparable: true, 3672 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", 3673 }, 3674 } { 3675 at := ArrayOf(table.n, TypeOf(table.value(0))) 3676 v := New(at).Elem() 3677 vok := New(at).Elem() 3678 vnot := New(at).Elem() 3679 for i := 0; i < v.Len(); i++ { 3680 v.Index(i).Set(ValueOf(table.value(i))) 3681 vok.Index(i).Set(ValueOf(table.value(i))) 3682 j := i 3683 if i+1 == v.Len() { 3684 j = i + 1 3685 } 3686 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element 3687 } 3688 s := fmt.Sprint(v.Interface()) 3689 if s != table.want { 3690 t.Errorf("constructed array = %s, want %s", s, table.want) 3691 } 3692 3693 if table.comparable != at.Comparable() { 3694 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable) 3695 } 3696 if table.comparable { 3697 if table.n > 0 { 3698 if DeepEqual(vnot.Interface(), v.Interface()) { 3699 t.Errorf( 3700 "arrays (%#v) compare ok (but should not)", 3701 v.Interface(), 3702 ) 3703 } 3704 } 3705 if !DeepEqual(vok.Interface(), v.Interface()) { 3706 t.Errorf( 3707 "arrays (%#v) compare NOT-ok (but should)", 3708 v.Interface(), 3709 ) 3710 } 3711 } 3712 } 3713 3714 // check that type already in binary is found 3715 type T int 3716 checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{}) 3717 } 3718 3719 func TestArrayOfGC(t *testing.T) { 3720 type T *uintptr 3721 tt := TypeOf(T(nil)) 3722 const n = 100 3723 var x []interface{} 3724 for i := 0; i < n; i++ { 3725 v := New(ArrayOf(n, tt)).Elem() 3726 for j := 0; j < v.Len(); j++ { 3727 p := new(uintptr) 3728 *p = uintptr(i*n + j) 3729 v.Index(j).Set(ValueOf(p).Convert(tt)) 3730 } 3731 x = append(x, v.Interface()) 3732 } 3733 runtime.GC() 3734 3735 for i, xi := range x { 3736 v := ValueOf(xi) 3737 for j := 0; j < v.Len(); j++ { 3738 k := v.Index(j).Elem().Interface() 3739 if k != uintptr(i*n+j) { 3740 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 3741 } 3742 } 3743 } 3744 } 3745 3746 func TestArrayOfAlg(t *testing.T) { 3747 at := ArrayOf(6, TypeOf(byte(0))) 3748 v1 := New(at).Elem() 3749 v2 := New(at).Elem() 3750 if v1.Interface() != v1.Interface() { 3751 t.Errorf("constructed array %v not equal to itself", v1.Interface()) 3752 } 3753 v1.Index(5).Set(ValueOf(byte(1))) 3754 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { 3755 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) 3756 } 3757 3758 at = ArrayOf(6, TypeOf([]int(nil))) 3759 v1 = New(at).Elem() 3760 shouldPanic(func() { _ = v1.Interface() == v1.Interface() }) 3761 } 3762 3763 func TestArrayOfGenericAlg(t *testing.T) { 3764 at1 := ArrayOf(5, TypeOf(string(""))) 3765 at := ArrayOf(6, at1) 3766 v1 := New(at).Elem() 3767 v2 := New(at).Elem() 3768 if v1.Interface() != v1.Interface() { 3769 t.Errorf("constructed array %v not equal to itself", v1.Interface()) 3770 } 3771 3772 v1.Index(0).Index(0).Set(ValueOf("abc")) 3773 v2.Index(0).Index(0).Set(ValueOf("efg")) 3774 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { 3775 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) 3776 } 3777 3778 v1.Index(0).Index(0).Set(ValueOf("abc")) 3779 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3])) 3780 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 { 3781 t.Errorf("constructed arrays %v and %v should be equal", i1, i2) 3782 } 3783 3784 // Test hash 3785 m := MakeMap(MapOf(at, TypeOf(int(0)))) 3786 m.SetMapIndex(v1, ValueOf(1)) 3787 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 3788 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2) 3789 } 3790 } 3791 3792 func TestArrayOfDirectIface(t *testing.T) { 3793 { 3794 type T [1]*byte 3795 i1 := Zero(TypeOf(T{})).Interface() 3796 v1 := ValueOf(&i1).Elem() 3797 p1 := v1.InterfaceData()[1] 3798 3799 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface() 3800 v2 := ValueOf(&i2).Elem() 3801 p2 := v2.InterfaceData()[1] 3802 3803 if p1 != 0 { 3804 t.Errorf("got p1=%v. want=%v", p1, nil) 3805 } 3806 3807 if p2 != 0 { 3808 t.Errorf("got p2=%v. want=%v", p2, nil) 3809 } 3810 } 3811 { 3812 type T [0]*byte 3813 i1 := Zero(TypeOf(T{})).Interface() 3814 v1 := ValueOf(&i1).Elem() 3815 p1 := v1.InterfaceData()[1] 3816 3817 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface() 3818 v2 := ValueOf(&i2).Elem() 3819 p2 := v2.InterfaceData()[1] 3820 3821 if p1 == 0 { 3822 t.Errorf("got p1=%v. want=not-%v", p1, nil) 3823 } 3824 3825 if p2 == 0 { 3826 t.Errorf("got p2=%v. want=not-%v", p2, nil) 3827 } 3828 } 3829 } 3830 3831 func TestSliceOf(t *testing.T) { 3832 // check construction and use of type not in binary 3833 type T int 3834 st := SliceOf(TypeOf(T(1))) 3835 if got, want := st.String(), "[]reflect_test.T"; got != want { 3836 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want) 3837 } 3838 v := MakeSlice(st, 10, 10) 3839 runtime.GC() 3840 for i := 0; i < v.Len(); i++ { 3841 v.Index(i).Set(ValueOf(T(i))) 3842 runtime.GC() 3843 } 3844 s := fmt.Sprint(v.Interface()) 3845 want := "[0 1 2 3 4 5 6 7 8 9]" 3846 if s != want { 3847 t.Errorf("constructed slice = %s, want %s", s, want) 3848 } 3849 3850 // check that type already in binary is found 3851 type T1 int 3852 checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{}) 3853 } 3854 3855 func TestSliceOverflow(t *testing.T) { 3856 // check that MakeSlice panics when size of slice overflows uint 3857 const S = 1e6 3858 s := uint(S) 3859 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1 3860 if l*s >= s { 3861 t.Fatal("slice size does not overflow") 3862 } 3863 var x [S]byte 3864 st := SliceOf(TypeOf(x)) 3865 defer func() { 3866 err := recover() 3867 if err == nil { 3868 t.Fatal("slice overflow does not panic") 3869 } 3870 }() 3871 MakeSlice(st, int(l), int(l)) 3872 } 3873 3874 func TestSliceOfGC(t *testing.T) { 3875 type T *uintptr 3876 tt := TypeOf(T(nil)) 3877 st := SliceOf(tt) 3878 const n = 100 3879 var x []interface{} 3880 for i := 0; i < n; i++ { 3881 v := MakeSlice(st, n, n) 3882 for j := 0; j < v.Len(); j++ { 3883 p := new(uintptr) 3884 *p = uintptr(i*n + j) 3885 v.Index(j).Set(ValueOf(p).Convert(tt)) 3886 } 3887 x = append(x, v.Interface()) 3888 } 3889 runtime.GC() 3890 3891 for i, xi := range x { 3892 v := ValueOf(xi) 3893 for j := 0; j < v.Len(); j++ { 3894 k := v.Index(j).Elem().Interface() 3895 if k != uintptr(i*n+j) { 3896 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 3897 } 3898 } 3899 } 3900 } 3901 3902 func TestStructOf(t *testing.T) { 3903 // check construction and use of type not in binary 3904 fields := []StructField{ 3905 StructField{ 3906 Name: "S", 3907 Tag: "s", 3908 Type: TypeOf(""), 3909 }, 3910 StructField{ 3911 Name: "X", 3912 Tag: "x", 3913 Type: TypeOf(byte(0)), 3914 }, 3915 StructField{ 3916 Name: "Y", 3917 Type: TypeOf(uint64(0)), 3918 }, 3919 StructField{ 3920 Name: "Z", 3921 Type: TypeOf([3]uint16{}), 3922 }, 3923 } 3924 3925 st := StructOf(fields) 3926 v := New(st).Elem() 3927 runtime.GC() 3928 v.FieldByName("X").Set(ValueOf(byte(2))) 3929 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1))) 3930 runtime.GC() 3931 3932 s := fmt.Sprint(v.Interface()) 3933 want := `{ 1 0 [0 0 0]}` 3934 if s != want { 3935 t.Errorf("constructed struct = %s, want %s", s, want) 3936 } 3937 3938 // check the size, alignment and field offsets 3939 stt := TypeOf(struct { 3940 String string 3941 X byte 3942 Y uint64 3943 Z [3]uint16 3944 }{}) 3945 if st.Size() != stt.Size() { 3946 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size()) 3947 } 3948 if st.Align() != stt.Align() { 3949 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align()) 3950 } 3951 if st.FieldAlign() != stt.FieldAlign() { 3952 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign()) 3953 } 3954 for i := 0; i < st.NumField(); i++ { 3955 o1 := st.Field(i).Offset 3956 o2 := stt.Field(i).Offset 3957 if o1 != o2 { 3958 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2) 3959 } 3960 } 3961 3962 // check duplicate names 3963 shouldPanic(func() { 3964 StructOf([]StructField{ 3965 StructField{Name: "string", Type: TypeOf("")}, 3966 StructField{Name: "string", Type: TypeOf("")}, 3967 }) 3968 }) 3969 shouldPanic(func() { 3970 StructOf([]StructField{ 3971 StructField{Type: TypeOf("")}, 3972 StructField{Name: "string", Type: TypeOf("")}, 3973 }) 3974 }) 3975 shouldPanic(func() { 3976 StructOf([]StructField{ 3977 StructField{Type: TypeOf("")}, 3978 StructField{Type: TypeOf("")}, 3979 }) 3980 }) 3981 // check that type already in binary is found 3982 checkSameType(t, Zero(StructOf(fields[2:3])).Interface(), struct{ Y uint64 }{}) 3983 } 3984 3985 func TestStructOfExportRules(t *testing.T) { 3986 type S1 struct{} 3987 type s2 struct{} 3988 type ΦType struct{} 3989 type φType struct{} 3990 3991 testPanic := func(i int, mustPanic bool, f func()) { 3992 defer func() { 3993 err := recover() 3994 if err == nil && mustPanic { 3995 t.Errorf("test-%d did not panic", i) 3996 } 3997 if err != nil && !mustPanic { 3998 t.Errorf("test-%d panicked: %v\n", i, err) 3999 } 4000 }() 4001 f() 4002 } 4003 4004 for i, test := range []struct { 4005 field StructField 4006 mustPanic bool 4007 exported bool 4008 }{ 4009 { 4010 field: StructField{Name: "", Type: TypeOf(S1{})}, 4011 mustPanic: false, 4012 exported: true, 4013 }, 4014 { 4015 field: StructField{Name: "", Type: TypeOf((*S1)(nil))}, 4016 mustPanic: false, 4017 exported: true, 4018 }, 4019 { 4020 field: StructField{Name: "", Type: TypeOf(s2{})}, 4021 mustPanic: false, 4022 exported: false, 4023 }, 4024 { 4025 field: StructField{Name: "", Type: TypeOf((*s2)(nil))}, 4026 mustPanic: false, 4027 exported: false, 4028 }, 4029 { 4030 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: "other/pkg"}, 4031 mustPanic: true, 4032 exported: true, 4033 }, 4034 { 4035 field: StructField{Name: "", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, 4036 mustPanic: true, 4037 exported: true, 4038 }, 4039 { 4040 field: StructField{Name: "", Type: TypeOf(s2{}), PkgPath: "other/pkg"}, 4041 mustPanic: true, 4042 exported: false, 4043 }, 4044 { 4045 field: StructField{Name: "", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, 4046 mustPanic: true, 4047 exported: false, 4048 }, 4049 { 4050 field: StructField{Name: "S", Type: TypeOf(S1{})}, 4051 mustPanic: false, 4052 exported: true, 4053 }, 4054 { 4055 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))}, 4056 mustPanic: false, 4057 exported: true, 4058 }, 4059 { 4060 field: StructField{Name: "S", Type: TypeOf(s2{})}, 4061 mustPanic: false, 4062 exported: true, 4063 }, 4064 { 4065 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))}, 4066 mustPanic: false, 4067 exported: true, 4068 }, 4069 { 4070 field: StructField{Name: "s", Type: TypeOf(S1{})}, 4071 mustPanic: true, 4072 exported: false, 4073 }, 4074 { 4075 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))}, 4076 mustPanic: true, 4077 exported: false, 4078 }, 4079 { 4080 field: StructField{Name: "s", Type: TypeOf(s2{})}, 4081 mustPanic: true, 4082 exported: false, 4083 }, 4084 { 4085 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))}, 4086 mustPanic: true, 4087 exported: false, 4088 }, 4089 { 4090 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"}, 4091 mustPanic: true, // TODO(sbinet): creating a name with a package path 4092 exported: false, 4093 }, 4094 { 4095 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, 4096 mustPanic: true, // TODO(sbinet): creating a name with a package path 4097 exported: false, 4098 }, 4099 { 4100 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"}, 4101 mustPanic: true, // TODO(sbinet): creating a name with a package path 4102 exported: false, 4103 }, 4104 { 4105 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, 4106 mustPanic: true, // TODO(sbinet): creating a name with a package path 4107 exported: false, 4108 }, 4109 { 4110 field: StructField{Name: "", Type: TypeOf(ΦType{})}, 4111 mustPanic: false, 4112 exported: true, 4113 }, 4114 { 4115 field: StructField{Name: "", Type: TypeOf(φType{})}, 4116 mustPanic: false, 4117 exported: false, 4118 }, 4119 { 4120 field: StructField{Name: "Φ", Type: TypeOf(0)}, 4121 mustPanic: false, 4122 exported: true, 4123 }, 4124 { 4125 field: StructField{Name: "φ", Type: TypeOf(0)}, 4126 mustPanic: false, 4127 exported: false, 4128 }, 4129 } { 4130 testPanic(i, test.mustPanic, func() { 4131 typ := StructOf([]StructField{test.field}) 4132 if typ == nil { 4133 t.Errorf("test-%d: error creating struct type", i) 4134 return 4135 } 4136 field := typ.Field(0) 4137 n := field.Name 4138 if n == "" { 4139 n = field.Type.Name() 4140 } 4141 exported := isExported(n) 4142 if exported != test.exported { 4143 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported) 4144 } 4145 }) 4146 } 4147 } 4148 4149 // isExported reports whether name is an exported Go symbol 4150 // (that is, whether it begins with an upper-case letter). 4151 // 4152 func isExported(name string) bool { 4153 ch, _ := utf8.DecodeRuneInString(name) 4154 return unicode.IsUpper(ch) 4155 } 4156 4157 func TestStructOfGC(t *testing.T) { 4158 type T *uintptr 4159 tt := TypeOf(T(nil)) 4160 fields := []StructField{ 4161 {Name: "X", Type: tt}, 4162 {Name: "Y", Type: tt}, 4163 } 4164 st := StructOf(fields) 4165 4166 const n = 10000 4167 var x []interface{} 4168 for i := 0; i < n; i++ { 4169 v := New(st).Elem() 4170 for j := 0; j < v.NumField(); j++ { 4171 p := new(uintptr) 4172 *p = uintptr(i*n + j) 4173 v.Field(j).Set(ValueOf(p).Convert(tt)) 4174 } 4175 x = append(x, v.Interface()) 4176 } 4177 runtime.GC() 4178 4179 for i, xi := range x { 4180 v := ValueOf(xi) 4181 for j := 0; j < v.NumField(); j++ { 4182 k := v.Field(j).Elem().Interface() 4183 if k != uintptr(i*n+j) { 4184 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j) 4185 } 4186 } 4187 } 4188 } 4189 4190 func TestStructOfAlg(t *testing.T) { 4191 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}}) 4192 v1 := New(st).Elem() 4193 v2 := New(st).Elem() 4194 if !DeepEqual(v1.Interface(), v1.Interface()) { 4195 t.Errorf("constructed struct %v not equal to itself", v1.Interface()) 4196 } 4197 v1.FieldByName("X").Set(ValueOf(int(1))) 4198 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { 4199 t.Errorf("constructed structs %v and %v should not be equal", i1, i2) 4200 } 4201 4202 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}}) 4203 v1 = New(st).Elem() 4204 shouldPanic(func() { _ = v1.Interface() == v1.Interface() }) 4205 } 4206 4207 func TestStructOfGenericAlg(t *testing.T) { 4208 st1 := StructOf([]StructField{ 4209 {Name: "X", Tag: "x", Type: TypeOf(int64(0))}, 4210 {Name: "Y", Type: TypeOf(string(""))}, 4211 }) 4212 st := StructOf([]StructField{ 4213 {Name: "S0", Type: st1}, 4214 {Name: "S1", Type: st1}, 4215 }) 4216 4217 for _, table := range []struct { 4218 rt Type 4219 idx []int 4220 }{ 4221 { 4222 rt: st, 4223 idx: []int{0, 1}, 4224 }, 4225 { 4226 rt: st1, 4227 idx: []int{1}, 4228 }, 4229 { 4230 rt: StructOf( 4231 []StructField{ 4232 {Name: "XX", Type: TypeOf([0]int{})}, 4233 {Name: "YY", Type: TypeOf("")}, 4234 }, 4235 ), 4236 idx: []int{1}, 4237 }, 4238 { 4239 rt: StructOf( 4240 []StructField{ 4241 {Name: "XX", Type: TypeOf([0]int{})}, 4242 {Name: "YY", Type: TypeOf("")}, 4243 {Name: "ZZ", Type: TypeOf([2]int{})}, 4244 }, 4245 ), 4246 idx: []int{1}, 4247 }, 4248 { 4249 rt: StructOf( 4250 []StructField{ 4251 {Name: "XX", Type: TypeOf([1]int{})}, 4252 {Name: "YY", Type: TypeOf("")}, 4253 }, 4254 ), 4255 idx: []int{1}, 4256 }, 4257 { 4258 rt: StructOf( 4259 []StructField{ 4260 {Name: "XX", Type: TypeOf([1]int{})}, 4261 {Name: "YY", Type: TypeOf("")}, 4262 {Name: "ZZ", Type: TypeOf([1]int{})}, 4263 }, 4264 ), 4265 idx: []int{1}, 4266 }, 4267 { 4268 rt: StructOf( 4269 []StructField{ 4270 {Name: "XX", Type: TypeOf([2]int{})}, 4271 {Name: "YY", Type: TypeOf("")}, 4272 {Name: "ZZ", Type: TypeOf([2]int{})}, 4273 }, 4274 ), 4275 idx: []int{1}, 4276 }, 4277 { 4278 rt: StructOf( 4279 []StructField{ 4280 {Name: "XX", Type: TypeOf(int64(0))}, 4281 {Name: "YY", Type: TypeOf(byte(0))}, 4282 {Name: "ZZ", Type: TypeOf("")}, 4283 }, 4284 ), 4285 idx: []int{2}, 4286 }, 4287 { 4288 rt: StructOf( 4289 []StructField{ 4290 {Name: "XX", Type: TypeOf(int64(0))}, 4291 {Name: "YY", Type: TypeOf(int64(0))}, 4292 {Name: "ZZ", Type: TypeOf("")}, 4293 {Name: "AA", Type: TypeOf([1]int64{})}, 4294 }, 4295 ), 4296 idx: []int{2}, 4297 }, 4298 } { 4299 v1 := New(table.rt).Elem() 4300 v2 := New(table.rt).Elem() 4301 4302 if !DeepEqual(v1.Interface(), v1.Interface()) { 4303 t.Errorf("constructed struct %v not equal to itself", v1.Interface()) 4304 } 4305 4306 v1.FieldByIndex(table.idx).Set(ValueOf("abc")) 4307 v2.FieldByIndex(table.idx).Set(ValueOf("def")) 4308 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { 4309 t.Errorf("constructed structs %v and %v should not be equal", i1, i2) 4310 } 4311 4312 abc := "abc" 4313 v1.FieldByIndex(table.idx).Set(ValueOf(abc)) 4314 val := "+" + abc + "-" 4315 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4])) 4316 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { 4317 t.Errorf("constructed structs %v and %v should be equal", i1, i2) 4318 } 4319 4320 // Test hash 4321 m := MakeMap(MapOf(table.rt, TypeOf(int(0)))) 4322 m.SetMapIndex(v1, ValueOf(1)) 4323 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4324 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2) 4325 } 4326 4327 v2.FieldByIndex(table.idx).Set(ValueOf("abc")) 4328 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { 4329 t.Errorf("constructed structs %v and %v should be equal", i1, i2) 4330 } 4331 4332 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4333 t.Errorf("constructed structs %v and %v have different hashes", i1, i2) 4334 } 4335 } 4336 } 4337 4338 func TestStructOfDirectIface(t *testing.T) { 4339 { 4340 type T struct{ X [1]*byte } 4341 i1 := Zero(TypeOf(T{})).Interface() 4342 v1 := ValueOf(&i1).Elem() 4343 p1 := v1.InterfaceData()[1] 4344 4345 i2 := Zero(StructOf([]StructField{ 4346 { 4347 Name: "X", 4348 Type: ArrayOf(1, TypeOf((*int8)(nil))), 4349 }, 4350 })).Interface() 4351 v2 := ValueOf(&i2).Elem() 4352 p2 := v2.InterfaceData()[1] 4353 4354 if p1 != 0 { 4355 t.Errorf("got p1=%v. want=%v", p1, nil) 4356 } 4357 4358 if p2 != 0 { 4359 t.Errorf("got p2=%v. want=%v", p2, nil) 4360 } 4361 } 4362 { 4363 type T struct{ X [0]*byte } 4364 i1 := Zero(TypeOf(T{})).Interface() 4365 v1 := ValueOf(&i1).Elem() 4366 p1 := v1.InterfaceData()[1] 4367 4368 i2 := Zero(StructOf([]StructField{ 4369 { 4370 Name: "X", 4371 Type: ArrayOf(0, TypeOf((*int8)(nil))), 4372 }, 4373 })).Interface() 4374 v2 := ValueOf(&i2).Elem() 4375 p2 := v2.InterfaceData()[1] 4376 4377 if p1 == 0 { 4378 t.Errorf("got p1=%v. want=not-%v", p1, nil) 4379 } 4380 4381 if p2 == 0 { 4382 t.Errorf("got p2=%v. want=not-%v", p2, nil) 4383 } 4384 } 4385 } 4386 4387 type StructI int 4388 4389 func (i StructI) Get() int { return int(i) } 4390 4391 type StructIPtr int 4392 4393 func (i *StructIPtr) Get() int { return int(*i) } 4394 4395 func TestStructOfWithInterface(t *testing.T) { 4396 const want = 42 4397 type Iface interface { 4398 Get() int 4399 } 4400 for i, table := range []struct { 4401 typ Type 4402 val Value 4403 impl bool 4404 }{ 4405 { 4406 typ: TypeOf(StructI(want)), 4407 val: ValueOf(StructI(want)), 4408 impl: true, 4409 }, 4410 { 4411 typ: PtrTo(TypeOf(StructI(want))), 4412 val: ValueOf(func() interface{} { 4413 v := StructI(want) 4414 return &v 4415 }()), 4416 impl: true, 4417 }, 4418 { 4419 typ: PtrTo(TypeOf(StructIPtr(want))), 4420 val: ValueOf(func() interface{} { 4421 v := StructIPtr(want) 4422 return &v 4423 }()), 4424 impl: true, 4425 }, 4426 { 4427 typ: TypeOf(StructIPtr(want)), 4428 val: ValueOf(StructIPtr(want)), 4429 impl: false, 4430 }, 4431 // { 4432 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn 4433 // val: ValueOf(StructI(want)), 4434 // impl: true, 4435 // }, 4436 } { 4437 rt := StructOf( 4438 []StructField{ 4439 { 4440 Name: "", 4441 PkgPath: "", 4442 Type: table.typ, 4443 }, 4444 }, 4445 ) 4446 rv := New(rt).Elem() 4447 rv.Field(0).Set(table.val) 4448 4449 if _, ok := rv.Interface().(Iface); ok != table.impl { 4450 if table.impl { 4451 t.Errorf("test-%d: type=%v fails to implement Iface.\n", i, table.typ) 4452 } else { 4453 t.Errorf("test-%d: type=%v should NOT implement Iface\n", i, table.typ) 4454 } 4455 continue 4456 } 4457 4458 if !table.impl { 4459 continue 4460 } 4461 4462 v := rv.Interface().(Iface).Get() 4463 if v != want { 4464 t.Errorf("test-%d: x.Get()=%v. want=%v\n", i, v, want) 4465 } 4466 4467 fct := rv.MethodByName("Get") 4468 out := fct.Call(nil) 4469 if !DeepEqual(out[0].Interface(), want) { 4470 t.Errorf("test-%d: x.Get()=%v. want=%v\n", i, out[0].Interface(), want) 4471 } 4472 } 4473 } 4474 4475 func TestChanOf(t *testing.T) { 4476 // check construction and use of type not in binary 4477 type T string 4478 ct := ChanOf(BothDir, TypeOf(T(""))) 4479 v := MakeChan(ct, 2) 4480 runtime.GC() 4481 v.Send(ValueOf(T("hello"))) 4482 runtime.GC() 4483 v.Send(ValueOf(T("world"))) 4484 runtime.GC() 4485 4486 sv1, _ := v.Recv() 4487 sv2, _ := v.Recv() 4488 s1 := sv1.String() 4489 s2 := sv2.String() 4490 if s1 != "hello" || s2 != "world" { 4491 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world") 4492 } 4493 4494 // check that type already in binary is found 4495 type T1 int 4496 checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil)) 4497 } 4498 4499 func TestChanOfDir(t *testing.T) { 4500 // check construction and use of type not in binary 4501 type T string 4502 crt := ChanOf(RecvDir, TypeOf(T(""))) 4503 cst := ChanOf(SendDir, TypeOf(T(""))) 4504 4505 // check that type already in binary is found 4506 type T1 int 4507 checkSameType(t, Zero(ChanOf(RecvDir, TypeOf(T1(1)))).Interface(), (<-chan T1)(nil)) 4508 checkSameType(t, Zero(ChanOf(SendDir, TypeOf(T1(1)))).Interface(), (chan<- T1)(nil)) 4509 4510 // check String form of ChanDir 4511 if crt.ChanDir().String() != "<-chan" { 4512 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan") 4513 } 4514 if cst.ChanDir().String() != "chan<-" { 4515 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-") 4516 } 4517 } 4518 4519 func TestChanOfGC(t *testing.T) { 4520 done := make(chan bool, 1) 4521 go func() { 4522 select { 4523 case <-done: 4524 case <-time.After(5 * time.Second): 4525 panic("deadlock in TestChanOfGC") 4526 } 4527 }() 4528 4529 defer func() { 4530 done <- true 4531 }() 4532 4533 type T *uintptr 4534 tt := TypeOf(T(nil)) 4535 ct := ChanOf(BothDir, tt) 4536 4537 // NOTE: The garbage collector handles allocated channels specially, 4538 // so we have to save pointers to channels in x; the pointer code will 4539 // use the gc info in the newly constructed chan type. 4540 const n = 100 4541 var x []interface{} 4542 for i := 0; i < n; i++ { 4543 v := MakeChan(ct, n) 4544 for j := 0; j < n; j++ { 4545 p := new(uintptr) 4546 *p = uintptr(i*n + j) 4547 v.Send(ValueOf(p).Convert(tt)) 4548 } 4549 pv := New(ct) 4550 pv.Elem().Set(v) 4551 x = append(x, pv.Interface()) 4552 } 4553 runtime.GC() 4554 4555 for i, xi := range x { 4556 v := ValueOf(xi).Elem() 4557 for j := 0; j < n; j++ { 4558 pv, _ := v.Recv() 4559 k := pv.Elem().Interface() 4560 if k != uintptr(i*n+j) { 4561 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 4562 } 4563 } 4564 } 4565 } 4566 4567 func TestMapOf(t *testing.T) { 4568 // check construction and use of type not in binary 4569 type K string 4570 type V float64 4571 4572 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0)))) 4573 runtime.GC() 4574 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1))) 4575 runtime.GC() 4576 4577 s := fmt.Sprint(v.Interface()) 4578 want := "map[a:1]" 4579 if s != want { 4580 t.Errorf("constructed map = %s, want %s", s, want) 4581 } 4582 4583 // check that type already in binary is found 4584 checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil)) 4585 4586 // check that invalid key type panics 4587 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) }) 4588 } 4589 4590 func TestMapOfGCKeys(t *testing.T) { 4591 type T *uintptr 4592 tt := TypeOf(T(nil)) 4593 mt := MapOf(tt, TypeOf(false)) 4594 4595 // NOTE: The garbage collector handles allocated maps specially, 4596 // so we have to save pointers to maps in x; the pointer code will 4597 // use the gc info in the newly constructed map type. 4598 const n = 100 4599 var x []interface{} 4600 for i := 0; i < n; i++ { 4601 v := MakeMap(mt) 4602 for j := 0; j < n; j++ { 4603 p := new(uintptr) 4604 *p = uintptr(i*n + j) 4605 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true)) 4606 } 4607 pv := New(mt) 4608 pv.Elem().Set(v) 4609 x = append(x, pv.Interface()) 4610 } 4611 runtime.GC() 4612 4613 for i, xi := range x { 4614 v := ValueOf(xi).Elem() 4615 var out []int 4616 for _, kv := range v.MapKeys() { 4617 out = append(out, int(kv.Elem().Interface().(uintptr))) 4618 } 4619 sort.Ints(out) 4620 for j, k := range out { 4621 if k != i*n+j { 4622 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 4623 } 4624 } 4625 } 4626 } 4627 4628 func TestMapOfGCValues(t *testing.T) { 4629 type T *uintptr 4630 tt := TypeOf(T(nil)) 4631 mt := MapOf(TypeOf(1), tt) 4632 4633 // NOTE: The garbage collector handles allocated maps specially, 4634 // so we have to save pointers to maps in x; the pointer code will 4635 // use the gc info in the newly constructed map type. 4636 const n = 100 4637 var x []interface{} 4638 for i := 0; i < n; i++ { 4639 v := MakeMap(mt) 4640 for j := 0; j < n; j++ { 4641 p := new(uintptr) 4642 *p = uintptr(i*n + j) 4643 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt)) 4644 } 4645 pv := New(mt) 4646 pv.Elem().Set(v) 4647 x = append(x, pv.Interface()) 4648 } 4649 runtime.GC() 4650 4651 for i, xi := range x { 4652 v := ValueOf(xi).Elem() 4653 for j := 0; j < n; j++ { 4654 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr) 4655 if k != uintptr(i*n+j) { 4656 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 4657 } 4658 } 4659 } 4660 } 4661 4662 func TestTypelinksSorted(t *testing.T) { 4663 var last string 4664 for i, n := range TypeLinks() { 4665 if n < last { 4666 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i) 4667 } 4668 last = n 4669 } 4670 } 4671 4672 func TestFuncOf(t *testing.T) { 4673 // check construction and use of type not in binary 4674 type K string 4675 type V float64 4676 4677 fn := func(args []Value) []Value { 4678 if len(args) != 1 { 4679 t.Errorf("args == %v, want exactly one arg", args) 4680 } else if args[0].Type() != TypeOf(K("")) { 4681 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K(""))) 4682 } else if args[0].String() != "gopher" { 4683 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher") 4684 } 4685 return []Value{ValueOf(V(3.14))} 4686 } 4687 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn) 4688 4689 outs := v.Call([]Value{ValueOf(K("gopher"))}) 4690 if len(outs) != 1 { 4691 t.Fatalf("v.Call returned %v, want exactly one result", outs) 4692 } else if outs[0].Type() != TypeOf(V(0)) { 4693 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0))) 4694 } 4695 f := outs[0].Float() 4696 if f != 3.14 { 4697 t.Errorf("constructed func returned %f, want %f", f, 3.14) 4698 } 4699 4700 // check that types already in binary are found 4701 type T1 int 4702 testCases := []struct { 4703 in, out []Type 4704 variadic bool 4705 want interface{} 4706 }{ 4707 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)}, 4708 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)}, 4709 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)}, 4710 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)}, 4711 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)}, 4712 } 4713 for _, tt := range testCases { 4714 checkSameType(t, Zero(FuncOf(tt.in, tt.out, tt.variadic)).Interface(), tt.want) 4715 } 4716 4717 // check that variadic requires last element be a slice. 4718 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true) 4719 shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) }) 4720 shouldPanic(func() { FuncOf(nil, nil, true) }) 4721 } 4722 4723 type B1 struct { 4724 X int 4725 Y int 4726 Z int 4727 } 4728 4729 func BenchmarkFieldByName1(b *testing.B) { 4730 t := TypeOf(B1{}) 4731 for i := 0; i < b.N; i++ { 4732 t.FieldByName("Z") 4733 } 4734 } 4735 4736 func BenchmarkFieldByName2(b *testing.B) { 4737 t := TypeOf(S3{}) 4738 for i := 0; i < b.N; i++ { 4739 t.FieldByName("B") 4740 } 4741 } 4742 4743 type R0 struct { 4744 *R1 4745 *R2 4746 *R3 4747 *R4 4748 } 4749 4750 type R1 struct { 4751 *R5 4752 *R6 4753 *R7 4754 *R8 4755 } 4756 4757 type R2 R1 4758 type R3 R1 4759 type R4 R1 4760 4761 type R5 struct { 4762 *R9 4763 *R10 4764 *R11 4765 *R12 4766 } 4767 4768 type R6 R5 4769 type R7 R5 4770 type R8 R5 4771 4772 type R9 struct { 4773 *R13 4774 *R14 4775 *R15 4776 *R16 4777 } 4778 4779 type R10 R9 4780 type R11 R9 4781 type R12 R9 4782 4783 type R13 struct { 4784 *R17 4785 *R18 4786 *R19 4787 *R20 4788 } 4789 4790 type R14 R13 4791 type R15 R13 4792 type R16 R13 4793 4794 type R17 struct { 4795 *R21 4796 *R22 4797 *R23 4798 *R24 4799 } 4800 4801 type R18 R17 4802 type R19 R17 4803 type R20 R17 4804 4805 type R21 struct { 4806 X int 4807 } 4808 4809 type R22 R21 4810 type R23 R21 4811 type R24 R21 4812 4813 func TestEmbed(t *testing.T) { 4814 typ := TypeOf(R0{}) 4815 f, ok := typ.FieldByName("X") 4816 if ok { 4817 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index) 4818 } 4819 } 4820 4821 func BenchmarkFieldByName3(b *testing.B) { 4822 t := TypeOf(R0{}) 4823 for i := 0; i < b.N; i++ { 4824 t.FieldByName("X") 4825 } 4826 } 4827 4828 type S struct { 4829 i1 int64 4830 i2 int64 4831 } 4832 4833 func BenchmarkInterfaceBig(b *testing.B) { 4834 v := ValueOf(S{}) 4835 for i := 0; i < b.N; i++ { 4836 v.Interface() 4837 } 4838 b.StopTimer() 4839 } 4840 4841 func TestAllocsInterfaceBig(t *testing.T) { 4842 if testing.Short() { 4843 t.Skip("skipping malloc count in short mode") 4844 } 4845 v := ValueOf(S{}) 4846 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { 4847 t.Error("allocs:", allocs) 4848 } 4849 } 4850 4851 func BenchmarkInterfaceSmall(b *testing.B) { 4852 v := ValueOf(int64(0)) 4853 for i := 0; i < b.N; i++ { 4854 v.Interface() 4855 } 4856 } 4857 4858 func TestAllocsInterfaceSmall(t *testing.T) { 4859 if testing.Short() { 4860 t.Skip("skipping malloc count in short mode") 4861 } 4862 v := ValueOf(int64(0)) 4863 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { 4864 t.Error("allocs:", allocs) 4865 } 4866 } 4867 4868 // An exhaustive is a mechanism for writing exhaustive or stochastic tests. 4869 // The basic usage is: 4870 // 4871 // for x.Next() { 4872 // ... code using x.Maybe() or x.Choice(n) to create test cases ... 4873 // } 4874 // 4875 // Each iteration of the loop returns a different set of results, until all 4876 // possible result sets have been explored. It is okay for different code paths 4877 // to make different method call sequences on x, but there must be no 4878 // other source of non-determinism in the call sequences. 4879 // 4880 // When faced with a new decision, x chooses randomly. Future explorations 4881 // of that path will choose successive values for the result. Thus, stopping 4882 // the loop after a fixed number of iterations gives somewhat stochastic 4883 // testing. 4884 // 4885 // Example: 4886 // 4887 // for x.Next() { 4888 // v := make([]bool, x.Choose(4)) 4889 // for i := range v { 4890 // v[i] = x.Maybe() 4891 // } 4892 // fmt.Println(v) 4893 // } 4894 // 4895 // prints (in some order): 4896 // 4897 // [] 4898 // [false] 4899 // [true] 4900 // [false false] 4901 // [false true] 4902 // ... 4903 // [true true] 4904 // [false false false] 4905 // ... 4906 // [true true true] 4907 // [false false false false] 4908 // ... 4909 // [true true true true] 4910 // 4911 type exhaustive struct { 4912 r *rand.Rand 4913 pos int 4914 last []choice 4915 } 4916 4917 type choice struct { 4918 off int 4919 n int 4920 max int 4921 } 4922 4923 func (x *exhaustive) Next() bool { 4924 if x.r == nil { 4925 x.r = rand.New(rand.NewSource(time.Now().UnixNano())) 4926 } 4927 x.pos = 0 4928 if x.last == nil { 4929 x.last = []choice{} 4930 return true 4931 } 4932 for i := len(x.last) - 1; i >= 0; i-- { 4933 c := &x.last[i] 4934 if c.n+1 < c.max { 4935 c.n++ 4936 x.last = x.last[:i+1] 4937 return true 4938 } 4939 } 4940 return false 4941 } 4942 4943 func (x *exhaustive) Choose(max int) int { 4944 if x.pos >= len(x.last) { 4945 x.last = append(x.last, choice{x.r.Intn(max), 0, max}) 4946 } 4947 c := &x.last[x.pos] 4948 x.pos++ 4949 if c.max != max { 4950 panic("inconsistent use of exhaustive tester") 4951 } 4952 return (c.n + c.off) % max 4953 } 4954 4955 func (x *exhaustive) Maybe() bool { 4956 return x.Choose(2) == 1 4957 } 4958 4959 func GCFunc(args []Value) []Value { 4960 runtime.GC() 4961 return []Value{} 4962 } 4963 4964 func TestReflectFuncTraceback(t *testing.T) { 4965 f := MakeFunc(TypeOf(func() {}), GCFunc) 4966 f.Call([]Value{}) 4967 } 4968 4969 func TestReflectMethodTraceback(t *testing.T) { 4970 p := Point{3, 4} 4971 m := ValueOf(p).MethodByName("GCMethod") 4972 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int() 4973 if i != 8 { 4974 t.Errorf("Call returned %d; want 8", i) 4975 } 4976 } 4977 4978 func TestBigZero(t *testing.T) { 4979 const size = 1 << 10 4980 var v [size]byte 4981 z := Zero(ValueOf(v).Type()).Interface().([size]byte) 4982 for i := 0; i < size; i++ { 4983 if z[i] != 0 { 4984 t.Fatalf("Zero object not all zero, index %d", i) 4985 } 4986 } 4987 } 4988 4989 func TestFieldByIndexNil(t *testing.T) { 4990 type P struct { 4991 F int 4992 } 4993 type T struct { 4994 *P 4995 } 4996 v := ValueOf(T{}) 4997 4998 v.FieldByName("P") // should be fine 4999 5000 defer func() { 5001 if err := recover(); err == nil { 5002 t.Fatalf("no error") 5003 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") { 5004 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err) 5005 } 5006 }() 5007 v.FieldByName("F") // should panic 5008 5009 t.Fatalf("did not panic") 5010 } 5011 5012 // Given 5013 // type Outer struct { 5014 // *Inner 5015 // ... 5016 // } 5017 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner. 5018 // The implementation is logically: 5019 // func (p *Outer) M() { 5020 // (p.Inner).M() 5021 // } 5022 // but since the only change here is the replacement of one pointer receiver with another, 5023 // the actual generated code overwrites the original receiver with the p.Inner pointer and 5024 // then jumps to the M method expecting the *Inner receiver. 5025 // 5026 // During reflect.Value.Call, we create an argument frame and the associated data structures 5027 // to describe it to the garbage collector, populate the frame, call reflect.call to 5028 // run a function call using that frame, and then copy the results back out of the frame. 5029 // The reflect.call function does a memmove of the frame structure onto the 5030 // stack (to set up the inputs), runs the call, and the memmoves the stack back to 5031 // the frame structure (to preserve the outputs). 5032 // 5033 // Originally reflect.call did not distinguish inputs from outputs: both memmoves 5034 // were for the full stack frame. However, in the case where the called function was 5035 // one of these wrappers, the rewritten receiver is almost certainly a different type 5036 // than the original receiver. This is not a problem on the stack, where we use the 5037 // program counter to determine the type information and understand that 5038 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same 5039 // memory word is now an *Inner. But in the statically typed argument frame created 5040 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer 5041 // off the stack into the frame will store an *Inner there, and then if a garbage collection 5042 // happens to scan that argument frame before it is discarded, it will scan the *Inner 5043 // memory as if it were an *Outer. If the two have different memory layouts, the 5044 // collection will interpret the memory incorrectly. 5045 // 5046 // One such possible incorrect interpretation is to treat two arbitrary memory words 5047 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting 5048 // an interface requires dereferencing the itab word, the misinterpretation will try to 5049 // deference Inner.P1, causing a crash during garbage collection. 5050 // 5051 // This came up in a real program in issue 7725. 5052 5053 type Outer struct { 5054 *Inner 5055 R io.Reader 5056 } 5057 5058 type Inner struct { 5059 X *Outer 5060 P1 uintptr 5061 P2 uintptr 5062 } 5063 5064 func (pi *Inner) M() { 5065 // Clear references to pi so that the only way the 5066 // garbage collection will find the pointer is in the 5067 // argument frame, typed as a *Outer. 5068 pi.X.Inner = nil 5069 5070 // Set up an interface value that will cause a crash. 5071 // P1 = 1 is a non-zero, so the interface looks non-nil. 5072 // P2 = pi ensures that the data word points into the 5073 // allocated heap; if not the collection skips the interface 5074 // value as irrelevant, without dereferencing P1. 5075 pi.P1 = 1 5076 pi.P2 = uintptr(unsafe.Pointer(pi)) 5077 } 5078 5079 func TestCallMethodJump(t *testing.T) { 5080 // In reflect.Value.Call, trigger a garbage collection after reflect.call 5081 // returns but before the args frame has been discarded. 5082 // This is a little clumsy but makes the failure repeatable. 5083 *CallGC = true 5084 5085 p := &Outer{Inner: new(Inner)} 5086 p.Inner.X = p 5087 ValueOf(p).Method(0).Call(nil) 5088 5089 // Stop garbage collecting during reflect.call. 5090 *CallGC = false 5091 } 5092 5093 func TestMakeFuncStackCopy(t *testing.T) { 5094 target := func(in []Value) []Value { 5095 runtime.GC() 5096 useStack(16) 5097 return []Value{ValueOf(9)} 5098 } 5099 5100 var concrete func(*int, int) int 5101 fn := MakeFunc(ValueOf(concrete).Type(), target) 5102 ValueOf(&concrete).Elem().Set(fn) 5103 x := concrete(nil, 7) 5104 if x != 9 { 5105 t.Errorf("have %#q want 9", x) 5106 } 5107 } 5108 5109 // use about n KB of stack 5110 func useStack(n int) { 5111 if n == 0 { 5112 return 5113 } 5114 var b [1024]byte // makes frame about 1KB 5115 useStack(n - 1 + int(b[99])) 5116 } 5117 5118 type Impl struct{} 5119 5120 func (Impl) F() {} 5121 5122 func TestValueString(t *testing.T) { 5123 rv := ValueOf(Impl{}) 5124 if rv.String() != "<reflect_test.Impl Value>" { 5125 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>") 5126 } 5127 5128 method := rv.Method(0) 5129 if method.String() != "<func() Value>" { 5130 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>") 5131 } 5132 } 5133 5134 func TestInvalid(t *testing.T) { 5135 // Used to have inconsistency between IsValid() and Kind() != Invalid. 5136 type T struct{ v interface{} } 5137 5138 v := ValueOf(T{}).Field(0) 5139 if v.IsValid() != true || v.Kind() != Interface { 5140 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind()) 5141 } 5142 v = v.Elem() 5143 if v.IsValid() != false || v.Kind() != Invalid { 5144 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind()) 5145 } 5146 } 5147 5148 // Issue 8917. 5149 func TestLargeGCProg(t *testing.T) { 5150 fv := ValueOf(func([256]*byte) {}) 5151 fv.Call([]Value{ValueOf([256]*byte{})}) 5152 } 5153 5154 func fieldIndexRecover(t Type, i int) (recovered interface{}) { 5155 defer func() { 5156 recovered = recover() 5157 }() 5158 5159 t.Field(i) 5160 return 5161 } 5162 5163 // Issue 15046. 5164 func TestTypeFieldOutOfRangePanic(t *testing.T) { 5165 typ := TypeOf(struct{ X int }{10}) 5166 testIndices := [...]struct { 5167 i int 5168 mustPanic bool 5169 }{ 5170 0: {-2, true}, 5171 1: {0, false}, 5172 2: {1, true}, 5173 3: {1 << 10, true}, 5174 } 5175 for i, tt := range testIndices { 5176 recoveredErr := fieldIndexRecover(typ, tt.i) 5177 if tt.mustPanic { 5178 if recoveredErr == nil { 5179 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i) 5180 } 5181 } else { 5182 if recoveredErr != nil { 5183 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr) 5184 } 5185 } 5186 } 5187 } 5188 5189 // Issue 9179. 5190 func TestCallGC(t *testing.T) { 5191 f := func(a, b, c, d, e string) { 5192 } 5193 g := func(in []Value) []Value { 5194 runtime.GC() 5195 return nil 5196 } 5197 typ := ValueOf(f).Type() 5198 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string)) 5199 f2("four", "five5", "six666", "seven77", "eight888") 5200 } 5201 5202 type funcLayoutTest struct { 5203 rcvr, t Type 5204 size, argsize, retOffset uintptr 5205 stack []byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized) 5206 gc []byte 5207 } 5208 5209 var funcLayoutTests []funcLayoutTest 5210 5211 func init() { 5212 var argAlign uintptr = PtrSize 5213 if runtime.GOARCH == "amd64p32" { 5214 argAlign = 2 * PtrSize 5215 } 5216 roundup := func(x uintptr, a uintptr) uintptr { 5217 return (x + a - 1) / a * a 5218 } 5219 5220 funcLayoutTests = append(funcLayoutTests, 5221 funcLayoutTest{ 5222 nil, 5223 ValueOf(func(a, b string) string { return "" }).Type(), 5224 6 * PtrSize, 5225 4 * PtrSize, 5226 4 * PtrSize, 5227 []byte{1, 0, 1}, 5228 []byte{1, 0, 1, 0, 1}, 5229 }) 5230 5231 var r []byte 5232 if PtrSize == 4 { 5233 r = []byte{0, 0, 0, 1} 5234 } else { 5235 r = []byte{0, 0, 1} 5236 } 5237 funcLayoutTests = append(funcLayoutTests, 5238 funcLayoutTest{ 5239 nil, 5240 ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(), 5241 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign), 5242 roundup(3*4, PtrSize) + PtrSize + 2, 5243 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign), 5244 r, 5245 r, 5246 }) 5247 5248 funcLayoutTests = append(funcLayoutTests, 5249 funcLayoutTest{ 5250 nil, 5251 ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(), 5252 4 * PtrSize, 5253 4 * PtrSize, 5254 4 * PtrSize, 5255 []byte{1, 0, 1, 1}, 5256 []byte{1, 0, 1, 1}, 5257 }) 5258 5259 type S struct { 5260 a, b uintptr 5261 c, d *byte 5262 } 5263 funcLayoutTests = append(funcLayoutTests, 5264 funcLayoutTest{ 5265 nil, 5266 ValueOf(func(a S) {}).Type(), 5267 4 * PtrSize, 5268 4 * PtrSize, 5269 4 * PtrSize, 5270 []byte{0, 0, 1, 1}, 5271 []byte{0, 0, 1, 1}, 5272 }) 5273 5274 funcLayoutTests = append(funcLayoutTests, 5275 funcLayoutTest{ 5276 ValueOf((*byte)(nil)).Type(), 5277 ValueOf(func(a uintptr, b *int) {}).Type(), 5278 roundup(3*PtrSize, argAlign), 5279 3 * PtrSize, 5280 roundup(3*PtrSize, argAlign), 5281 []byte{1, 0, 1}, 5282 []byte{1, 0, 1}, 5283 }) 5284 5285 funcLayoutTests = append(funcLayoutTests, 5286 funcLayoutTest{ 5287 nil, 5288 ValueOf(func(a uintptr) {}).Type(), 5289 roundup(PtrSize, argAlign), 5290 PtrSize, 5291 roundup(PtrSize, argAlign), 5292 []byte{}, 5293 []byte{}, 5294 }) 5295 5296 funcLayoutTests = append(funcLayoutTests, 5297 funcLayoutTest{ 5298 nil, 5299 ValueOf(func() uintptr { return 0 }).Type(), 5300 PtrSize, 5301 0, 5302 0, 5303 []byte{}, 5304 []byte{}, 5305 }) 5306 5307 funcLayoutTests = append(funcLayoutTests, 5308 funcLayoutTest{ 5309 ValueOf(uintptr(0)).Type(), 5310 ValueOf(func(a uintptr) {}).Type(), 5311 2 * PtrSize, 5312 2 * PtrSize, 5313 2 * PtrSize, 5314 []byte{1}, 5315 []byte{1}, 5316 // Note: this one is tricky, as the receiver is not a pointer. But we 5317 // pass the receiver by reference to the autogenerated pointer-receiver 5318 // version of the function. 5319 }) 5320 } 5321 5322 func TestFuncLayout(t *testing.T) { 5323 for _, lt := range funcLayoutTests { 5324 typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr) 5325 if typ.Size() != lt.size { 5326 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size) 5327 } 5328 if argsize != lt.argsize { 5329 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize) 5330 } 5331 if retOffset != lt.retOffset { 5332 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset) 5333 } 5334 if !bytes.Equal(stack, lt.stack) { 5335 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack) 5336 } 5337 if !bytes.Equal(gc, lt.gc) { 5338 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc) 5339 } 5340 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 { 5341 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs) 5342 } 5343 } 5344 } 5345 5346 func verifyGCBits(t *testing.T, typ Type, bits []byte) { 5347 heapBits := GCBits(New(typ).Interface()) 5348 if !bytes.Equal(heapBits, bits) { 5349 t.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ, heapBits, bits) 5350 } 5351 } 5352 5353 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) { 5354 // Creating a slice causes the runtime to repeat a bitmap, 5355 // which exercises a different path from making the compiler 5356 // repeat a bitmap for a small array or executing a repeat in 5357 // a GC program. 5358 val := MakeSlice(typ, 0, cap) 5359 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer())) 5360 heapBits := GCBits(data.Interface()) 5361 // Repeat the bitmap for the slice size, trimming scalars in 5362 // the last element. 5363 bits = rep(cap, bits) 5364 for len(bits) > 2 && bits[len(bits)-1] == 0 { 5365 bits = bits[:len(bits)-1] 5366 } 5367 if len(bits) == 2 && bits[0] == 0 && bits[1] == 0 { 5368 bits = bits[:0] 5369 } 5370 if !bytes.Equal(heapBits, bits) { 5371 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits) 5372 } 5373 } 5374 5375 func TestGCBits(t *testing.T) { 5376 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1}) 5377 5378 // Building blocks for types seen by the compiler (like [2]Xscalar). 5379 // The compiler will create the type structures for the derived types, 5380 // including their GC metadata. 5381 type Xscalar struct{ x uintptr } 5382 type Xptr struct{ x *byte } 5383 type Xptrscalar struct { 5384 *byte 5385 uintptr 5386 } 5387 type Xscalarptr struct { 5388 uintptr 5389 *byte 5390 } 5391 type Xbigptrscalar struct { 5392 _ [100]*byte 5393 _ [100]uintptr 5394 } 5395 5396 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type 5397 { 5398 // Building blocks for types constructed by reflect. 5399 // This code is in a separate block so that code below 5400 // cannot accidentally refer to these. 5401 // The compiler must NOT see types derived from these 5402 // (for example, [2]Scalar must NOT appear in the program), 5403 // or else reflect will use it instead of having to construct one. 5404 // The goal is to test the construction. 5405 type Scalar struct{ x uintptr } 5406 type Ptr struct{ x *byte } 5407 type Ptrscalar struct { 5408 *byte 5409 uintptr 5410 } 5411 type Scalarptr struct { 5412 uintptr 5413 *byte 5414 } 5415 type Bigptrscalar struct { 5416 _ [100]*byte 5417 _ [100]uintptr 5418 } 5419 type Int64 int64 5420 Tscalar = TypeOf(Scalar{}) 5421 Tint64 = TypeOf(Int64(0)) 5422 Tptr = TypeOf(Ptr{}) 5423 Tscalarptr = TypeOf(Scalarptr{}) 5424 Tptrscalar = TypeOf(Ptrscalar{}) 5425 Tbigptrscalar = TypeOf(Bigptrscalar{}) 5426 } 5427 5428 empty := []byte{} 5429 5430 verifyGCBits(t, TypeOf(Xscalar{}), empty) 5431 verifyGCBits(t, Tscalar, empty) 5432 verifyGCBits(t, TypeOf(Xptr{}), lit(1)) 5433 verifyGCBits(t, Tptr, lit(1)) 5434 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1)) 5435 verifyGCBits(t, Tscalarptr, lit(0, 1)) 5436 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1)) 5437 verifyGCBits(t, Tptrscalar, lit(1)) 5438 5439 verifyGCBits(t, TypeOf([0]Xptr{}), empty) 5440 verifyGCBits(t, ArrayOf(0, Tptr), empty) 5441 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1)) 5442 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1)) 5443 verifyGCBits(t, TypeOf([2]Xscalar{}), empty) 5444 verifyGCBits(t, ArrayOf(2, Tscalar), empty) 5445 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty) 5446 verifyGCBits(t, ArrayOf(10000, Tscalar), empty) 5447 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1)) 5448 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1)) 5449 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1))) 5450 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1))) 5451 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1)) 5452 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1)) 5453 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1))) 5454 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1))) 5455 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1)) 5456 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1)) 5457 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0))) 5458 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0))) 5459 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0))) 5460 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0))) 5461 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0))) 5462 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0))) 5463 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) 5464 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) 5465 5466 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty) 5467 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty) 5468 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1)) 5469 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1)) 5470 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0)) 5471 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0)) 5472 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0)) 5473 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0)) 5474 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1)) 5475 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1)) 5476 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1)) 5477 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1)) 5478 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1)) 5479 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1)) 5480 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1)) 5481 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1)) 5482 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0)) 5483 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0)) 5484 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0)) 5485 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0)) 5486 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0))) 5487 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0))) 5488 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0))) 5489 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0))) 5490 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0)))) 5491 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0)))) 5492 5493 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1)) 5494 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1)) 5495 5496 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1)) 5497 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1)) 5498 5499 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1)) 5500 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1)) 5501 5502 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1)) 5503 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1)) 5504 5505 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1)) 5506 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1)) 5507 5508 hdr := make([]byte, 8/PtrSize) 5509 5510 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) { 5511 verifyGCBits(t, MapBucketOf(k, e), want) 5512 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want) 5513 } 5514 verifyMapBucket(t, 5515 Tscalar, Tptr, 5516 map[Xscalar]Xptr(nil), 5517 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1))) 5518 verifyMapBucket(t, 5519 Tscalarptr, Tptr, 5520 map[Xscalarptr]Xptr(nil), 5521 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1))) 5522 verifyMapBucket(t, Tint64, Tptr, 5523 map[int64]Xptr(nil), 5524 join(hdr, rep(8, rep(8/PtrSize, lit(0))), rep(8, lit(1)), naclpad(), lit(1))) 5525 verifyMapBucket(t, 5526 Tscalar, Tscalar, 5527 map[Xscalar]Xscalar(nil), 5528 empty) 5529 verifyMapBucket(t, 5530 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar), 5531 map[[2]Xscalarptr][3]Xptrscalar(nil), 5532 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1))) 5533 verifyMapBucket(t, 5534 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar), 5535 map[[64 / PtrSize]Xscalarptr][64 / PtrSize]Xptrscalar(nil), 5536 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8*64/PtrSize, lit(1, 0)), lit(1))) 5537 verifyMapBucket(t, 5538 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar), 5539 map[[64/PtrSize + 1]Xscalarptr][64 / PtrSize]Xptrscalar(nil), 5540 join(hdr, rep(8, lit(1)), rep(8*64/PtrSize, lit(1, 0)), lit(1))) 5541 verifyMapBucket(t, 5542 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar), 5543 map[[64 / PtrSize]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil), 5544 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1))) 5545 verifyMapBucket(t, 5546 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar), 5547 map[[64/PtrSize + 1]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil), 5548 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1))) 5549 } 5550 5551 func naclpad() []byte { 5552 if runtime.GOARCH == "amd64p32" { 5553 return lit(0) 5554 } 5555 return nil 5556 } 5557 5558 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) } 5559 func join(b ...[]byte) []byte { return bytes.Join(b, nil) } 5560 func lit(x ...byte) []byte { return x } 5561 5562 func TestTypeOfTypeOf(t *testing.T) { 5563 // Check that all the type constructors return concrete *rtype implementations. 5564 // It's difficult to test directly because the reflect package is only at arm's length. 5565 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype. 5566 check := func(name string, typ Type) { 5567 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" { 5568 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying) 5569 } 5570 } 5571 5572 type T struct{ int } 5573 check("TypeOf", TypeOf(T{})) 5574 5575 check("ArrayOf", ArrayOf(10, TypeOf(T{}))) 5576 check("ChanOf", ChanOf(BothDir, TypeOf(T{}))) 5577 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false)) 5578 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{}))) 5579 check("PtrTo", PtrTo(TypeOf(T{}))) 5580 check("SliceOf", SliceOf(TypeOf(T{}))) 5581 } 5582 5583 type XM struct{} 5584 5585 func (*XM) String() string { return "" } 5586 5587 func TestPtrToMethods(t *testing.T) { 5588 var y struct{ XM } 5589 yp := New(TypeOf(y)).Interface() 5590 _, ok := yp.(fmt.Stringer) 5591 if !ok { 5592 t.Fatal("does not implement Stringer, but should") 5593 } 5594 } 5595 5596 func TestMapAlloc(t *testing.T) { 5597 m := ValueOf(make(map[int]int, 10)) 5598 k := ValueOf(5) 5599 v := ValueOf(7) 5600 allocs := testing.AllocsPerRun(100, func() { 5601 m.SetMapIndex(k, v) 5602 }) 5603 if allocs > 0.5 { 5604 t.Errorf("allocs per map assignment: want 0 got %f", allocs) 5605 } 5606 } 5607 5608 func TestChanAlloc(t *testing.T) { 5609 // Note: for a chan int, the return Value must be allocated, so we 5610 // use a chan *int instead. 5611 c := ValueOf(make(chan *int, 1)) 5612 v := ValueOf(new(int)) 5613 allocs := testing.AllocsPerRun(100, func() { 5614 c.Send(v) 5615 _, _ = c.Recv() 5616 }) 5617 if allocs < 0.5 || allocs > 1.5 { 5618 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs) 5619 } 5620 // Note: there is one allocation in reflect.recv which seems to be 5621 // a limitation of escape analysis. If that is ever fixed the 5622 // allocs < 0.5 condition will trigger and this test should be fixed. 5623 } 5624 5625 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int 5626 5627 type nameTest struct { 5628 v interface{} 5629 want string 5630 } 5631 5632 var nameTests = []nameTest{ 5633 {(*int32)(nil), "int32"}, 5634 {(*D1)(nil), "D1"}, 5635 {(*[]D1)(nil), ""}, 5636 {(*chan D1)(nil), ""}, 5637 {(*func() D1)(nil), ""}, 5638 {(*<-chan D1)(nil), ""}, 5639 {(*chan<- D1)(nil), ""}, 5640 {(*interface{})(nil), ""}, 5641 {(*interface { 5642 F() 5643 })(nil), ""}, 5644 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"}, 5645 } 5646 5647 func TestNames(t *testing.T) { 5648 for _, test := range nameTests { 5649 typ := TypeOf(test.v).Elem() 5650 if got := typ.Name(); got != test.want { 5651 t.Errorf("%v Name()=%q, want %q", typ, got, test.want) 5652 } 5653 } 5654 } 5655 5656 func TestExported(t *testing.T) { 5657 type ΦExported struct{} 5658 type φUnexported struct{} 5659 type BigP *big 5660 type P int 5661 type p *P 5662 type P2 p 5663 type p3 p 5664 5665 type exportTest struct { 5666 v interface{} 5667 want bool 5668 } 5669 exportTests := []exportTest{ 5670 {D1{}, true}, 5671 {(*D1)(nil), true}, 5672 {big{}, false}, 5673 {(*big)(nil), false}, 5674 {(BigP)(nil), true}, 5675 {(*BigP)(nil), true}, 5676 {ΦExported{}, true}, 5677 {φUnexported{}, false}, 5678 {P(0), true}, 5679 {(p)(nil), false}, 5680 {(P2)(nil), true}, 5681 {(p3)(nil), false}, 5682 } 5683 5684 for i, test := range exportTests { 5685 typ := TypeOf(test.v) 5686 if got := IsExported(typ); got != test.want { 5687 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want) 5688 } 5689 } 5690 } 5691 5692 type embed struct { 5693 EmbedWithUnexpMeth 5694 } 5695 5696 func TestNameBytesAreAligned(t *testing.T) { 5697 typ := TypeOf(embed{}) 5698 b := FirstMethodNameBytes(typ) 5699 v := uintptr(unsafe.Pointer(b)) 5700 if v%unsafe.Alignof((*byte)(nil)) != 0 { 5701 t.Errorf("reflect.name.bytes pointer is not aligned: %x", v) 5702 } 5703 } 5704 5705 func TestTypeStrings(t *testing.T) { 5706 type stringTest struct { 5707 typ Type 5708 want string 5709 } 5710 stringTests := []stringTest{ 5711 {TypeOf(func(int) {}), "func(int)"}, 5712 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"}, 5713 {TypeOf(XM{}), "reflect_test.XM"}, 5714 {TypeOf(new(XM)), "*reflect_test.XM"}, 5715 {TypeOf(new(XM).String), "func() string"}, 5716 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"}, 5717 } 5718 5719 for i, test := range stringTests { 5720 if got, want := test.typ.String(), test.want; got != want { 5721 t.Errorf("type %d String()=%q, want %q", i, got, want) 5722 } 5723 } 5724 } 5725 5726 func TestOffsetLock(t *testing.T) { 5727 var wg sync.WaitGroup 5728 for i := 0; i < 4; i++ { 5729 i := i 5730 wg.Add(1) 5731 go func() { 5732 for j := 0; j < 50; j++ { 5733 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j)) 5734 } 5735 wg.Done() 5736 }() 5737 } 5738 wg.Wait() 5739 }