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