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