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