| 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 |
"go/token" |
| 13 |
"internal/goarch" |
| 14 |
"io" |
| 15 |
"math" |
| 16 |
"math/rand" |
| 17 |
"os" |
| 18 |
. "reflect" |
| 19 |
"reflect/internal/example1" |
| 20 |
"reflect/internal/example2" |
| 21 |
"runtime" |
| 22 |
"sort" |
| 23 |
"strconv" |
| 24 |
"strings" |
| 25 |
"sync" |
| 26 |
"sync/atomic" |
| 27 |
"testing" |
| 28 |
"time" |
| 29 |
"unsafe" |
| 30 |
) |
| 31 |
|
| 32 |
var sink any |
| 33 |
|
| 34 |
func TestBool(t *testing.T) { |
| 35 |
v := ValueOf(true) |
| 36 |
if v.Bool() != true { |
| 37 |
t.Fatal("ValueOf(true).Bool() = false") |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
type integer int |
| 42 |
type T struct { |
| 43 |
a int |
| 44 |
b float64 |
| 45 |
c string |
| 46 |
d *int |
| 47 |
} |
| 48 |
|
| 49 |
type pair struct { |
| 50 |
i any |
| 51 |
s string |
| 52 |
} |
| 53 |
|
| 54 |
func assert(t *testing.T, s, want string) { |
| 55 |
if s != want { |
| 56 |
t.Errorf("have %#q want %#q", s, want) |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
var typeTests = []pair{ |
| 61 |
{struct{ x int }{}, "int"}, |
| 62 |
{struct{ x int8 }{}, "int8"}, |
| 63 |
{struct{ x int16 }{}, "int16"}, |
| 64 |
{struct{ x int32 }{}, "int32"}, |
| 65 |
{struct{ x int64 }{}, "int64"}, |
| 66 |
{struct{ x uint }{}, "uint"}, |
| 67 |
{struct{ x uint8 }{}, "uint8"}, |
| 68 |
{struct{ x uint16 }{}, "uint16"}, |
| 69 |
{struct{ x uint32 }{}, "uint32"}, |
| 70 |
{struct{ x uint64 }{}, "uint64"}, |
| 71 |
{struct{ x float32 }{}, "float32"}, |
| 72 |
{struct{ x float64 }{}, "float64"}, |
| 73 |
{struct{ x int8 }{}, "int8"}, |
| 74 |
{struct{ x (**int8) }{}, "**int8"}, |
| 75 |
{struct{ x (**integer) }{}, "**reflect_test.integer"}, |
| 76 |
{struct{ x ([32]int32) }{}, "[32]int32"}, |
| 77 |
{struct{ x ([]int8) }{}, "[]int8"}, |
| 78 |
{struct{ x (map[string]int32) }{}, "map[string]int32"}, |
| 79 |
{struct{ x (chan<- string) }{}, "chan<- string"}, |
| 80 |
{struct{ x (chan<- chan string) }{}, "chan<- chan string"}, |
| 81 |
{struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"}, |
| 82 |
{struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"}, |
| 83 |
{struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"}, |
| 84 |
{struct { |
| 85 |
x struct { |
| 86 |
c chan *int32 |
| 87 |
d float32 |
| 88 |
} |
| 89 |
}{}, |
| 90 |
"struct { c chan *int32; d float32 }", |
| 91 |
}, |
| 92 |
{struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"}, |
| 93 |
{struct { |
| 94 |
x struct { |
| 95 |
c func(chan *integer, *int8) |
| 96 |
} |
| 97 |
}{}, |
| 98 |
"struct { c func(chan *reflect_test.integer, *int8) }", |
| 99 |
}, |
| 100 |
{struct { |
| 101 |
x struct { |
| 102 |
a int8 |
| 103 |
b int32 |
| 104 |
} |
| 105 |
}{}, |
| 106 |
"struct { a int8; b int32 }", |
| 107 |
}, |
| 108 |
{struct { |
| 109 |
x struct { |
| 110 |
a int8 |
| 111 |
b int8 |
| 112 |
c int32 |
| 113 |
} |
| 114 |
}{}, |
| 115 |
"struct { a int8; b int8; c int32 }", |
| 116 |
}, |
| 117 |
{struct { |
| 118 |
x struct { |
| 119 |
a int8 |
| 120 |
b int8 |
| 121 |
c int8 |
| 122 |
d int32 |
| 123 |
} |
| 124 |
}{}, |
| 125 |
"struct { a int8; b int8; c int8; d int32 }", |
| 126 |
}, |
| 127 |
{struct { |
| 128 |
x struct { |
| 129 |
a int8 |
| 130 |
b int8 |
| 131 |
c int8 |
| 132 |
d int8 |
| 133 |
e int32 |
| 134 |
} |
| 135 |
}{}, |
| 136 |
"struct { a int8; b int8; c int8; d int8; e int32 }", |
| 137 |
}, |
| 138 |
{struct { |
| 139 |
x struct { |
| 140 |
a int8 |
| 141 |
b int8 |
| 142 |
c int8 |
| 143 |
d int8 |
| 144 |
e int8 |
| 145 |
f int32 |
| 146 |
} |
| 147 |
}{}, |
| 148 |
"struct { a int8; b int8; c int8; d int8; e int8; f int32 }", |
| 149 |
}, |
| 150 |
{struct { |
| 151 |
x struct { |
| 152 |
a int8 `reflect:"hi there"` |
| 153 |
} |
| 154 |
}{}, |
| 155 |
`struct { a int8 "reflect:\"hi there\"" }`, |
| 156 |
}, |
| 157 |
{struct { |
| 158 |
x struct { |
| 159 |
a int8 `reflect:"hi \x00there\t\n\"\\"` |
| 160 |
} |
| 161 |
}{}, |
| 162 |
`struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`, |
| 163 |
}, |
| 164 |
{struct { |
| 165 |
x struct { |
| 166 |
f func(args ...int) |
| 167 |
} |
| 168 |
}{}, |
| 169 |
"struct { f func(...int) }", |
| 170 |
}, |
| 171 |
{struct { |
| 172 |
x (interface { |
| 173 |
a(func(func(int) int) func(func(int)) int) |
| 174 |
b() |
| 175 |
}) |
| 176 |
}{}, |
| 177 |
"interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }", |
| 178 |
}, |
| 179 |
{struct { |
| 180 |
x struct { |
| 181 |
int32 |
| 182 |
int64 |
| 183 |
} |
| 184 |
}{}, |
| 185 |
"struct { int32; int64 }", |
| 186 |
}, |
| 187 |
} |
| 188 |
|
| 189 |
var valueTests = []pair{ |
| 190 |
{new(int), "132"}, |
| 191 |
{new(int8), "8"}, |
| 192 |
{new(int16), "16"}, |
| 193 |
{new(int32), "32"}, |
| 194 |
{new(int64), "64"}, |
| 195 |
{new(uint), "132"}, |
| 196 |
{new(uint8), "8"}, |
| 197 |
{new(uint16), "16"}, |
| 198 |
{new(uint32), "32"}, |
| 199 |
{new(uint64), "64"}, |
| 200 |
{new(float32), "256.25"}, |
| 201 |
{new(float64), "512.125"}, |
| 202 |
{new(complex64), "532.125+10i"}, |
| 203 |
{new(complex128), "564.25+1i"}, |
| 204 |
{new(string), "stringy cheese"}, |
| 205 |
{new(bool), "true"}, |
| 206 |
{new(*int8), "*int8(0)"}, |
| 207 |
{new(**int8), "**int8(0)"}, |
| 208 |
{new([5]int32), "[5]int32{0, 0, 0, 0, 0}"}, |
| 209 |
{new(**integer), "**reflect_test.integer(0)"}, |
| 210 |
{new(map[string]int32), "map[string]int32{<can't iterate on maps>}"}, |
| 211 |
{new(chan<- string), "chan<- string"}, |
| 212 |
{new(func(a int8, b int32)), "func(int8, int32)(0)"}, |
| 213 |
{new(struct { |
| 214 |
c chan *int32 |
| 215 |
d float32 |
| 216 |
}), |
| 217 |
"struct { c chan *int32; d float32 }{chan *int32, 0}", |
| 218 |
}, |
| 219 |
{new(struct{ c func(chan *integer, *int8) }), |
| 220 |
"struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}", |
| 221 |
}, |
| 222 |
{new(struct { |
| 223 |
a int8 |
| 224 |
b int32 |
| 225 |
}), |
| 226 |
"struct { a int8; b int32 }{0, 0}", |
| 227 |
}, |
| 228 |
{new(struct { |
| 229 |
a int8 |
| 230 |
b int8 |
| 231 |
c int32 |
| 232 |
}), |
| 233 |
"struct { a int8; b int8; c int32 }{0, 0, 0}", |
| 234 |
}, |
| 235 |
} |
| 236 |
|
| 237 |
func testType(t *testing.T, i int, typ Type, want string) { |
| 238 |
s := typ.String() |
| 239 |
if s != want { |
| 240 |
t.Errorf("#%d: have %#q, want %#q", i, s, want) |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
func TestTypes(t *testing.T) { |
| 245 |
for i, tt := range typeTests { |
| 246 |
testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s) |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
func TestSet(t *testing.T) { |
| 251 |
for i, tt := range valueTests { |
| 252 |
v := ValueOf(tt.i) |
| 253 |
v = v.Elem() |
| 254 |
switch v.Kind() { |
| 255 |
case Int: |
| 256 |
v.SetInt(132) |
| 257 |
case Int8: |
| 258 |
v.SetInt(8) |
| 259 |
case Int16: |
| 260 |
v.SetInt(16) |
| 261 |
case Int32: |
| 262 |
v.SetInt(32) |
| 263 |
case Int64: |
| 264 |
v.SetInt(64) |
| 265 |
case Uint: |
| 266 |
v.SetUint(132) |
| 267 |
case Uint8: |
| 268 |
v.SetUint(8) |
| 269 |
case Uint16: |
| 270 |
v.SetUint(16) |
| 271 |
case Uint32: |
| 272 |
v.SetUint(32) |
| 273 |
case Uint64: |
| 274 |
v.SetUint(64) |
| 275 |
case Float32: |
| 276 |
v.SetFloat(256.25) |
| 277 |
case Float64: |
| 278 |
v.SetFloat(512.125) |
| 279 |
case Complex64: |
| 280 |
v.SetComplex(532.125 + 10i) |
| 281 |
case Complex128: |
| 282 |
v.SetComplex(564.25 + 1i) |
| 283 |
case String: |
| 284 |
v.SetString("stringy cheese") |
| 285 |
case Bool: |
| 286 |
v.SetBool(true) |
| 287 |
} |
| 288 |
s := valueToString(v) |
| 289 |
if s != tt.s { |
| 290 |
t.Errorf("#%d: have %#q, want %#q", i, s, tt.s) |
| 291 |
} |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
func TestSetValue(t *testing.T) { |
| 296 |
for i, tt := range valueTests { |
| 297 |
v := ValueOf(tt.i).Elem() |
| 298 |
switch v.Kind() { |
| 299 |
case Int: |
| 300 |
v.Set(ValueOf(int(132))) |
| 301 |
case Int8: |
| 302 |
v.Set(ValueOf(int8(8))) |
| 303 |
case Int16: |
| 304 |
v.Set(ValueOf(int16(16))) |
| 305 |
case Int32: |
| 306 |
v.Set(ValueOf(int32(32))) |
| 307 |
case Int64: |
| 308 |
v.Set(ValueOf(int64(64))) |
| 309 |
case Uint: |
| 310 |
v.Set(ValueOf(uint(132))) |
| 311 |
case Uint8: |
| 312 |
v.Set(ValueOf(uint8(8))) |
| 313 |
case Uint16: |
| 314 |
v.Set(ValueOf(uint16(16))) |
| 315 |
case Uint32: |
| 316 |
v.Set(ValueOf(uint32(32))) |
| 317 |
case Uint64: |
| 318 |
v.Set(ValueOf(uint64(64))) |
| 319 |
case Float32: |
| 320 |
v.Set(ValueOf(float32(256.25))) |
| 321 |
case Float64: |
| 322 |
v.Set(ValueOf(512.125)) |
| 323 |
case Complex64: |
| 324 |
v.Set(ValueOf(complex64(532.125 + 10i))) |
| 325 |
case Complex128: |
| 326 |
v.Set(ValueOf(complex128(564.25 + 1i))) |
| 327 |
case String: |
| 328 |
v.Set(ValueOf("stringy cheese")) |
| 329 |
case Bool: |
| 330 |
v.Set(ValueOf(true)) |
| 331 |
} |
| 332 |
s := valueToString(v) |
| 333 |
if s != tt.s { |
| 334 |
t.Errorf("#%d: have %#q, want %#q", i, s, tt.s) |
| 335 |
} |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
func TestMapIterSet(t *testing.T) { |
| 340 |
m := make(map[string]any, len(valueTests)) |
| 341 |
for _, tt := range valueTests { |
| 342 |
m[tt.s] = tt.i |
| 343 |
} |
| 344 |
v := ValueOf(m) |
| 345 |
|
| 346 |
k := New(v.Type().Key()).Elem() |
| 347 |
e := New(v.Type().Elem()).Elem() |
| 348 |
|
| 349 |
iter := v.MapRange() |
| 350 |
for iter.Next() { |
| 351 |
k.SetIterKey(iter) |
| 352 |
e.SetIterValue(iter) |
| 353 |
want := m[k.String()] |
| 354 |
got := e.Interface() |
| 355 |
if got != want { |
| 356 |
t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got) |
| 357 |
} |
| 358 |
if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key { |
| 359 |
t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey) |
| 360 |
} |
| 361 |
if setval, val := valueToString(e), valueToString(iter.Value()); setval != val { |
| 362 |
t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval) |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
got := int(testing.AllocsPerRun(10, func() { |
| 367 |
iter := v.MapRange() |
| 368 |
for iter.Next() { |
| 369 |
k.SetIterKey(iter) |
| 370 |
e.SetIterValue(iter) |
| 371 |
} |
| 372 |
})) |
| 373 |
// Making a *MapIter allocates. This should be the only allocation. |
| 374 |
if got != 1 { |
| 375 |
t.Errorf("wanted 1 alloc, got %d", got) |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
func TestCanIntUintFloatComplex(t *testing.T) { |
| 380 |
type integer int |
| 381 |
type uinteger uint |
| 382 |
type float float64 |
| 383 |
type complex complex128 |
| 384 |
|
| 385 |
var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"} |
| 386 |
|
| 387 |
var testCases = []struct { |
| 388 |
i any |
| 389 |
want [4]bool |
| 390 |
}{ |
| 391 |
// signed integer |
| 392 |
{132, [...]bool{true, false, false, false}}, |
| 393 |
{int8(8), [...]bool{true, false, false, false}}, |
| 394 |
{int16(16), [...]bool{true, false, false, false}}, |
| 395 |
{int32(32), [...]bool{true, false, false, false}}, |
| 396 |
{int64(64), [...]bool{true, false, false, false}}, |
| 397 |
// unsigned integer |
| 398 |
{uint(132), [...]bool{false, true, false, false}}, |
| 399 |
{uint8(8), [...]bool{false, true, false, false}}, |
| 400 |
{uint16(16), [...]bool{false, true, false, false}}, |
| 401 |
{uint32(32), [...]bool{false, true, false, false}}, |
| 402 |
{uint64(64), [...]bool{false, true, false, false}}, |
| 403 |
{uintptr(0xABCD), [...]bool{false, true, false, false}}, |
| 404 |
// floating-point |
| 405 |
{float32(256.25), [...]bool{false, false, true, false}}, |
| 406 |
{float64(512.125), [...]bool{false, false, true, false}}, |
| 407 |
// complex |
| 408 |
{complex64(532.125 + 10i), [...]bool{false, false, false, true}}, |
| 409 |
{complex128(564.25 + 1i), [...]bool{false, false, false, true}}, |
| 410 |
// underlying |
| 411 |
{integer(-132), [...]bool{true, false, false, false}}, |
| 412 |
{uinteger(132), [...]bool{false, true, false, false}}, |
| 413 |
{float(256.25), [...]bool{false, false, true, false}}, |
| 414 |
{complex(532.125 + 10i), [...]bool{false, false, false, true}}, |
| 415 |
// not-acceptable |
| 416 |
{"hello world", [...]bool{false, false, false, false}}, |
| 417 |
{new(int), [...]bool{false, false, false, false}}, |
| 418 |
{new(uint), [...]bool{false, false, false, false}}, |
| 419 |
{new(float64), [...]bool{false, false, false, false}}, |
| 420 |
{new(complex64), [...]bool{false, false, false, false}}, |
| 421 |
{new([5]int), [...]bool{false, false, false, false}}, |
| 422 |
{new(integer), [...]bool{false, false, false, false}}, |
| 423 |
{new(map[int]int), [...]bool{false, false, false, false}}, |
| 424 |
{new(chan<- int), [...]bool{false, false, false, false}}, |
| 425 |
{new(func(a int8)), [...]bool{false, false, false, false}}, |
| 426 |
{new(struct{ i int }), [...]bool{false, false, false, false}}, |
| 427 |
} |
| 428 |
|
| 429 |
for i, tc := range testCases { |
| 430 |
v := ValueOf(tc.i) |
| 431 |
got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()} |
| 432 |
|
| 433 |
for j := range tc.want { |
| 434 |
if got[j] != tc.want[j] { |
| 435 |
t.Errorf( |
| 436 |
"#%d: v.%s() returned %t for type %T, want %t", |
| 437 |
i, |
| 438 |
ops[j], |
| 439 |
got[j], |
| 440 |
tc.i, |
| 441 |
tc.want[j], |
| 442 |
) |
| 443 |
} |
| 444 |
} |
| 445 |
} |
| 446 |
} |
| 447 |
|
| 448 |
func TestCanSetField(t *testing.T) { |
| 449 |
type embed struct{ x, X int } |
| 450 |
type Embed struct{ x, X int } |
| 451 |
type S1 struct { |
| 452 |
embed |
| 453 |
x, X int |
| 454 |
} |
| 455 |
type S2 struct { |
| 456 |
*embed |
| 457 |
x, X int |
| 458 |
} |
| 459 |
type S3 struct { |
| 460 |
Embed |
| 461 |
x, X int |
| 462 |
} |
| 463 |
type S4 struct { |
| 464 |
*Embed |
| 465 |
x, X int |
| 466 |
} |
| 467 |
|
| 468 |
type testCase struct { |
| 469 |
// -1 means Addr().Elem() of current value |
| 470 |
index []int |
| 471 |
canSet bool |
| 472 |
} |
| 473 |
tests := []struct { |
| 474 |
val Value |
| 475 |
cases []testCase |
| 476 |
}{{ |
| 477 |
val: ValueOf(&S1{}), |
| 478 |
cases: []testCase{ |
| 479 |
{[]int{0}, false}, |
| 480 |
{[]int{0, -1}, false}, |
| 481 |
{[]int{0, 0}, false}, |
| 482 |
{[]int{0, 0, -1}, false}, |
| 483 |
{[]int{0, -1, 0}, false}, |
| 484 |
{[]int{0, -1, 0, -1}, false}, |
| 485 |
{[]int{0, 1}, true}, |
| 486 |
{[]int{0, 1, -1}, true}, |
| 487 |
{[]int{0, -1, 1}, true}, |
| 488 |
{[]int{0, -1, 1, -1}, true}, |
| 489 |
{[]int{1}, false}, |
| 490 |
{[]int{1, -1}, false}, |
| 491 |
{[]int{2}, true}, |
| 492 |
{[]int{2, -1}, true}, |
| 493 |
}, |
| 494 |
}, { |
| 495 |
val: ValueOf(&S2{embed: &embed{}}), |
| 496 |
cases: []testCase{ |
| 497 |
{[]int{0}, false}, |
| 498 |
{[]int{0, -1}, false}, |
| 499 |
{[]int{0, 0}, false}, |
| 500 |
{[]int{0, 0, -1}, false}, |
| 501 |
{[]int{0, -1, 0}, false}, |
| 502 |
{[]int{0, -1, 0, -1}, false}, |
| 503 |
{[]int{0, 1}, true}, |
| 504 |
{[]int{0, 1, -1}, true}, |
| 505 |
{[]int{0, -1, 1}, true}, |
| 506 |
{[]int{0, -1, 1, -1}, true}, |
| 507 |
{[]int{1}, false}, |
| 508 |
{[]int{2}, true}, |
| 509 |
}, |
| 510 |
}, { |
| 511 |
val: ValueOf(&S3{}), |
| 512 |
cases: []testCase{ |
| 513 |
{[]int{0}, true}, |
| 514 |
{[]int{0, -1}, true}, |
| 515 |
{[]int{0, 0}, false}, |
| 516 |
{[]int{0, 0, -1}, false}, |
| 517 |
{[]int{0, -1, 0}, false}, |
| 518 |
{[]int{0, -1, 0, -1}, false}, |
| 519 |
{[]int{0, 1}, true}, |
| 520 |
{[]int{0, 1, -1}, true}, |
| 521 |
{[]int{0, -1, 1}, true}, |
| 522 |
{[]int{0, -1, 1, -1}, true}, |
| 523 |
{[]int{1}, false}, |
| 524 |
{[]int{2}, true}, |
| 525 |
}, |
| 526 |
}, { |
| 527 |
val: ValueOf(&S4{Embed: &Embed{}}), |
| 528 |
cases: []testCase{ |
| 529 |
{[]int{0}, true}, |
| 530 |
{[]int{0, -1}, true}, |
| 531 |
{[]int{0, 0}, false}, |
| 532 |
{[]int{0, 0, -1}, false}, |
| 533 |
{[]int{0, -1, 0}, false}, |
| 534 |
{[]int{0, -1, 0, -1}, false}, |
| 535 |
{[]int{0, 1}, true}, |
| 536 |
{[]int{0, 1, -1}, true}, |
| 537 |
{[]int{0, -1, 1}, true}, |
| 538 |
{[]int{0, -1, 1, -1}, true}, |
| 539 |
{[]int{1}, false}, |
| 540 |
{[]int{2}, true}, |
| 541 |
}, |
| 542 |
}} |
| 543 |
|
| 544 |
for _, tt := range tests { |
| 545 |
t.Run(tt.val.Type().Name(), func(t *testing.T) { |
| 546 |
for _, tc := range tt.cases { |
| 547 |
f := tt.val |
| 548 |
for _, i := range tc.index { |
| 549 |
if f.Kind() == Pointer { |
| 550 |
f = f.Elem() |
| 551 |
} |
| 552 |
if i == -1 { |
| 553 |
f = f.Addr().Elem() |
| 554 |
} else { |
| 555 |
f = f.Field(i) |
| 556 |
} |
| 557 |
} |
| 558 |
if got := f.CanSet(); got != tc.canSet { |
| 559 |
t.Errorf("CanSet() = %v, want %v", got, tc.canSet) |
| 560 |
} |
| 561 |
} |
| 562 |
}) |
| 563 |
} |
| 564 |
} |
| 565 |
|
| 566 |
var _i = 7 |
| 567 |
|
| 568 |
var valueToStringTests = []pair{ |
| 569 |
{123, "123"}, |
| 570 |
{123.5, "123.5"}, |
| 571 |
{byte(123), "123"}, |
| 572 |
{"abc", "abc"}, |
| 573 |
{T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"}, |
| 574 |
{new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"}, |
| 575 |
{[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, |
| 576 |
{&[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})"}, |
| 577 |
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, |
| 578 |
{&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"}, |
| 579 |
} |
| 580 |
|
| 581 |
func TestValueToString(t *testing.T) { |
| 582 |
for i, test := range valueToStringTests { |
| 583 |
s := valueToString(ValueOf(test.i)) |
| 584 |
if s != test.s { |
| 585 |
t.Errorf("#%d: have %#q, want %#q", i, s, test.s) |
| 586 |
} |
| 587 |
} |
| 588 |
} |
| 589 |
|
| 590 |
func TestArrayElemSet(t *testing.T) { |
| 591 |
v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem() |
| 592 |
v.Index(4).SetInt(123) |
| 593 |
s := valueToString(v) |
| 594 |
const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}" |
| 595 |
if s != want { |
| 596 |
t.Errorf("[10]int: have %#q want %#q", s, want) |
| 597 |
} |
| 598 |
|
| 599 |
v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) |
| 600 |
v.Index(4).SetInt(123) |
| 601 |
s = valueToString(v) |
| 602 |
const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}" |
| 603 |
if s != want1 { |
| 604 |
t.Errorf("[]int: have %#q want %#q", s, want1) |
| 605 |
} |
| 606 |
} |
| 607 |
|
| 608 |
func TestPtrPointTo(t *testing.T) { |
| 609 |
var ip *int32 |
| 610 |
var i int32 = 1234 |
| 611 |
vip := ValueOf(&ip) |
| 612 |
vi := ValueOf(&i).Elem() |
| 613 |
vip.Elem().Set(vi.Addr()) |
| 614 |
if *ip != 1234 { |
| 615 |
t.Errorf("got %d, want 1234", *ip) |
| 616 |
} |
| 617 |
|
| 618 |
ip = nil |
| 619 |
vp := ValueOf(&ip).Elem() |
| 620 |
vp.Set(Zero(vp.Type())) |
| 621 |
if ip != nil { |
| 622 |
t.Errorf("got non-nil (%p), want nil", ip) |
| 623 |
} |
| 624 |
} |
| 625 |
|
| 626 |
func TestPtrSetNil(t *testing.T) { |
| 627 |
var i int32 = 1234 |
| 628 |
ip := &i |
| 629 |
vip := ValueOf(&ip) |
| 630 |
vip.Elem().Set(Zero(vip.Elem().Type())) |
| 631 |
if ip != nil { |
| 632 |
t.Errorf("got non-nil (%d), want nil", *ip) |
| 633 |
} |
| 634 |
} |
| 635 |
|
| 636 |
func TestMapSetNil(t *testing.T) { |
| 637 |
m := make(map[string]int) |
| 638 |
vm := ValueOf(&m) |
| 639 |
vm.Elem().Set(Zero(vm.Elem().Type())) |
| 640 |
if m != nil { |
| 641 |
t.Errorf("got non-nil (%p), want nil", m) |
| 642 |
} |
| 643 |
} |
| 644 |
|
| 645 |
func TestAll(t *testing.T) { |
| 646 |
testType(t, 1, TypeOf((int8)(0)), "int8") |
| 647 |
testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8") |
| 648 |
|
| 649 |
typ := TypeOf((*struct { |
| 650 |
c chan *int32 |
| 651 |
d float32 |
| 652 |
})(nil)) |
| 653 |
testType(t, 3, typ, "*struct { c chan *int32; d float32 }") |
| 654 |
etyp := typ.Elem() |
| 655 |
testType(t, 4, etyp, "struct { c chan *int32; d float32 }") |
| 656 |
styp := etyp |
| 657 |
f := styp.Field(0) |
| 658 |
testType(t, 5, f.Type, "chan *int32") |
| 659 |
|
| 660 |
f, present := styp.FieldByName("d") |
| 661 |
if !present { |
| 662 |
t.Errorf("FieldByName says present field is absent") |
| 663 |
} |
| 664 |
testType(t, 6, f.Type, "float32") |
| 665 |
|
| 666 |
f, present = styp.FieldByName("absent") |
| 667 |
if present { |
| 668 |
t.Errorf("FieldByName says absent field is present") |
| 669 |
} |
| 670 |
|
| 671 |
typ = TypeOf([32]int32{}) |
| 672 |
testType(t, 7, typ, "[32]int32") |
| 673 |
testType(t, 8, typ.Elem(), "int32") |
| 674 |
|
| 675 |
typ = TypeOf((map[string]*int32)(nil)) |
| 676 |
testType(t, 9, typ, "map[string]*int32") |
| 677 |
mtyp := typ |
| 678 |
testType(t, 10, mtyp.Key(), "string") |
| 679 |
testType(t, 11, mtyp.Elem(), "*int32") |
| 680 |
|
| 681 |
typ = TypeOf((chan<- string)(nil)) |
| 682 |
testType(t, 12, typ, "chan<- string") |
| 683 |
testType(t, 13, typ.Elem(), "string") |
| 684 |
|
| 685 |
// make sure tag strings are not part of element type |
| 686 |
typ = TypeOf(struct { |
| 687 |
d []uint32 `reflect:"TAG"` |
| 688 |
}{}).Field(0).Type |
| 689 |
testType(t, 14, typ, "[]uint32") |
| 690 |
} |
| 691 |
|
| 692 |
func TestInterfaceGet(t *testing.T) { |
| 693 |
var inter struct { |
| 694 |
E any |
| 695 |
} |
| 696 |
inter.E = 123.456 |
| 697 |
v1 := ValueOf(&inter) |
| 698 |
v2 := v1.Elem().Field(0) |
| 699 |
assert(t, v2.Type().String(), "interface {}") |
| 700 |
i2 := v2.Interface() |
| 701 |
v3 := ValueOf(i2) |
| 702 |
assert(t, v3.Type().String(), "float64") |
| 703 |
} |
| 704 |
|
| 705 |
func TestInterfaceValue(t *testing.T) { |
| 706 |
var inter struct { |
| 707 |
E any |
| 708 |
} |
| 709 |
inter.E = 123.456 |
| 710 |
v1 := ValueOf(&inter) |
| 711 |
v2 := v1.Elem().Field(0) |
| 712 |
assert(t, v2.Type().String(), "interface {}") |
| 713 |
v3 := v2.Elem() |
| 714 |
assert(t, v3.Type().String(), "float64") |
| 715 |
|
| 716 |
i3 := v2.Interface() |
| 717 |
if _, ok := i3.(float64); !ok { |
| 718 |
t.Error("v2.Interface() did not return float64, got ", TypeOf(i3)) |
| 719 |
} |
| 720 |
} |
| 721 |
|
| 722 |
func TestFunctionValue(t *testing.T) { |
| 723 |
var x any = func() {} |
| 724 |
v := ValueOf(x) |
| 725 |
if fmt.Sprint(v.Interface()) != fmt.Sprint(x) { |
| 726 |
t.Fatalf("TestFunction returned wrong pointer") |
| 727 |
} |
| 728 |
assert(t, v.Type().String(), "func()") |
| 729 |
} |
| 730 |
|
| 731 |
var appendTests = []struct { |
| 732 |
orig, extra []int |
| 733 |
}{ |
| 734 |
{make([]int, 2, 4), []int{22}}, |
| 735 |
{make([]int, 2, 4), []int{22, 33, 44}}, |
| 736 |
} |
| 737 |
|
| 738 |
func sameInts(x, y []int) bool { |
| 739 |
if len(x) != len(y) { |
| 740 |
return false |
| 741 |
} |
| 742 |
for i, xx := range x { |
| 743 |
if xx != y[i] { |
| 744 |
return false |
| 745 |
} |
| 746 |
} |
| 747 |
return true |
| 748 |
} |
| 749 |
|
| 750 |
func TestAppend(t *testing.T) { |
| 751 |
for i, test := range appendTests { |
| 752 |
origLen, extraLen := len(test.orig), len(test.extra) |
| 753 |
want := append(test.orig, test.extra...) |
| 754 |
// Convert extra from []int to []Value. |
| 755 |
e0 := make([]Value, len(test.extra)) |
| 756 |
for j, e := range test.extra { |
| 757 |
e0[j] = ValueOf(e) |
| 758 |
} |
| 759 |
// Convert extra from []int to *SliceValue. |
| 760 |
e1 := ValueOf(test.extra) |
| 761 |
// Test Append. |
| 762 |
a0 := ValueOf(test.orig) |
| 763 |
have0 := Append(a0, e0...).Interface().([]int) |
| 764 |
if !sameInts(have0, want) { |
| 765 |
t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0) |
| 766 |
} |
| 767 |
// Check that the orig and extra slices were not modified. |
| 768 |
if len(test.orig) != origLen { |
| 769 |
t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen) |
| 770 |
} |
| 771 |
if len(test.extra) != extraLen { |
| 772 |
t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen) |
| 773 |
} |
| 774 |
// Test AppendSlice. |
| 775 |
a1 := ValueOf(test.orig) |
| 776 |
have1 := AppendSlice(a1, e1).Interface().([]int) |
| 777 |
if !sameInts(have1, want) { |
| 778 |
t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want) |
| 779 |
} |
| 780 |
// Check that the orig and extra slices were not modified. |
| 781 |
if len(test.orig) != origLen { |
| 782 |
t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen) |
| 783 |
} |
| 784 |
if len(test.extra) != extraLen { |
| 785 |
t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen) |
| 786 |
} |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
func TestCopy(t *testing.T) { |
| 791 |
a := []int{1, 2, 3, 4, 10, 9, 8, 7} |
| 792 |
b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} |
| 793 |
c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} |
| 794 |
for i := 0; i < len(b); i++ { |
| 795 |
if b[i] != c[i] { |
| 796 |
t.Fatalf("b != c before test") |
| 797 |
} |
| 798 |
} |
| 799 |
a1 := a |
| 800 |
b1 := b |
| 801 |
aa := ValueOf(&a1).Elem() |
| 802 |
ab := ValueOf(&b1).Elem() |
| 803 |
for tocopy := 1; tocopy <= 7; tocopy++ { |
| 804 |
aa.SetLen(tocopy) |
| 805 |
Copy(ab, aa) |
| 806 |
aa.SetLen(8) |
| 807 |
for i := 0; i < tocopy; i++ { |
| 808 |
if a[i] != b[i] { |
| 809 |
t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d", |
| 810 |
tocopy, i, a[i], i, b[i]) |
| 811 |
} |
| 812 |
} |
| 813 |
for i := tocopy; i < len(b); i++ { |
| 814 |
if b[i] != c[i] { |
| 815 |
if i < len(a) { |
| 816 |
t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d", |
| 817 |
tocopy, i, a[i], i, b[i], i, c[i]) |
| 818 |
} else { |
| 819 |
t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d", |
| 820 |
tocopy, i, b[i], i, c[i]) |
| 821 |
} |
| 822 |
} else { |
| 823 |
t.Logf("tocopy=%d elem %d is okay\n", tocopy, i) |
| 824 |
} |
| 825 |
} |
| 826 |
} |
| 827 |
} |
| 828 |
|
| 829 |
func TestCopyString(t *testing.T) { |
| 830 |
t.Run("Slice", func(t *testing.T) { |
| 831 |
s := bytes.Repeat([]byte{'_'}, 8) |
| 832 |
val := ValueOf(s) |
| 833 |
|
| 834 |
n := Copy(val, ValueOf("")) |
| 835 |
if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) { |
| 836 |
t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting) |
| 837 |
} |
| 838 |
|
| 839 |
n = Copy(val, ValueOf("hello")) |
| 840 |
if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) { |
| 841 |
t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting) |
| 842 |
} |
| 843 |
|
| 844 |
n = Copy(val, ValueOf("helloworld")) |
| 845 |
if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) { |
| 846 |
t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting) |
| 847 |
} |
| 848 |
}) |
| 849 |
t.Run("Array", func(t *testing.T) { |
| 850 |
s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'} |
| 851 |
val := ValueOf(&s).Elem() |
| 852 |
|
| 853 |
n := Copy(val, ValueOf("")) |
| 854 |
if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) { |
| 855 |
t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting) |
| 856 |
} |
| 857 |
|
| 858 |
n = Copy(val, ValueOf("hello")) |
| 859 |
if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) { |
| 860 |
t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting) |
| 861 |
} |
| 862 |
|
| 863 |
n = Copy(val, ValueOf("helloworld")) |
| 864 |
if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) { |
| 865 |
t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting) |
| 866 |
} |
| 867 |
}) |
| 868 |
} |
| 869 |
|
| 870 |
func TestCopyArray(t *testing.T) { |
| 871 |
a := [8]int{1, 2, 3, 4, 10, 9, 8, 7} |
| 872 |
b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} |
| 873 |
c := b |
| 874 |
aa := ValueOf(&a).Elem() |
| 875 |
ab := ValueOf(&b).Elem() |
| 876 |
Copy(ab, aa) |
| 877 |
for i := 0; i < len(a); i++ { |
| 878 |
if a[i] != b[i] { |
| 879 |
t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i]) |
| 880 |
} |
| 881 |
} |
| 882 |
for i := len(a); i < len(b); i++ { |
| 883 |
if b[i] != c[i] { |
| 884 |
t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i]) |
| 885 |
} else { |
| 886 |
t.Logf("elem %d is okay\n", i) |
| 887 |
} |
| 888 |
} |
| 889 |
} |
| 890 |
|
| 891 |
func TestBigUnnamedStruct(t *testing.T) { |
| 892 |
b := struct{ a, b, c, d int64 }{1, 2, 3, 4} |
| 893 |
v := ValueOf(b) |
| 894 |
b1 := v.Interface().(struct { |
| 895 |
a, b, c, d int64 |
| 896 |
}) |
| 897 |
if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d { |
| 898 |
t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1) |
| 899 |
} |
| 900 |
} |
| 901 |
|
| 902 |
type big struct { |
| 903 |
a, b, c, d, e int64 |
| 904 |
} |
| 905 |
|
| 906 |
func TestBigStruct(t *testing.T) { |
| 907 |
b := big{1, 2, 3, 4, 5} |
| 908 |
v := ValueOf(b) |
| 909 |
b1 := v.Interface().(big) |
| 910 |
if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e { |
| 911 |
t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1) |
| 912 |
} |
| 913 |
} |
| 914 |
|
| 915 |
type Basic struct { |
| 916 |
x int |
| 917 |
y float32 |
| 918 |
} |
| 919 |
|
| 920 |
type NotBasic Basic |
| 921 |
|
| 922 |
type DeepEqualTest struct { |
| 923 |
a, b any |
| 924 |
eq bool |
| 925 |
} |
| 926 |
|
| 927 |
// Simple functions for DeepEqual tests. |
| 928 |
var ( |
| 929 |
fn1 func() // nil. |
| 930 |
fn2 func() // nil. |
| 931 |
fn3 = func() { fn1() } // Not nil. |
| 932 |
) |
| 933 |
|
| 934 |
type self struct{} |
| 935 |
|
| 936 |
type Loop *Loop |
| 937 |
type Loopy any |
| 938 |
|
| 939 |
var loop1, loop2 Loop |
| 940 |
var loopy1, loopy2 Loopy |
| 941 |
var cycleMap1, cycleMap2, cycleMap3 map[string]any |
| 942 |
|
| 943 |
type structWithSelfPtr struct { |
| 944 |
p *structWithSelfPtr |
| 945 |
s string |
| 946 |
} |
| 947 |
|
| 948 |
func init() { |
| 949 |
loop1 = &loop2 |
| 950 |
loop2 = &loop1 |
| 951 |
|
| 952 |
loopy1 = &loopy2 |
| 953 |
loopy2 = &loopy1 |
| 954 |
|
| 955 |
cycleMap1 = map[string]any{} |
| 956 |
cycleMap1["cycle"] = cycleMap1 |
| 957 |
cycleMap2 = map[string]any{} |
| 958 |
cycleMap2["cycle"] = cycleMap2 |
| 959 |
cycleMap3 = map[string]any{} |
| 960 |
cycleMap3["different"] = cycleMap3 |
| 961 |
} |
| 962 |
|
| 963 |
var deepEqualTests = []DeepEqualTest{ |
| 964 |
// Equalities |
| 965 |
{nil, nil, true}, |
| 966 |
{1, 1, true}, |
| 967 |
{int32(1), int32(1), true}, |
| 968 |
{0.5, 0.5, true}, |
| 969 |
{float32(0.5), float32(0.5), true}, |
| 970 |
{"hello", "hello", true}, |
| 971 |
{make([]int, 10), make([]int, 10), true}, |
| 972 |
{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true}, |
| 973 |
{Basic{1, 0.5}, Basic{1, 0.5}, true}, |
| 974 |
{error(nil), error(nil), true}, |
| 975 |
{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true}, |
| 976 |
{fn1, fn2, true}, |
| 977 |
{[]byte{1, 2, 3}, []byte{1, 2, 3}, true}, |
| 978 |
{[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true}, |
| 979 |
{MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true}, |
| 980 |
|
| 981 |
// Inequalities |
| 982 |
{1, 2, false}, |
| 983 |
{int32(1), int32(2), false}, |
| 984 |
{0.5, 0.6, false}, |
| 985 |
{float32(0.5), float32(0.6), false}, |
| 986 |
{"hello", "hey", false}, |
| 987 |
{make([]int, 10), make([]int, 11), false}, |
| 988 |
{&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false}, |
| 989 |
{Basic{1, 0.5}, Basic{1, 0.6}, false}, |
| 990 |
{Basic{1, 0}, Basic{2, 0}, false}, |
| 991 |
{map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false}, |
| 992 |
{map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false}, |
| 993 |
{map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false}, |
| 994 |
{map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false}, |
| 995 |
{nil, 1, false}, |
| 996 |
{1, nil, false}, |
| 997 |
{fn1, fn3, false}, |
| 998 |
{fn3, fn3, false}, |
| 999 |
{[][]int{{1}}, [][]int{{2}}, false}, |
| 1000 |
{&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false}, |
| 1001 |
|
| 1002 |
// Fun with floating point. |
| 1003 |
{math.NaN(), math.NaN(), false}, |
| 1004 |
{&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false}, |
| 1005 |
{&[1]float64{math.NaN()}, self{}, true}, |
| 1006 |
{[]float64{math.NaN()}, []float64{math.NaN()}, false}, |
| 1007 |
{[]float64{math.NaN()}, self{}, true}, |
| 1008 |
{map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false}, |
| 1009 |
{map[float64]float64{math.NaN(): 1}, self{}, true}, |
| 1010 |
|
| 1011 |
// Nil vs empty: not the same. |
| 1012 |
{[]int{}, []int(nil), false}, |
| 1013 |
{[]int{}, []int{}, true}, |
| 1014 |
{[]int(nil), []int(nil), true}, |
| 1015 |
{map[int]int{}, map[int]int(nil), false}, |
| 1016 |
{map[int]int{}, map[int]int{}, true}, |
| 1017 |
{map[int]int(nil), map[int]int(nil), true}, |
| 1018 |
|
| 1019 |
// Mismatched types |
| 1020 |
{1, 1.0, false}, |
| 1021 |
{int32(1), int64(1), false}, |
| 1022 |
{0.5, "hello", false}, |
| 1023 |
{[]int{1, 2, 3}, [3]int{1, 2, 3}, false}, |
| 1024 |
{&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false}, |
| 1025 |
{Basic{1, 0.5}, NotBasic{1, 0.5}, false}, |
| 1026 |
{map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false}, |
| 1027 |
{[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false}, |
| 1028 |
{[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false}, |
| 1029 |
{[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false}, |
| 1030 |
|
| 1031 |
// Possible loops. |
| 1032 |
{&loop1, &loop1, true}, |
| 1033 |
{&loop1, &loop2, true}, |
| 1034 |
{&loopy1, &loopy1, true}, |
| 1035 |
{&loopy1, &loopy2, true}, |
| 1036 |
{&cycleMap1, &cycleMap2, true}, |
| 1037 |
{&cycleMap1, &cycleMap3, false}, |
| 1038 |
} |
| 1039 |
|
| 1040 |
func TestDeepEqual(t *testing.T) { |
| 1041 |
for _, test := range deepEqualTests { |
| 1042 |
if test.b == (self{}) { |
| 1043 |
test.b = test.a |
| 1044 |
} |
| 1045 |
if r := DeepEqual(test.a, test.b); r != test.eq { |
| 1046 |
t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq) |
| 1047 |
} |
| 1048 |
} |
| 1049 |
} |
| 1050 |
|
| 1051 |
func TestTypeOf(t *testing.T) { |
| 1052 |
// Special case for nil |
| 1053 |
if typ := TypeOf(nil); typ != nil { |
| 1054 |
t.Errorf("expected nil type for nil value; got %v", typ) |
| 1055 |
} |
| 1056 |
for _, test := range deepEqualTests { |
| 1057 |
v := ValueOf(test.a) |
| 1058 |
if !v.IsValid() { |
| 1059 |
continue |
| 1060 |
} |
| 1061 |
typ := TypeOf(test.a) |
| 1062 |
if typ != v.Type() { |
| 1063 |
t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type()) |
| 1064 |
} |
| 1065 |
} |
| 1066 |
} |
| 1067 |
|
| 1068 |
type Recursive struct { |
| 1069 |
x int |
| 1070 |
r *Recursive |
| 1071 |
} |
| 1072 |
|
| 1073 |
func TestDeepEqualRecursiveStruct(t *testing.T) { |
| 1074 |
a, b := new(Recursive), new(Recursive) |
| 1075 |
*a = Recursive{12, a} |
| 1076 |
*b = Recursive{12, b} |
| 1077 |
if !DeepEqual(a, b) { |
| 1078 |
t.Error("DeepEqual(recursive same) = false, want true") |
| 1079 |
} |
| 1080 |
} |
| 1081 |
|
| 1082 |
type _Complex struct { |
| 1083 |
a int |
| 1084 |
b [3]*_Complex |
| 1085 |
c *string |
| 1086 |
d map[float64]float64 |
| 1087 |
} |
| 1088 |
|
| 1089 |
func TestDeepEqualComplexStruct(t *testing.T) { |
| 1090 |
m := make(map[float64]float64) |
| 1091 |
stra, strb := "hello", "hello" |
| 1092 |
a, b := new(_Complex), new(_Complex) |
| 1093 |
*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m} |
| 1094 |
*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m} |
| 1095 |
if !DeepEqual(a, b) { |
| 1096 |
t.Error("DeepEqual(complex same) = false, want true") |
| 1097 |
} |
| 1098 |
} |
| 1099 |
|
| 1100 |
func TestDeepEqualComplexStructInequality(t *testing.T) { |
| 1101 |
m := make(map[float64]float64) |
| 1102 |
stra, strb := "hello", "helloo" // Difference is here |
| 1103 |
a, b := new(_Complex), new(_Complex) |
| 1104 |
*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m} |
| 1105 |
*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m} |
| 1106 |
if DeepEqual(a, b) { |
| 1107 |
t.Error("DeepEqual(complex different) = true, want false") |
| 1108 |
} |
| 1109 |
} |
| 1110 |
|
| 1111 |
type UnexpT struct { |
| 1112 |
m map[int]int |
| 1113 |
} |
| 1114 |
|
| 1115 |
func TestDeepEqualUnexportedMap(t *testing.T) { |
| 1116 |
// Check that DeepEqual can look at unexported fields. |
| 1117 |
x1 := UnexpT{map[int]int{1: 2}} |
| 1118 |
x2 := UnexpT{map[int]int{1: 2}} |
| 1119 |
if !DeepEqual(&x1, &x2) { |
| 1120 |
t.Error("DeepEqual(x1, x2) = false, want true") |
| 1121 |
} |
| 1122 |
|
| 1123 |
y1 := UnexpT{map[int]int{2: 3}} |
| 1124 |
if DeepEqual(&x1, &y1) { |
| 1125 |
t.Error("DeepEqual(x1, y1) = true, want false") |
| 1126 |
} |
| 1127 |
} |
| 1128 |
|
| 1129 |
var deepEqualPerfTests = []struct { |
| 1130 |
x, y any |
| 1131 |
}{ |
| 1132 |
{x: int8(99), y: int8(99)}, |
| 1133 |
{x: []int8{99}, y: []int8{99}}, |
| 1134 |
{x: int16(99), y: int16(99)}, |
| 1135 |
{x: []int16{99}, y: []int16{99}}, |
| 1136 |
{x: int32(99), y: int32(99)}, |
| 1137 |
{x: []int32{99}, y: []int32{99}}, |
| 1138 |
{x: int64(99), y: int64(99)}, |
| 1139 |
{x: []int64{99}, y: []int64{99}}, |
| 1140 |
{x: int(999999), y: int(999999)}, |
| 1141 |
{x: []int{999999}, y: []int{999999}}, |
| 1142 |
|
| 1143 |
{x: uint8(99), y: uint8(99)}, |
| 1144 |
{x: []uint8{99}, y: []uint8{99}}, |
| 1145 |
{x: uint16(99), y: uint16(99)}, |
| 1146 |
{x: []uint16{99}, y: []uint16{99}}, |
| 1147 |
{x: uint32(99), y: uint32(99)}, |
| 1148 |
{x: []uint32{99}, y: []uint32{99}}, |
| 1149 |
{x: uint64(99), y: uint64(99)}, |
| 1150 |
{x: []uint64{99}, y: []uint64{99}}, |
| 1151 |
{x: uint(999999), y: uint(999999)}, |
| 1152 |
{x: []uint{999999}, y: []uint{999999}}, |
| 1153 |
{x: uintptr(999999), y: uintptr(999999)}, |
| 1154 |
{x: []uintptr{999999}, y: []uintptr{999999}}, |
| 1155 |
|
| 1156 |
{x: float32(1.414), y: float32(1.414)}, |
| 1157 |
{x: []float32{1.414}, y: []float32{1.414}}, |
| 1158 |
{x: float64(1.414), y: float64(1.414)}, |
| 1159 |
{x: []float64{1.414}, y: []float64{1.414}}, |
| 1160 |
|
| 1161 |
{x: complex64(1.414), y: complex64(1.414)}, |
| 1162 |
{x: []complex64{1.414}, y: []complex64{1.414}}, |
| 1163 |
{x: complex128(1.414), y: complex128(1.414)}, |
| 1164 |
{x: []complex128{1.414}, y: []complex128{1.414}}, |
| 1165 |
|
| 1166 |
{x: true, y: true}, |
| 1167 |
{x: []bool{true}, y: []bool{true}}, |
| 1168 |
|
| 1169 |
{x: "abcdef", y: "abcdef"}, |
| 1170 |
{x: []string{"abcdef"}, y: []string{"abcdef"}}, |
| 1171 |
|
| 1172 |
{x: []byte("abcdef"), y: []byte("abcdef")}, |
| 1173 |
{x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}}, |
| 1174 |
|
| 1175 |
{x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, |
| 1176 |
{x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}}, |
| 1177 |
} |
| 1178 |
|
| 1179 |
func TestDeepEqualAllocs(t *testing.T) { |
| 1180 |
if runtime.Compiler == "gccgo" { |
| 1181 |
t.Skip("conservative GC") |
| 1182 |
} |
| 1183 |
for _, tt := range deepEqualPerfTests { |
| 1184 |
t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) { |
| 1185 |
got := testing.AllocsPerRun(100, func() { |
| 1186 |
if !DeepEqual(tt.x, tt.y) { |
| 1187 |
t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y) |
| 1188 |
} |
| 1189 |
}) |
| 1190 |
if int(got) != 0 { |
| 1191 |
t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got)) |
| 1192 |
} |
| 1193 |
}) |
| 1194 |
} |
| 1195 |
} |
| 1196 |
|
| 1197 |
func BenchmarkDeepEqual(b *testing.B) { |
| 1198 |
for _, bb := range deepEqualPerfTests { |
| 1199 |
b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) { |
| 1200 |
b.ReportAllocs() |
| 1201 |
for i := 0; i < b.N; i++ { |
| 1202 |
sink = DeepEqual(bb.x, bb.y) |
| 1203 |
} |
| 1204 |
}) |
| 1205 |
} |
| 1206 |
} |
| 1207 |
|
| 1208 |
func check2ndField(x any, offs uintptr, t *testing.T) { |
| 1209 |
s := ValueOf(x) |
| 1210 |
f := s.Type().Field(1) |
| 1211 |
if f.Offset != offs { |
| 1212 |
t.Error("mismatched offsets in structure alignment:", f.Offset, offs) |
| 1213 |
} |
| 1214 |
} |
| 1215 |
|
| 1216 |
// Check that structure alignment & offsets viewed through reflect agree with those |
| 1217 |
// from the compiler itself. |
| 1218 |
func TestAlignment(t *testing.T) { |
| 1219 |
type T1inner struct { |
| 1220 |
a int |
| 1221 |
} |
| 1222 |
type T1 struct { |
| 1223 |
T1inner |
| 1224 |
f int |
| 1225 |
} |
| 1226 |
type T2inner struct { |
| 1227 |
a, b int |
| 1228 |
} |
| 1229 |
type T2 struct { |
| 1230 |
T2inner |
| 1231 |
f int |
| 1232 |
} |
| 1233 |
|
| 1234 |
x := T1{T1inner{2}, 17} |
| 1235 |
check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t) |
| 1236 |
|
| 1237 |
x1 := T2{T2inner{2, 3}, 17} |
| 1238 |
check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t) |
| 1239 |
} |
| 1240 |
|
| 1241 |
func Nil(a any, t *testing.T) { |
| 1242 |
n := ValueOf(a).Field(0) |
| 1243 |
if !n.IsNil() { |
| 1244 |
t.Errorf("%v should be nil", a) |
| 1245 |
} |
| 1246 |
} |
| 1247 |
|
| 1248 |
func NotNil(a any, t *testing.T) { |
| 1249 |
n := ValueOf(a).Field(0) |
| 1250 |
if n.IsNil() { |
| 1251 |
t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String()) |
| 1252 |
} |
| 1253 |
} |
| 1254 |
|
| 1255 |
func TestIsNil(t *testing.T) { |
| 1256 |
// These implement IsNil. |
| 1257 |
// Wrap in extra struct to hide interface type. |
| 1258 |
doNil := []any{ |
| 1259 |
struct{ x *int }{}, |
| 1260 |
struct{ x any }{}, |
| 1261 |
struct{ x map[string]int }{}, |
| 1262 |
struct{ x func() bool }{}, |
| 1263 |
struct{ x chan int }{}, |
| 1264 |
struct{ x []string }{}, |
| 1265 |
struct{ x unsafe.Pointer }{}, |
| 1266 |
} |
| 1267 |
for _, ts := range doNil { |
| 1268 |
ty := TypeOf(ts).Field(0).Type |
| 1269 |
v := Zero(ty) |
| 1270 |
v.IsNil() // panics if not okay to call |
| 1271 |
} |
| 1272 |
|
| 1273 |
// Check the implementations |
| 1274 |
var pi struct { |
| 1275 |
x *int |
| 1276 |
} |
| 1277 |
Nil(pi, t) |
| 1278 |
pi.x = new(int) |
| 1279 |
NotNil(pi, t) |
| 1280 |
|
| 1281 |
var si struct { |
| 1282 |
x []int |
| 1283 |
} |
| 1284 |
Nil(si, t) |
| 1285 |
si.x = make([]int, 10) |
| 1286 |
NotNil(si, t) |
| 1287 |
|
| 1288 |
var ci struct { |
| 1289 |
x chan int |
| 1290 |
} |
| 1291 |
Nil(ci, t) |
| 1292 |
ci.x = make(chan int) |
| 1293 |
NotNil(ci, t) |
| 1294 |
|
| 1295 |
var mi struct { |
| 1296 |
x map[int]int |
| 1297 |
} |
| 1298 |
Nil(mi, t) |
| 1299 |
mi.x = make(map[int]int) |
| 1300 |
NotNil(mi, t) |
| 1301 |
|
| 1302 |
var ii struct { |
| 1303 |
x any |
| 1304 |
} |
| 1305 |
Nil(ii, t) |
| 1306 |
ii.x = 2 |
| 1307 |
NotNil(ii, t) |
| 1308 |
|
| 1309 |
var fi struct { |
| 1310 |
x func(t *testing.T) |
| 1311 |
} |
| 1312 |
Nil(fi, t) |
| 1313 |
fi.x = TestIsNil |
| 1314 |
NotNil(fi, t) |
| 1315 |
} |
| 1316 |
|
| 1317 |
func TestIsZero(t *testing.T) { |
| 1318 |
for i, tt := range []struct { |
| 1319 |
x any |
| 1320 |
want bool |
| 1321 |
}{ |
| 1322 |
// Booleans |
| 1323 |
{true, false}, |
| 1324 |
{false, true}, |
| 1325 |
// Numeric types |
| 1326 |
{int(0), true}, |
| 1327 |
{int(1), false}, |
| 1328 |
{int8(0), true}, |
| 1329 |
{int8(1), false}, |
| 1330 |
{int16(0), true}, |
| 1331 |
{int16(1), false}, |
| 1332 |
{int32(0), true}, |
| 1333 |
{int32(1), false}, |
| 1334 |
{int64(0), true}, |
| 1335 |
{int64(1), false}, |
| 1336 |
{uint(0), true}, |
| 1337 |
{uint(1), false}, |
| 1338 |
{uint8(0), true}, |
| 1339 |
{uint8(1), false}, |
| 1340 |
{uint16(0), true}, |
| 1341 |
{uint16(1), false}, |
| 1342 |
{uint32(0), true}, |
| 1343 |
{uint32(1), false}, |
| 1344 |
{uint64(0), true}, |
| 1345 |
{uint64(1), false}, |
| 1346 |
{float32(0), true}, |
| 1347 |
{float32(1.2), false}, |
| 1348 |
{float64(0), true}, |
| 1349 |
{float64(1.2), false}, |
| 1350 |
{math.Copysign(0, -1), false}, |
| 1351 |
{complex64(0), true}, |
| 1352 |
{complex64(1.2), false}, |
| 1353 |
{complex128(0), true}, |
| 1354 |
{complex128(1.2), false}, |
| 1355 |
{complex(math.Copysign(0, -1), 0), false}, |
| 1356 |
{complex(0, math.Copysign(0, -1)), false}, |
| 1357 |
{complex(math.Copysign(0, -1), math.Copysign(0, -1)), false}, |
| 1358 |
{uintptr(0), true}, |
| 1359 |
{uintptr(128), false}, |
| 1360 |
// Array |
| 1361 |
{Zero(TypeOf([5]string{})).Interface(), true}, |
| 1362 |
{[5]string{"", "", "", "", ""}, true}, |
| 1363 |
{[5]string{}, true}, |
| 1364 |
{[5]string{"", "", "", "a", ""}, false}, |
| 1365 |
// Chan |
| 1366 |
{(chan string)(nil), true}, |
| 1367 |
{make(chan string), false}, |
| 1368 |
{time.After(1), false}, |
| 1369 |
// Func |
| 1370 |
{(func())(nil), true}, |
| 1371 |
{New, false}, |
| 1372 |
// Interface |
| 1373 |
{New(TypeOf(new(error)).Elem()).Elem(), true}, |
| 1374 |
{(io.Reader)(strings.NewReader("")), false}, |
| 1375 |
// Map |
| 1376 |
{(map[string]string)(nil), true}, |
| 1377 |
{map[string]string{}, false}, |
| 1378 |
{make(map[string]string), false}, |
| 1379 |
// Pointer |
| 1380 |
{(*func())(nil), true}, |
| 1381 |
{(*int)(nil), true}, |
| 1382 |
{new(int), false}, |
| 1383 |
// Slice |
| 1384 |
{[]string{}, false}, |
| 1385 |
{([]string)(nil), true}, |
| 1386 |
{make([]string, 0), false}, |
| 1387 |
// Strings |
| 1388 |
{"", true}, |
| 1389 |
{"not-zero", false}, |
| 1390 |
// Structs |
| 1391 |
{T{}, true}, |
| 1392 |
{T{123, 456.75, "hello", &_i}, false}, |
| 1393 |
// UnsafePointer |
| 1394 |
{(unsafe.Pointer)(nil), true}, |
| 1395 |
{(unsafe.Pointer)(new(int)), false}, |
| 1396 |
} { |
| 1397 |
var x Value |
| 1398 |
if v, ok := tt.x.(Value); ok { |
| 1399 |
x = v |
| 1400 |
} else { |
| 1401 |
x = ValueOf(tt.x) |
| 1402 |
} |
| 1403 |
|
| 1404 |
b := x.IsZero() |
| 1405 |
if b != tt.want { |
| 1406 |
t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want) |
| 1407 |
} |
| 1408 |
|
| 1409 |
if !Zero(TypeOf(tt.x)).IsZero() { |
| 1410 |
t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x) |
| 1411 |
} |
| 1412 |
} |
| 1413 |
|
| 1414 |
func() { |
| 1415 |
defer func() { |
| 1416 |
if r := recover(); r == nil { |
| 1417 |
t.Error("should panic for invalid value") |
| 1418 |
} |
| 1419 |
}() |
| 1420 |
(Value{}).IsZero() |
| 1421 |
}() |
| 1422 |
} |
| 1423 |
|
| 1424 |
func TestInterfaceExtraction(t *testing.T) { |
| 1425 |
var s struct { |
| 1426 |
W io.Writer |
| 1427 |
} |
| 1428 |
|
| 1429 |
s.W = os.Stdout |
| 1430 |
v := Indirect(ValueOf(&s)).Field(0).Interface() |
| 1431 |
if v != s.W.(any) { |
| 1432 |
t.Error("Interface() on interface: ", v, s.W) |
| 1433 |
} |
| 1434 |
} |
| 1435 |
|
| 1436 |
func TestNilPtrValueSub(t *testing.T) { |
| 1437 |
var pi *int |
| 1438 |
if pv := ValueOf(pi); pv.Elem().IsValid() { |
| 1439 |
t.Error("ValueOf((*int)(nil)).Elem().IsValid()") |
| 1440 |
} |
| 1441 |
} |
| 1442 |
|
| 1443 |
func TestMap(t *testing.T) { |
| 1444 |
m := map[string]int{"a": 1, "b": 2} |
| 1445 |
mv := ValueOf(m) |
| 1446 |
if n := mv.Len(); n != len(m) { |
| 1447 |
t.Errorf("Len = %d, want %d", n, len(m)) |
| 1448 |
} |
| 1449 |
keys := mv.MapKeys() |
| 1450 |
newmap := MakeMap(mv.Type()) |
| 1451 |
for k, v := range m { |
| 1452 |
// Check that returned Keys match keys in range. |
| 1453 |
// These aren't required to be in the same order. |
| 1454 |
seen := false |
| 1455 |
for _, kv := range keys { |
| 1456 |
if kv.String() == k { |
| 1457 |
seen = true |
| 1458 |
break |
| 1459 |
} |
| 1460 |
} |
| 1461 |
if !seen { |
| 1462 |
t.Errorf("Missing key %q", k) |
| 1463 |
} |
| 1464 |
|
| 1465 |
// Check that value lookup is correct. |
| 1466 |
vv := mv.MapIndex(ValueOf(k)) |
| 1467 |
if vi := vv.Int(); vi != int64(v) { |
| 1468 |
t.Errorf("Key %q: have value %d, want %d", k, vi, v) |
| 1469 |
} |
| 1470 |
|
| 1471 |
// Copy into new map. |
| 1472 |
newmap.SetMapIndex(ValueOf(k), ValueOf(v)) |
| 1473 |
} |
| 1474 |
vv := mv.MapIndex(ValueOf("not-present")) |
| 1475 |
if vv.IsValid() { |
| 1476 |
t.Errorf("Invalid key: got non-nil value %s", valueToString(vv)) |
| 1477 |
} |
| 1478 |
|
| 1479 |
newm := newmap.Interface().(map[string]int) |
| 1480 |
if len(newm) != len(m) { |
| 1481 |
t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m)) |
| 1482 |
} |
| 1483 |
|
| 1484 |
for k, v := range newm { |
| 1485 |
mv, ok := m[k] |
| 1486 |
if mv != v { |
| 1487 |
t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok) |
| 1488 |
} |
| 1489 |
} |
| 1490 |
|
| 1491 |
newmap.SetMapIndex(ValueOf("a"), Value{}) |
| 1492 |
v, ok := newm["a"] |
| 1493 |
if ok { |
| 1494 |
t.Errorf("newm[\"a\"] = %d after delete", v) |
| 1495 |
} |
| 1496 |
|
| 1497 |
mv = ValueOf(&m).Elem() |
| 1498 |
mv.Set(Zero(mv.Type())) |
| 1499 |
if m != nil { |
| 1500 |
t.Errorf("mv.Set(nil) failed") |
| 1501 |
} |
| 1502 |
} |
| 1503 |
|
| 1504 |
func TestNilMap(t *testing.T) { |
| 1505 |
var m map[string]int |
| 1506 |
mv := ValueOf(m) |
| 1507 |
keys := mv.MapKeys() |
| 1508 |
if len(keys) != 0 { |
| 1509 |
t.Errorf(">0 keys for nil map: %v", keys) |
| 1510 |
} |
| 1511 |
|
| 1512 |
// Check that value for missing key is zero. |
| 1513 |
x := mv.MapIndex(ValueOf("hello")) |
| 1514 |
if x.Kind() != Invalid { |
| 1515 |
t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x) |
| 1516 |
} |
| 1517 |
|
| 1518 |
// Check big value too. |
| 1519 |
var mbig map[string][10 << 20]byte |
| 1520 |
x = ValueOf(mbig).MapIndex(ValueOf("hello")) |
| 1521 |
if x.Kind() != Invalid { |
| 1522 |
t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x) |
| 1523 |
} |
| 1524 |
|
| 1525 |
// Test that deletes from a nil map succeed. |
| 1526 |
mv.SetMapIndex(ValueOf("hi"), Value{}) |
| 1527 |
} |
| 1528 |
|
| 1529 |
func TestChan(t *testing.T) { |
| 1530 |
for loop := 0; loop < 2; loop++ { |
| 1531 |
var c chan int |
| 1532 |
var cv Value |
| 1533 |
|
| 1534 |
// check both ways to allocate channels |
| 1535 |
switch loop { |
| 1536 |
case 1: |
| 1537 |
c = make(chan int, 1) |
| 1538 |
cv = ValueOf(c) |
| 1539 |
case 0: |
| 1540 |
cv = MakeChan(TypeOf(c), 1) |
| 1541 |
c = cv.Interface().(chan int) |
| 1542 |
} |
| 1543 |
|
| 1544 |
// Send |
| 1545 |
cv.Send(ValueOf(2)) |
| 1546 |
if i := <-c; i != 2 { |
| 1547 |
t.Errorf("reflect Send 2, native recv %d", i) |
| 1548 |
} |
| 1549 |
|
| 1550 |
// Recv |
| 1551 |
c <- 3 |
| 1552 |
if i, ok := cv.Recv(); i.Int() != 3 || !ok { |
| 1553 |
t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok) |
| 1554 |
} |
| 1555 |
|
| 1556 |
// TryRecv fail |
| 1557 |
val, ok := cv.TryRecv() |
| 1558 |
if val.IsValid() || ok { |
| 1559 |
t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok) |
| 1560 |
} |
| 1561 |
|
| 1562 |
// TryRecv success |
| 1563 |
c <- 4 |
| 1564 |
val, ok = cv.TryRecv() |
| 1565 |
if !val.IsValid() { |
| 1566 |
t.Errorf("TryRecv on ready chan got nil") |
| 1567 |
} else if i := val.Int(); i != 4 || !ok { |
| 1568 |
t.Errorf("native send 4, TryRecv %d, %t", i, ok) |
| 1569 |
} |
| 1570 |
|
| 1571 |
// TrySend fail |
| 1572 |
c <- 100 |
| 1573 |
ok = cv.TrySend(ValueOf(5)) |
| 1574 |
i := <-c |
| 1575 |
if ok { |
| 1576 |
t.Errorf("TrySend on full chan succeeded: value %d", i) |
| 1577 |
} |
| 1578 |
|
| 1579 |
// TrySend success |
| 1580 |
ok = cv.TrySend(ValueOf(6)) |
| 1581 |
if !ok { |
| 1582 |
t.Errorf("TrySend on empty chan failed") |
| 1583 |
select { |
| 1584 |
case x := <-c: |
| 1585 |
t.Errorf("TrySend failed but it did send %d", x) |
| 1586 |
default: |
| 1587 |
} |
| 1588 |
} else { |
| 1589 |
if i = <-c; i != 6 { |
| 1590 |
t.Errorf("TrySend 6, recv %d", i) |
| 1591 |
} |
| 1592 |
} |
| 1593 |
|
| 1594 |
// Close |
| 1595 |
c <- 123 |
| 1596 |
cv.Close() |
| 1597 |
if i, ok := cv.Recv(); i.Int() != 123 || !ok { |
| 1598 |
t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok) |
| 1599 |
} |
| 1600 |
if i, ok := cv.Recv(); i.Int() != 0 || ok { |
| 1601 |
t.Errorf("after close Recv %d, %t", i.Int(), ok) |
| 1602 |
} |
| 1603 |
} |
| 1604 |
|
| 1605 |
// check creation of unbuffered channel |
| 1606 |
var c chan int |
| 1607 |
cv := MakeChan(TypeOf(c), 0) |
| 1608 |
c = cv.Interface().(chan int) |
| 1609 |
if cv.TrySend(ValueOf(7)) { |
| 1610 |
t.Errorf("TrySend on sync chan succeeded") |
| 1611 |
} |
| 1612 |
if v, ok := cv.TryRecv(); v.IsValid() || ok { |
| 1613 |
t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok) |
| 1614 |
} |
| 1615 |
|
| 1616 |
// len/cap |
| 1617 |
cv = MakeChan(TypeOf(c), 10) |
| 1618 |
c = cv.Interface().(chan int) |
| 1619 |
for i := 0; i < 3; i++ { |
| 1620 |
c <- i |
| 1621 |
} |
| 1622 |
if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) { |
| 1623 |
t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c)) |
| 1624 |
} |
| 1625 |
} |
| 1626 |
|
| 1627 |
// caseInfo describes a single case in a select test. |
| 1628 |
type caseInfo struct { |
| 1629 |
desc string |
| 1630 |
canSelect bool |
| 1631 |
recv Value |
| 1632 |
closed bool |
| 1633 |
helper func() |
| 1634 |
panic bool |
| 1635 |
} |
| 1636 |
|
| 1637 |
var allselect = flag.Bool("allselect", false, "exhaustive select test") |
| 1638 |
|
| 1639 |
func TestSelect(t *testing.T) { |
| 1640 |
selectWatch.once.Do(func() { go selectWatcher() }) |
| 1641 |
|
| 1642 |
var x exhaustive |
| 1643 |
nch := 0 |
| 1644 |
newop := func(n int, cap int) (ch, val Value) { |
| 1645 |
nch++ |
| 1646 |
if nch%101%2 == 1 { |
| 1647 |
c := make(chan int, cap) |
| 1648 |
ch = ValueOf(c) |
| 1649 |
val = ValueOf(n) |
| 1650 |
} else { |
| 1651 |
c := make(chan string, cap) |
| 1652 |
ch = ValueOf(c) |
| 1653 |
val = ValueOf(fmt.Sprint(n)) |
| 1654 |
} |
| 1655 |
return |
| 1656 |
} |
| 1657 |
|
| 1658 |
for n := 0; x.Next(); n++ { |
| 1659 |
if testing.Short() && n >= 1000 { |
| 1660 |
break |
| 1661 |
} |
| 1662 |
if n >= 100000 && !*allselect { |
| 1663 |
break |
| 1664 |
} |
| 1665 |
if n%100000 == 0 && testing.Verbose() { |
| 1666 |
println("TestSelect", n) |
| 1667 |
} |
| 1668 |
var cases []SelectCase |
| 1669 |
var info []caseInfo |
| 1670 |
|
| 1671 |
// Ready send. |
| 1672 |
if x.Maybe() { |
| 1673 |
ch, val := newop(len(cases), 1) |
| 1674 |
cases = append(cases, SelectCase{ |
| 1675 |
Dir: SelectSend, |
| 1676 |
Chan: ch, |
| 1677 |
Send: val, |
| 1678 |
}) |
| 1679 |
info = append(info, caseInfo{desc: "ready send", canSelect: true}) |
| 1680 |
} |
| 1681 |
|
| 1682 |
// Ready recv. |
| 1683 |
if x.Maybe() { |
| 1684 |
ch, val := newop(len(cases), 1) |
| 1685 |
ch.Send(val) |
| 1686 |
cases = append(cases, SelectCase{ |
| 1687 |
Dir: SelectRecv, |
| 1688 |
Chan: ch, |
| 1689 |
}) |
| 1690 |
info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val}) |
| 1691 |
} |
| 1692 |
|
| 1693 |
// Blocking send. |
| 1694 |
if x.Maybe() { |
| 1695 |
ch, val := newop(len(cases), 0) |
| 1696 |
cases = append(cases, SelectCase{ |
| 1697 |
Dir: SelectSend, |
| 1698 |
Chan: ch, |
| 1699 |
Send: val, |
| 1700 |
}) |
| 1701 |
// Let it execute? |
| 1702 |
if x.Maybe() { |
| 1703 |
f := func() { ch.Recv() } |
| 1704 |
info = append(info, caseInfo{desc: "blocking send", helper: f}) |
| 1705 |
} else { |
| 1706 |
info = append(info, caseInfo{desc: "blocking send"}) |
| 1707 |
} |
| 1708 |
} |
| 1709 |
|
| 1710 |
// Blocking recv. |
| 1711 |
if x.Maybe() { |
| 1712 |
ch, val := newop(len(cases), 0) |
| 1713 |
cases = append(cases, SelectCase{ |
| 1714 |
Dir: SelectRecv, |
| 1715 |
Chan: ch, |
| 1716 |
}) |
| 1717 |
// Let it execute? |
| 1718 |
if x.Maybe() { |
| 1719 |
f := func() { ch.Send(val) } |
| 1720 |
info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f}) |
| 1721 |
} else { |
| 1722 |
info = append(info, caseInfo{desc: "blocking recv"}) |
| 1723 |
} |
| 1724 |
} |
| 1725 |
|
| 1726 |
// Zero Chan send. |
| 1727 |
if x.Maybe() { |
| 1728 |
// Maybe include value to send. |
| 1729 |
var val Value |
| 1730 |
if x.Maybe() { |
| 1731 |
val = ValueOf(100) |
| 1732 |
} |
| 1733 |
cases = append(cases, SelectCase{ |
| 1734 |
Dir: SelectSend, |
| 1735 |
Send: val, |
| 1736 |
}) |
| 1737 |
info = append(info, caseInfo{desc: "zero Chan send"}) |
| 1738 |
} |
| 1739 |
|
| 1740 |
// Zero Chan receive. |
| 1741 |
if x.Maybe() { |
| 1742 |
cases = append(cases, SelectCase{ |
| 1743 |
Dir: SelectRecv, |
| 1744 |
}) |
| 1745 |
info = append(info, caseInfo{desc: "zero Chan recv"}) |
| 1746 |
} |
| 1747 |
|
| 1748 |
// nil Chan send. |
| 1749 |
if x.Maybe() { |
| 1750 |
cases = append(cases, SelectCase{ |
| 1751 |
Dir: SelectSend, |
| 1752 |
Chan: ValueOf((chan int)(nil)), |
| 1753 |
Send: ValueOf(101), |
| 1754 |
}) |
| 1755 |
info = append(info, caseInfo{desc: "nil Chan send"}) |
| 1756 |
} |
| 1757 |
|
| 1758 |
// nil Chan recv. |
| 1759 |
if x.Maybe() { |
| 1760 |
cases = append(cases, SelectCase{ |
| 1761 |
Dir: SelectRecv, |
| 1762 |
Chan: ValueOf((chan int)(nil)), |
| 1763 |
}) |
| 1764 |
info = append(info, caseInfo{desc: "nil Chan recv"}) |
| 1765 |
} |
| 1766 |
|
| 1767 |
// closed Chan send. |
| 1768 |
if x.Maybe() { |
| 1769 |
ch := make(chan int) |
| 1770 |
close(ch) |
| 1771 |
cases = append(cases, SelectCase{ |
| 1772 |
Dir: SelectSend, |
| 1773 |
Chan: ValueOf(ch), |
| 1774 |
Send: ValueOf(101), |
| 1775 |
}) |
| 1776 |
info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true}) |
| 1777 |
} |
| 1778 |
|
| 1779 |
// closed Chan recv. |
| 1780 |
if x.Maybe() { |
| 1781 |
ch, val := newop(len(cases), 0) |
| 1782 |
ch.Close() |
| 1783 |
val = Zero(val.Type()) |
| 1784 |
cases = append(cases, SelectCase{ |
| 1785 |
Dir: SelectRecv, |
| 1786 |
Chan: ch, |
| 1787 |
}) |
| 1788 |
info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val}) |
| 1789 |
} |
| 1790 |
|
| 1791 |
var helper func() // goroutine to help the select complete |
| 1792 |
|
| 1793 |
// Add default? Must be last case here, but will permute. |
| 1794 |
// Add the default if the select would otherwise |
| 1795 |
// block forever, and maybe add it anyway. |
| 1796 |
numCanSelect := 0 |
| 1797 |
canProceed := false |
| 1798 |
canBlock := true |
| 1799 |
canPanic := false |
| 1800 |
helpers := []int{} |
| 1801 |
for i, c := range info { |
| 1802 |
if c.canSelect { |
| 1803 |
canProceed = true |
| 1804 |
canBlock = false |
| 1805 |
numCanSelect++ |
| 1806 |
if c.panic { |
| 1807 |
canPanic = true |
| 1808 |
} |
| 1809 |
} else if c.helper != nil { |
| 1810 |
canProceed = true |
| 1811 |
helpers = append(helpers, i) |
| 1812 |
} |
| 1813 |
} |
| 1814 |
if !canProceed || x.Maybe() { |
| 1815 |
cases = append(cases, SelectCase{ |
| 1816 |
Dir: SelectDefault, |
| 1817 |
}) |
| 1818 |
info = append(info, caseInfo{desc: "default", canSelect: canBlock}) |
| 1819 |
numCanSelect++ |
| 1820 |
} else if canBlock { |
| 1821 |
// Select needs to communicate with another goroutine. |
| 1822 |
cas := &info[helpers[x.Choose(len(helpers))]] |
| 1823 |
helper = cas.helper |
| 1824 |
cas.canSelect = true |
| 1825 |
numCanSelect++ |
| 1826 |
} |
| 1827 |
|
| 1828 |
// Permute cases and case info. |
| 1829 |
// Doing too much here makes the exhaustive loop |
| 1830 |
// too exhausting, so just do two swaps. |
| 1831 |
for loop := 0; loop < 2; loop++ { |
| 1832 |
i := x.Choose(len(cases)) |
| 1833 |
j := x.Choose(len(cases)) |
| 1834 |
cases[i], cases[j] = cases[j], cases[i] |
| 1835 |
info[i], info[j] = info[j], info[i] |
| 1836 |
} |
| 1837 |
|
| 1838 |
if helper != nil { |
| 1839 |
// We wait before kicking off a goroutine to satisfy a blocked select. |
| 1840 |
// The pause needs to be big enough to let the select block before |
| 1841 |
// we run the helper, but if we lose that race once in a while it's okay: the |
| 1842 |
// select will just proceed immediately. Not a big deal. |
| 1843 |
// For short tests we can grow [sic] the timeout a bit without fear of taking too long |
| 1844 |
pause := 10 * time.Microsecond |
| 1845 |
if testing.Short() { |
| 1846 |
pause = 100 * time.Microsecond |
| 1847 |
} |
| 1848 |
time.AfterFunc(pause, helper) |
| 1849 |
} |
| 1850 |
|
| 1851 |
// Run select. |
| 1852 |
i, recv, recvOK, panicErr := runSelect(cases, info) |
| 1853 |
if panicErr != nil && !canPanic { |
| 1854 |
t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr) |
| 1855 |
} |
| 1856 |
if panicErr == nil && canPanic && numCanSelect == 1 { |
| 1857 |
t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i) |
| 1858 |
} |
| 1859 |
if panicErr != nil { |
| 1860 |
continue |
| 1861 |
} |
| 1862 |
|
| 1863 |
cas := info[i] |
| 1864 |
if !cas.canSelect { |
| 1865 |
recvStr := "" |
| 1866 |
if recv.IsValid() { |
| 1867 |
recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK) |
| 1868 |
} |
| 1869 |
t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr) |
| 1870 |
continue |
| 1871 |
} |
| 1872 |
if cas.panic { |
| 1873 |
t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i) |
| 1874 |
continue |
| 1875 |
} |
| 1876 |
|
| 1877 |
if cases[i].Dir == SelectRecv { |
| 1878 |
if !recv.IsValid() { |
| 1879 |
t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed) |
| 1880 |
} |
| 1881 |
if !cas.recv.IsValid() { |
| 1882 |
t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i) |
| 1883 |
} |
| 1884 |
if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed { |
| 1885 |
if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed { |
| 1886 |
t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface()) |
| 1887 |
} |
| 1888 |
t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed) |
| 1889 |
} |
| 1890 |
} else { |
| 1891 |
if recv.IsValid() || recvOK { |
| 1892 |
t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false) |
| 1893 |
} |
| 1894 |
} |
| 1895 |
} |
| 1896 |
} |
| 1897 |
|
| 1898 |
func TestSelectMaxCases(t *testing.T) { |
| 1899 |
var sCases []SelectCase |
| 1900 |
channel := make(chan int) |
| 1901 |
close(channel) |
| 1902 |
for i := 0; i < 65536; i++ { |
| 1903 |
sCases = append(sCases, SelectCase{ |
| 1904 |
Dir: SelectRecv, |
| 1905 |
Chan: ValueOf(channel), |
| 1906 |
}) |
| 1907 |
} |
| 1908 |
// Should not panic |
| 1909 |
_, _, _ = Select(sCases) |
| 1910 |
sCases = append(sCases, SelectCase{ |
| 1911 |
Dir: SelectRecv, |
| 1912 |
Chan: ValueOf(channel), |
| 1913 |
}) |
| 1914 |
defer func() { |
| 1915 |
if err := recover(); err != nil { |
| 1916 |
if err.(string) != "reflect.Select: too many cases (max 65536)" { |
| 1917 |
t.Fatalf("unexpected error from select call with greater than max supported cases") |
| 1918 |
} |
| 1919 |
} else { |
| 1920 |
t.Fatalf("expected select call to panic with greater than max supported cases") |
| 1921 |
} |
| 1922 |
}() |
| 1923 |
// Should panic |
| 1924 |
_, _, _ = Select(sCases) |
| 1925 |
} |
| 1926 |
|
| 1927 |
func TestSelectNop(t *testing.T) { |
| 1928 |
// "select { default: }" should always return the default case. |
| 1929 |
chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}}) |
| 1930 |
if chosen != 0 { |
| 1931 |
t.Fatalf("expected Select to return 0, but got %#v", chosen) |
| 1932 |
} |
| 1933 |
} |
| 1934 |
|
| 1935 |
func BenchmarkSelect(b *testing.B) { |
| 1936 |
channel := make(chan int) |
| 1937 |
close(channel) |
| 1938 |
var cases []SelectCase |
| 1939 |
for i := 0; i < 8; i++ { |
| 1940 |
cases = append(cases, SelectCase{ |
| 1941 |
Dir: SelectRecv, |
| 1942 |
Chan: ValueOf(channel), |
| 1943 |
}) |
| 1944 |
} |
| 1945 |
for _, numCases := range []int{1, 4, 8} { |
| 1946 |
b.Run(strconv.Itoa(numCases), func(b *testing.B) { |
| 1947 |
b.ReportAllocs() |
| 1948 |
for i := 0; i < b.N; i++ { |
| 1949 |
_, _, _ = Select(cases[:numCases]) |
| 1950 |
} |
| 1951 |
}) |
| 1952 |
} |
| 1953 |
} |
| 1954 |
|
| 1955 |
// selectWatch and the selectWatcher are a watchdog mechanism for running Select. |
| 1956 |
// If the selectWatcher notices that the select has been blocked for >1 second, it prints |
| 1957 |
// an error describing the select and panics the entire test binary. |
| 1958 |
var selectWatch struct { |
| 1959 |
sync.Mutex |
| 1960 |
once sync.Once |
| 1961 |
now time.Time |
| 1962 |
info []caseInfo |
| 1963 |
} |
| 1964 |
|
| 1965 |
func selectWatcher() { |
| 1966 |
for { |
| 1967 |
time.Sleep(1 * time.Second) |
| 1968 |
selectWatch.Lock() |
| 1969 |
if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second { |
| 1970 |
fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info)) |
| 1971 |
panic("select stuck") |
| 1972 |
} |
| 1973 |
selectWatch.Unlock() |
| 1974 |
} |
| 1975 |
} |
| 1976 |
|
| 1977 |
// runSelect runs a single select test. |
| 1978 |
// It returns the values returned by Select but also returns |
| 1979 |
// a panic value if the Select panics. |
| 1980 |
func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) { |
| 1981 |
defer func() { |
| 1982 |
panicErr = recover() |
| 1983 |
|
| 1984 |
selectWatch.Lock() |
| 1985 |
selectWatch.info = nil |
| 1986 |
selectWatch.Unlock() |
| 1987 |
}() |
| 1988 |
|
| 1989 |
selectWatch.Lock() |
| 1990 |
selectWatch.now = time.Now() |
| 1991 |
selectWatch.info = info |
| 1992 |
selectWatch.Unlock() |
| 1993 |
|
| 1994 |
chosen, recv, recvOK = Select(cases) |
| 1995 |
return |
| 1996 |
} |
| 1997 |
|
| 1998 |
// fmtSelect formats the information about a single select test. |
| 1999 |
func fmtSelect(info []caseInfo) string { |
| 2000 |
var buf bytes.Buffer |
| 2001 |
fmt.Fprintf(&buf, "\nselect {\n") |
| 2002 |
for i, cas := range info { |
| 2003 |
fmt.Fprintf(&buf, "%d: %s", i, cas.desc) |
| 2004 |
if cas.recv.IsValid() { |
| 2005 |
fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface()) |
| 2006 |
} |
| 2007 |
if cas.canSelect { |
| 2008 |
fmt.Fprintf(&buf, " canselect") |
| 2009 |
} |
| 2010 |
if cas.panic { |
| 2011 |
fmt.Fprintf(&buf, " panic") |
| 2012 |
} |
| 2013 |
fmt.Fprintf(&buf, "\n") |
| 2014 |
} |
| 2015 |
fmt.Fprintf(&buf, "}") |
| 2016 |
return buf.String() |
| 2017 |
} |
| 2018 |
|
| 2019 |
type two [2]uintptr |
| 2020 |
|
| 2021 |
// Difficult test for function call because of |
| 2022 |
// implicit padding between arguments. |
| 2023 |
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) { |
| 2024 |
return b, c, d, e, f, g, h |
| 2025 |
} |
| 2026 |
|
| 2027 |
func TestFunc(t *testing.T) { |
| 2028 |
ret := ValueOf(dummy).Call([]Value{ |
| 2029 |
ValueOf(byte(10)), |
| 2030 |
ValueOf(20), |
| 2031 |
ValueOf(byte(30)), |
| 2032 |
ValueOf(two{40, 50}), |
| 2033 |
ValueOf(byte(60)), |
| 2034 |
ValueOf(float32(70)), |
| 2035 |
ValueOf(byte(80)), |
| 2036 |
}) |
| 2037 |
if len(ret) != 7 { |
| 2038 |
t.Fatalf("Call returned %d values, want 7", len(ret)) |
| 2039 |
} |
| 2040 |
|
| 2041 |
i := byte(ret[0].Uint()) |
| 2042 |
j := int(ret[1].Int()) |
| 2043 |
k := byte(ret[2].Uint()) |
| 2044 |
l := ret[3].Interface().(two) |
| 2045 |
m := byte(ret[4].Uint()) |
| 2046 |
n := float32(ret[5].Float()) |
| 2047 |
o := byte(ret[6].Uint()) |
| 2048 |
|
| 2049 |
if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 { |
| 2050 |
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) |
| 2051 |
} |
| 2052 |
|
| 2053 |
for i, v := range ret { |
| 2054 |
if v.CanAddr() { |
| 2055 |
t.Errorf("result %d is addressable", i) |
| 2056 |
} |
| 2057 |
} |
| 2058 |
} |
| 2059 |
|
| 2060 |
func TestCallConvert(t *testing.T) { |
| 2061 |
v := ValueOf(new(io.ReadWriter)).Elem() |
| 2062 |
f := ValueOf(func(r io.Reader) io.Reader { return r }) |
| 2063 |
out := f.Call([]Value{v}) |
| 2064 |
if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() { |
| 2065 |
t.Errorf("expected [nil], got %v", out) |
| 2066 |
} |
| 2067 |
} |
| 2068 |
|
| 2069 |
type emptyStruct struct{} |
| 2070 |
|
| 2071 |
type nonEmptyStruct struct { |
| 2072 |
member int |
| 2073 |
} |
| 2074 |
|
| 2075 |
func returnEmpty() emptyStruct { |
| 2076 |
return emptyStruct{} |
| 2077 |
} |
| 2078 |
|
| 2079 |
func takesEmpty(e emptyStruct) { |
| 2080 |
} |
| 2081 |
|
| 2082 |
func returnNonEmpty(i int) nonEmptyStruct { |
| 2083 |
return nonEmptyStruct{member: i} |
| 2084 |
} |
| 2085 |
|
| 2086 |
func takesNonEmpty(n nonEmptyStruct) int { |
| 2087 |
return n.member |
| 2088 |
} |
| 2089 |
|
| 2090 |
func TestCallWithStruct(t *testing.T) { |
| 2091 |
r := ValueOf(returnEmpty).Call(nil) |
| 2092 |
if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) { |
| 2093 |
t.Errorf("returning empty struct returned %#v instead", r) |
| 2094 |
} |
| 2095 |
r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})}) |
| 2096 |
if len(r) != 0 { |
| 2097 |
t.Errorf("takesEmpty returned values: %#v", r) |
| 2098 |
} |
| 2099 |
r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)}) |
| 2100 |
if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 { |
| 2101 |
t.Errorf("returnNonEmpty returned %#v", r) |
| 2102 |
} |
| 2103 |
r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})}) |
| 2104 |
if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 { |
| 2105 |
t.Errorf("takesNonEmpty returned %#v", r) |
| 2106 |
} |
| 2107 |
} |
| 2108 |
|
| 2109 |
func TestCallReturnsEmpty(t *testing.T) { |
| 2110 |
if runtime.Compiler == "gccgo" { |
| 2111 |
t.Skip("skipping on gccgo: imprecise stack can keep i live") |
| 2112 |
} |
| 2113 |
// Issue 21717: past-the-end pointer write in Call with |
| 2114 |
// nonzero-sized frame and zero-sized return value. |
| 2115 |
runtime.GC() |
| 2116 |
var finalized uint32 |
| 2117 |
f := func() (emptyStruct, *[2]int64) { |
| 2118 |
i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies |
| 2119 |
runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) }) |
| 2120 |
return emptyStruct{}, i |
| 2121 |
} |
| 2122 |
v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run. |
| 2123 |
timeout := time.After(5 * time.Second) |
| 2124 |
for atomic.LoadUint32(&finalized) == 0 { |
| 2125 |
select { |
| 2126 |
case <-timeout: |
| 2127 |
t.Fatal("finalizer did not run") |
| 2128 |
default: |
| 2129 |
} |
| 2130 |
runtime.Gosched() |
| 2131 |
runtime.GC() |
| 2132 |
} |
| 2133 |
runtime.KeepAlive(v) |
| 2134 |
} |
| 2135 |
|
| 2136 |
func BenchmarkCall(b *testing.B) { |
| 2137 |
fv := ValueOf(func(a, b string) {}) |
| 2138 |
b.ReportAllocs() |
| 2139 |
b.RunParallel(func(pb *testing.PB) { |
| 2140 |
args := []Value{ValueOf("a"), ValueOf("b")} |
| 2141 |
for pb.Next() { |
| 2142 |
fv.Call(args) |
| 2143 |
} |
| 2144 |
}) |
| 2145 |
} |
| 2146 |
|
| 2147 |
type myint int64 |
| 2148 |
|
| 2149 |
func (i *myint) inc() { |
| 2150 |
*i = *i + 1 |
| 2151 |
} |
| 2152 |
|
| 2153 |
func BenchmarkCallMethod(b *testing.B) { |
| 2154 |
b.ReportAllocs() |
| 2155 |
z := new(myint) |
| 2156 |
|
| 2157 |
v := ValueOf(z.inc) |
| 2158 |
for i := 0; i < b.N; i++ { |
| 2159 |
v.Call(nil) |
| 2160 |
} |
| 2161 |
} |
| 2162 |
|
| 2163 |
func BenchmarkCallArgCopy(b *testing.B) { |
| 2164 |
byteArray := func(n int) Value { |
| 2165 |
return Zero(ArrayOf(n, TypeOf(byte(0)))) |
| 2166 |
} |
| 2167 |
sizes := [...]struct { |
| 2168 |
fv Value |
| 2169 |
arg Value |
| 2170 |
}{ |
| 2171 |
{ValueOf(func(a [128]byte) {}), byteArray(128)}, |
| 2172 |
{ValueOf(func(a [256]byte) {}), byteArray(256)}, |
| 2173 |
{ValueOf(func(a [1024]byte) {}), byteArray(1024)}, |
| 2174 |
{ValueOf(func(a [4096]byte) {}), byteArray(4096)}, |
| 2175 |
{ValueOf(func(a [65536]byte) {}), byteArray(65536)}, |
| 2176 |
} |
| 2177 |
for _, size := range sizes { |
| 2178 |
bench := func(b *testing.B) { |
| 2179 |
args := []Value{size.arg} |
| 2180 |
b.SetBytes(int64(size.arg.Len())) |
| 2181 |
b.ResetTimer() |
| 2182 |
b.RunParallel(func(pb *testing.PB) { |
| 2183 |
for pb.Next() { |
| 2184 |
size.fv.Call(args) |
| 2185 |
} |
| 2186 |
}) |
| 2187 |
} |
| 2188 |
name := fmt.Sprintf("size=%v", size.arg.Len()) |
| 2189 |
b.Run(name, bench) |
| 2190 |
} |
| 2191 |
} |
| 2192 |
|
| 2193 |
func TestMakeFunc(t *testing.T) { |
| 2194 |
f := dummy |
| 2195 |
fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in }) |
| 2196 |
ValueOf(&f).Elem().Set(fv) |
| 2197 |
|
| 2198 |
// Call g with small arguments so that there is |
| 2199 |
// something predictable (and different from the |
| 2200 |
// correct results) in those positions on the stack. |
| 2201 |
g := dummy |
| 2202 |
g(1, 2, 3, two{4, 5}, 6, 7, 8) |
| 2203 |
|
| 2204 |
// Call constructed function f. |
| 2205 |
i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80) |
| 2206 |
if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 { |
| 2207 |
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) |
| 2208 |
} |
| 2209 |
} |
| 2210 |
|
| 2211 |
func TestMakeFuncInterface(t *testing.T) { |
| 2212 |
fn := func(i int) int { return i } |
| 2213 |
incr := func(in []Value) []Value { |
| 2214 |
return []Value{ValueOf(int(in[0].Int() + 1))} |
| 2215 |
} |
| 2216 |
fv := MakeFunc(TypeOf(fn), incr) |
| 2217 |
ValueOf(&fn).Elem().Set(fv) |
| 2218 |
if r := fn(2); r != 3 { |
| 2219 |
t.Errorf("Call returned %d, want 3", r) |
| 2220 |
} |
| 2221 |
if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 { |
| 2222 |
t.Errorf("Call returned %d, want 15", r) |
| 2223 |
} |
| 2224 |
if r := fv.Interface().(func(int) int)(26); r != 27 { |
| 2225 |
t.Errorf("Call returned %d, want 27", r) |
| 2226 |
} |
| 2227 |
} |
| 2228 |
|
| 2229 |
func TestMakeFuncVariadic(t *testing.T) { |
| 2230 |
// Test that variadic arguments are packed into a slice and passed as last arg |
| 2231 |
fn := func(_ int, is ...int) []int { return nil } |
| 2232 |
fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] }) |
| 2233 |
ValueOf(&fn).Elem().Set(fv) |
| 2234 |
|
| 2235 |
r := fn(1, 2, 3) |
| 2236 |
if r[0] != 2 || r[1] != 3 { |
| 2237 |
t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) |
| 2238 |
} |
| 2239 |
|
| 2240 |
r = fn(1, []int{2, 3}...) |
| 2241 |
if r[0] != 2 || r[1] != 3 { |
| 2242 |
t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) |
| 2243 |
} |
| 2244 |
|
| 2245 |
r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int) |
| 2246 |
if r[0] != 2 || r[1] != 3 { |
| 2247 |
t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) |
| 2248 |
} |
| 2249 |
|
| 2250 |
r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int) |
| 2251 |
if r[0] != 2 || r[1] != 3 { |
| 2252 |
t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) |
| 2253 |
} |
| 2254 |
|
| 2255 |
f := fv.Interface().(func(int, ...int) []int) |
| 2256 |
|
| 2257 |
r = f(1, 2, 3) |
| 2258 |
if r[0] != 2 || r[1] != 3 { |
| 2259 |
t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) |
| 2260 |
} |
| 2261 |
r = f(1, []int{2, 3}...) |
| 2262 |
if r[0] != 2 || r[1] != 3 { |
| 2263 |
t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) |
| 2264 |
} |
| 2265 |
} |
| 2266 |
|
| 2267 |
// Dummy type that implements io.WriteCloser |
| 2268 |
type WC struct { |
| 2269 |
} |
| 2270 |
|
| 2271 |
func (w *WC) Write(p []byte) (n int, err error) { |
| 2272 |
return 0, nil |
| 2273 |
} |
| 2274 |
func (w *WC) Close() error { |
| 2275 |
return nil |
| 2276 |
} |
| 2277 |
|
| 2278 |
func TestMakeFuncValidReturnAssignments(t *testing.T) { |
| 2279 |
// reflect.Values returned from the wrapped function should be assignment-converted |
| 2280 |
// to the types returned by the result of MakeFunc. |
| 2281 |
|
| 2282 |
// Concrete types should be promotable to interfaces they implement. |
| 2283 |
var f func() error |
| 2284 |
f = MakeFunc(TypeOf(f), func([]Value) []Value { |
| 2285 |
return []Value{ValueOf(io.EOF)} |
| 2286 |
}).Interface().(func() error) |
| 2287 |
f() |
| 2288 |
|
| 2289 |
// Super-interfaces should be promotable to simpler interfaces. |
| 2290 |
var g func() io.Writer |
| 2291 |
g = MakeFunc(TypeOf(g), func([]Value) []Value { |
| 2292 |
var w io.WriteCloser = &WC{} |
| 2293 |
return []Value{ValueOf(&w).Elem()} |
| 2294 |
}).Interface().(func() io.Writer) |
| 2295 |
g() |
| 2296 |
|
| 2297 |
// Channels should be promotable to directional channels. |
| 2298 |
var h func() <-chan int |
| 2299 |
h = MakeFunc(TypeOf(h), func([]Value) []Value { |
| 2300 |
return []Value{ValueOf(make(chan int))} |
| 2301 |
}).Interface().(func() <-chan int) |
| 2302 |
h() |
| 2303 |
|
| 2304 |
// Unnamed types should be promotable to named types. |
| 2305 |
type T struct{ a, b, c int } |
| 2306 |
var i func() T |
| 2307 |
i = MakeFunc(TypeOf(i), func([]Value) []Value { |
| 2308 |
return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})} |
| 2309 |
}).Interface().(func() T) |
| 2310 |
i() |
| 2311 |
} |
| 2312 |
|
| 2313 |
func TestMakeFuncInvalidReturnAssignments(t *testing.T) { |
| 2314 |
// Type doesn't implement the required interface. |
| 2315 |
shouldPanic("", func() { |
| 2316 |
var f func() error |
| 2317 |
f = MakeFunc(TypeOf(f), func([]Value) []Value { |
| 2318 |
return []Value{ValueOf(int(7))} |
| 2319 |
}).Interface().(func() error) |
| 2320 |
f() |
| 2321 |
}) |
| 2322 |
// Assigning to an interface with additional methods. |
| 2323 |
shouldPanic("", func() { |
| 2324 |
var f func() io.ReadWriteCloser |
| 2325 |
f = MakeFunc(TypeOf(f), func([]Value) []Value { |
| 2326 |
var w io.WriteCloser = &WC{} |
| 2327 |
return []Value{ValueOf(&w).Elem()} |
| 2328 |
}).Interface().(func() io.ReadWriteCloser) |
| 2329 |
f() |
| 2330 |
}) |
| 2331 |
// Directional channels can't be assigned to bidirectional ones. |
| 2332 |
shouldPanic("", func() { |
| 2333 |
var f func() chan int |
| 2334 |
f = MakeFunc(TypeOf(f), func([]Value) []Value { |
| 2335 |
var c <-chan int = make(chan int) |
| 2336 |
return []Value{ValueOf(c)} |
| 2337 |
}).Interface().(func() chan int) |
| 2338 |
f() |
| 2339 |
}) |
| 2340 |
// Two named types which are otherwise identical. |
| 2341 |
shouldPanic("", func() { |
| 2342 |
type T struct{ a, b, c int } |
| 2343 |
type U struct{ a, b, c int } |
| 2344 |
var f func() T |
| 2345 |
f = MakeFunc(TypeOf(f), func([]Value) []Value { |
| 2346 |
return []Value{ValueOf(U{a: 1, b: 2, c: 3})} |
| 2347 |
}).Interface().(func() T) |
| 2348 |
f() |
| 2349 |
}) |
| 2350 |
} |
| 2351 |
|
| 2352 |
type Point struct { |
| 2353 |
x, y int |
| 2354 |
} |
| 2355 |
|
| 2356 |
// This will be index 0. |
| 2357 |
func (p Point) AnotherMethod(scale int) int { |
| 2358 |
return -1 |
| 2359 |
} |
| 2360 |
|
| 2361 |
// This will be index 1. |
| 2362 |
func (p Point) Dist(scale int) int { |
| 2363 |
//println("Point.Dist", p.x, p.y, scale) |
| 2364 |
return p.x*p.x*scale + p.y*p.y*scale |
| 2365 |
} |
| 2366 |
|
| 2367 |
// This will be index 2. |
| 2368 |
func (p Point) GCMethod(k int) int { |
| 2369 |
runtime.GC() |
| 2370 |
return k + p.x |
| 2371 |
} |
| 2372 |
|
| 2373 |
// This will be index 3. |
| 2374 |
func (p Point) NoArgs() { |
| 2375 |
// Exercise no-argument/no-result paths. |
| 2376 |
} |
| 2377 |
|
| 2378 |
// This will be index 4. |
| 2379 |
func (p Point) TotalDist(points ...Point) int { |
| 2380 |
tot := 0 |
| 2381 |
for _, q := range points { |
| 2382 |
dx := q.x - p.x |
| 2383 |
dy := q.y - p.y |
| 2384 |
tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test. |
| 2385 |
|
| 2386 |
} |
| 2387 |
return tot |
| 2388 |
} |
| 2389 |
|
| 2390 |
// This will be index 5. |
| 2391 |
func (p *Point) Int64Method(x int64) int64 { |
| 2392 |
return x |
| 2393 |
} |
| 2394 |
|
| 2395 |
// This will be index 6. |
| 2396 |
func (p *Point) Int32Method(x int32) int32 { |
| 2397 |
return x |
| 2398 |
} |
| 2399 |
|
| 2400 |
func TestMethod(t *testing.T) { |
| 2401 |
// Non-curried method of type. |
| 2402 |
p := Point{3, 4} |
| 2403 |
i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int() |
| 2404 |
if i != 250 { |
| 2405 |
t.Errorf("Type Method returned %d; want 250", i) |
| 2406 |
} |
| 2407 |
|
| 2408 |
m, ok := TypeOf(p).MethodByName("Dist") |
| 2409 |
if !ok { |
| 2410 |
t.Fatalf("method by name failed") |
| 2411 |
} |
| 2412 |
i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int() |
| 2413 |
if i != 275 { |
| 2414 |
t.Errorf("Type MethodByName returned %d; want 275", i) |
| 2415 |
} |
| 2416 |
|
| 2417 |
m, ok = TypeOf(p).MethodByName("NoArgs") |
| 2418 |
if !ok { |
| 2419 |
t.Fatalf("method by name failed") |
| 2420 |
} |
| 2421 |
n := len(m.Func.Call([]Value{ValueOf(p)})) |
| 2422 |
if n != 0 { |
| 2423 |
t.Errorf("NoArgs returned %d values; want 0", n) |
| 2424 |
} |
| 2425 |
|
| 2426 |
i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int() |
| 2427 |
if i != 300 { |
| 2428 |
t.Errorf("Pointer Type Method returned %d; want 300", i) |
| 2429 |
} |
| 2430 |
|
| 2431 |
m, ok = TypeOf(&p).MethodByName("Dist") |
| 2432 |
if !ok { |
| 2433 |
t.Fatalf("ptr method by name failed") |
| 2434 |
} |
| 2435 |
i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int() |
| 2436 |
if i != 325 { |
| 2437 |
t.Errorf("Pointer Type MethodByName returned %d; want 325", i) |
| 2438 |
} |
| 2439 |
|
| 2440 |
m, ok = TypeOf(&p).MethodByName("NoArgs") |
| 2441 |
if !ok { |
| 2442 |
t.Fatalf("method by name failed") |
| 2443 |
} |
| 2444 |
n = len(m.Func.Call([]Value{ValueOf(&p)})) |
| 2445 |
if n != 0 { |
| 2446 |
t.Errorf("NoArgs returned %d values; want 0", n) |
| 2447 |
} |
| 2448 |
|
| 2449 |
// Curried method of value. |
| 2450 |
tfunc := TypeOf((func(int) int)(nil)) |
| 2451 |
v := ValueOf(p).Method(1) |
| 2452 |
if tt := v.Type(); tt != tfunc { |
| 2453 |
t.Errorf("Value Method Type is %s; want %s", tt, tfunc) |
| 2454 |
} |
| 2455 |
i = v.Call([]Value{ValueOf(14)})[0].Int() |
| 2456 |
if i != 350 { |
| 2457 |
t.Errorf("Value Method returned %d; want 350", i) |
| 2458 |
} |
| 2459 |
v = ValueOf(p).MethodByName("Dist") |
| 2460 |
if tt := v.Type(); tt != tfunc { |
| 2461 |
t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc) |
| 2462 |
} |
| 2463 |
i = v.Call([]Value{ValueOf(15)})[0].Int() |
| 2464 |
if i != 375 { |
| 2465 |
t.Errorf("Value MethodByName returned %d; want 375", i) |
| 2466 |
} |
| 2467 |
v = ValueOf(p).MethodByName("NoArgs") |
| 2468 |
v.Call(nil) |
| 2469 |
|
| 2470 |
// Curried method of pointer. |
| 2471 |
v = ValueOf(&p).Method(1) |
| 2472 |
if tt := v.Type(); tt != tfunc { |
| 2473 |
t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc) |
| 2474 |
} |
| 2475 |
i = v.Call([]Value{ValueOf(16)})[0].Int() |
| 2476 |
if i != 400 { |
| 2477 |
t.Errorf("Pointer Value Method returned %d; want 400", i) |
| 2478 |
} |
| 2479 |
v = ValueOf(&p).MethodByName("Dist") |
| 2480 |
if tt := v.Type(); tt != tfunc { |
| 2481 |
t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc) |
| 2482 |
} |
| 2483 |
i = v.Call([]Value{ValueOf(17)})[0].Int() |
| 2484 |
if i != 425 { |
| 2485 |
t.Errorf("Pointer Value MethodByName returned %d; want 425", i) |
| 2486 |
} |
| 2487 |
v = ValueOf(&p).MethodByName("NoArgs") |
| 2488 |
v.Call(nil) |
| 2489 |
|
| 2490 |
// Curried method of interface value. |
| 2491 |
// Have to wrap interface value in a struct to get at it. |
| 2492 |
// Passing it to ValueOf directly would |
| 2493 |
// access the underlying Point, not the interface. |
| 2494 |
var x interface { |
| 2495 |
Dist(int) int |
| 2496 |
} = p |
| 2497 |
pv := ValueOf(&x).Elem() |
| 2498 |
v = pv.Method(0) |
| 2499 |
if tt := v.Type(); tt != tfunc { |
| 2500 |
t.Errorf("Interface Method Type is %s; want %s", tt, tfunc) |
| 2501 |
} |
| 2502 |
i = v.Call([]Value{ValueOf(18)})[0].Int() |
| 2503 |
if i != 450 { |
| 2504 |
t.Errorf("Interface Method returned %d; want 450", i) |
| 2505 |
} |
| 2506 |
v = pv.MethodByName("Dist") |
| 2507 |
if tt := v.Type(); tt != tfunc { |
| 2508 |
t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc) |
| 2509 |
} |
| 2510 |
i = v.Call([]Value{ValueOf(19)})[0].Int() |
| 2511 |
if i != 475 { |
| 2512 |
t.Errorf("Interface MethodByName returned %d; want 475", i) |
| 2513 |
} |
| 2514 |
} |
| 2515 |
|
| 2516 |
func TestMethodValue(t *testing.T) { |
| 2517 |
p := Point{3, 4} |
| 2518 |
var i int64 |
| 2519 |
|
| 2520 |
// Check that method value have the same underlying code pointers. |
| 2521 |
if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() { |
| 2522 |
t.Errorf("methodValueCall mismatched: %v - %v", p1, p2) |
| 2523 |
} |
| 2524 |
|
| 2525 |
// Curried method of value. |
| 2526 |
tfunc := TypeOf((func(int) int)(nil)) |
| 2527 |
v := ValueOf(p).Method(1) |
| 2528 |
if tt := v.Type(); tt != tfunc { |
| 2529 |
t.Errorf("Value Method Type is %s; want %s", tt, tfunc) |
| 2530 |
} |
| 2531 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int() |
| 2532 |
if i != 250 { |
| 2533 |
t.Errorf("Value Method returned %d; want 250", i) |
| 2534 |
} |
| 2535 |
v = ValueOf(p).MethodByName("Dist") |
| 2536 |
if tt := v.Type(); tt != tfunc { |
| 2537 |
t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc) |
| 2538 |
} |
| 2539 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int() |
| 2540 |
if i != 275 { |
| 2541 |
t.Errorf("Value MethodByName returned %d; want 275", i) |
| 2542 |
} |
| 2543 |
v = ValueOf(p).MethodByName("NoArgs") |
| 2544 |
ValueOf(v.Interface()).Call(nil) |
| 2545 |
v.Interface().(func())() |
| 2546 |
|
| 2547 |
// Curried method of pointer. |
| 2548 |
v = ValueOf(&p).Method(1) |
| 2549 |
if tt := v.Type(); tt != tfunc { |
| 2550 |
t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc) |
| 2551 |
} |
| 2552 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int() |
| 2553 |
if i != 300 { |
| 2554 |
t.Errorf("Pointer Value Method returned %d; want 300", i) |
| 2555 |
} |
| 2556 |
v = ValueOf(&p).MethodByName("Dist") |
| 2557 |
if tt := v.Type(); tt != tfunc { |
| 2558 |
t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc) |
| 2559 |
} |
| 2560 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int() |
| 2561 |
if i != 325 { |
| 2562 |
t.Errorf("Pointer Value MethodByName returned %d; want 325", i) |
| 2563 |
} |
| 2564 |
v = ValueOf(&p).MethodByName("NoArgs") |
| 2565 |
ValueOf(v.Interface()).Call(nil) |
| 2566 |
v.Interface().(func())() |
| 2567 |
|
| 2568 |
// Curried method of pointer to pointer. |
| 2569 |
pp := &p |
| 2570 |
v = ValueOf(&pp).Elem().Method(1) |
| 2571 |
if tt := v.Type(); tt != tfunc { |
| 2572 |
t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc) |
| 2573 |
} |
| 2574 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int() |
| 2575 |
if i != 350 { |
| 2576 |
t.Errorf("Pointer Pointer Value Method returned %d; want 350", i) |
| 2577 |
} |
| 2578 |
v = ValueOf(&pp).Elem().MethodByName("Dist") |
| 2579 |
if tt := v.Type(); tt != tfunc { |
| 2580 |
t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc) |
| 2581 |
} |
| 2582 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int() |
| 2583 |
if i != 375 { |
| 2584 |
t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i) |
| 2585 |
} |
| 2586 |
|
| 2587 |
// Curried method of interface value. |
| 2588 |
// Have to wrap interface value in a struct to get at it. |
| 2589 |
// Passing it to ValueOf directly would |
| 2590 |
// access the underlying Point, not the interface. |
| 2591 |
var s = struct { |
| 2592 |
X interface { |
| 2593 |
Dist(int) int |
| 2594 |
} |
| 2595 |
}{p} |
| 2596 |
pv := ValueOf(s).Field(0) |
| 2597 |
v = pv.Method(0) |
| 2598 |
if tt := v.Type(); tt != tfunc { |
| 2599 |
t.Errorf("Interface Method Type is %s; want %s", tt, tfunc) |
| 2600 |
} |
| 2601 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int() |
| 2602 |
if i != 400 { |
| 2603 |
t.Errorf("Interface Method returned %d; want 400", i) |
| 2604 |
} |
| 2605 |
v = pv.MethodByName("Dist") |
| 2606 |
if tt := v.Type(); tt != tfunc { |
| 2607 |
t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc) |
| 2608 |
} |
| 2609 |
i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int() |
| 2610 |
if i != 425 { |
| 2611 |
t.Errorf("Interface MethodByName returned %d; want 425", i) |
| 2612 |
} |
| 2613 |
|
| 2614 |
// For issue #33628: method args are not stored at the right offset |
| 2615 |
// on amd64p32. |
| 2616 |
m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64) |
| 2617 |
if x := m64(123); x != 123 { |
| 2618 |
t.Errorf("Int64Method returned %d; want 123", x) |
| 2619 |
} |
| 2620 |
m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32) |
| 2621 |
if x := m32(456); x != 456 { |
| 2622 |
t.Errorf("Int32Method returned %d; want 456", x) |
| 2623 |
} |
| 2624 |
} |
| 2625 |
|
| 2626 |
func TestVariadicMethodValue(t *testing.T) { |
| 2627 |
p := Point{3, 4} |
| 2628 |
points := []Point{{20, 21}, {22, 23}, {24, 25}} |
| 2629 |
want := int64(p.TotalDist(points[0], points[1], points[2])) |
| 2630 |
|
| 2631 |
// Variadic method of type. |
| 2632 |
tfunc := TypeOf((func(Point, ...Point) int)(nil)) |
| 2633 |
if tt := TypeOf(p).Method(4).Type; tt != tfunc { |
| 2634 |
t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc) |
| 2635 |
} |
| 2636 |
|
| 2637 |
// Curried method of value. |
| 2638 |
tfunc = TypeOf((func(...Point) int)(nil)) |
| 2639 |
v := ValueOf(p).Method(4) |
| 2640 |
if tt := v.Type(); tt != tfunc { |
| 2641 |
t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc) |
| 2642 |
} |
| 2643 |
i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int() |
| 2644 |
if i != want { |
| 2645 |
t.Errorf("Variadic Method returned %d; want %d", i, want) |
| 2646 |
} |
| 2647 |
i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int() |
| 2648 |
if i != want { |
| 2649 |
t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want) |
| 2650 |
} |
| 2651 |
|
| 2652 |
f := v.Interface().(func(...Point) int) |
| 2653 |
i = int64(f(points[0], points[1], points[2])) |
| 2654 |
if i != want { |
| 2655 |
t.Errorf("Variadic Method Interface returned %d; want %d", i, want) |
| 2656 |
} |
| 2657 |
i = int64(f(points...)) |
| 2658 |
if i != want { |
| 2659 |
t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want) |
| 2660 |
} |
| 2661 |
} |
| 2662 |
|
| 2663 |
type DirectIfaceT struct { |
| 2664 |
p *int |
| 2665 |
} |
| 2666 |
|
| 2667 |
func (d DirectIfaceT) M() int { return *d.p } |
| 2668 |
|
| 2669 |
func TestDirectIfaceMethod(t *testing.T) { |
| 2670 |
x := 42 |
| 2671 |
v := DirectIfaceT{&x} |
| 2672 |
typ := TypeOf(v) |
| 2673 |
m, ok := typ.MethodByName("M") |
| 2674 |
if !ok { |
| 2675 |
t.Fatalf("cannot find method M") |
| 2676 |
} |
| 2677 |
in := []Value{ValueOf(v)} |
| 2678 |
out := m.Func.Call(in) |
| 2679 |
if got := out[0].Int(); got != 42 { |
| 2680 |
t.Errorf("Call with value receiver got %d, want 42", got) |
| 2681 |
} |
| 2682 |
|
| 2683 |
pv := &v |
| 2684 |
typ = TypeOf(pv) |
| 2685 |
m, ok = typ.MethodByName("M") |
| 2686 |
if !ok { |
| 2687 |
t.Fatalf("cannot find method M") |
| 2688 |
} |
| 2689 |
in = []Value{ValueOf(pv)} |
| 2690 |
out = m.Func.Call(in) |
| 2691 |
if got := out[0].Int(); got != 42 { |
| 2692 |
t.Errorf("Call with pointer receiver got %d, want 42", got) |
| 2693 |
} |
| 2694 |
} |
| 2695 |
|
| 2696 |
// Reflect version of $GOROOT/test/method5.go |
| 2697 |
|
| 2698 |
// Concrete types implementing M method. |
| 2699 |
// Smaller than a word, word-sized, larger than a word. |
| 2700 |
// Value and pointer receivers. |
| 2701 |
|
| 2702 |
type Tinter interface { |
| 2703 |
M(int, byte) (byte, int) |
| 2704 |
} |
| 2705 |
|
| 2706 |
type Tsmallv byte |
| 2707 |
|
| 2708 |
func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) } |
| 2709 |
|
| 2710 |
type Tsmallp byte |
| 2711 |
|
| 2712 |
func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) } |
| 2713 |
|
| 2714 |
type Twordv uintptr |
| 2715 |
|
| 2716 |
func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) } |
| 2717 |
|
| 2718 |
type Twordp uintptr |
| 2719 |
|
| 2720 |
func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) } |
| 2721 |
|
| 2722 |
type Tbigv [2]uintptr |
| 2723 |
|
| 2724 |
func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) } |
| 2725 |
|
| 2726 |
type Tbigp [2]uintptr |
| 2727 |
|
| 2728 |
func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) } |
| 2729 |
|
| 2730 |
type tinter interface { |
| 2731 |
m(int, byte) (byte, int) |
| 2732 |
} |
| 2733 |
|
| 2734 |
// Embedding via pointer. |
| 2735 |
|
| 2736 |
type Tm1 struct { |
| 2737 |
Tm2 |
| 2738 |
} |
| 2739 |
|
| 2740 |
type Tm2 struct { |
| 2741 |
*Tm3 |
| 2742 |
} |
| 2743 |
|
| 2744 |
type Tm3 struct { |
| 2745 |
*Tm4 |
| 2746 |
} |
| 2747 |
|
| 2748 |
type Tm4 struct { |
| 2749 |
} |
| 2750 |
|
| 2751 |
func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 } |
| 2752 |
|
| 2753 |
func TestMethod5(t *testing.T) { |
| 2754 |
CheckF := func(name string, f func(int, byte) (byte, int), inc int) { |
| 2755 |
b, x := f(1000, 99) |
| 2756 |
if b != 99 || x != 1000+inc { |
| 2757 |
t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc) |
| 2758 |
} |
| 2759 |
} |
| 2760 |
|
| 2761 |
CheckV := func(name string, i Value, inc int) { |
| 2762 |
bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))}) |
| 2763 |
b := bx[0].Interface() |
| 2764 |
x := bx[1].Interface() |
| 2765 |
if b != byte(99) || x != 1000+inc { |
| 2766 |
t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc) |
| 2767 |
} |
| 2768 |
|
| 2769 |
CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc) |
| 2770 |
} |
| 2771 |
|
| 2772 |
var TinterType = TypeOf(new(Tinter)).Elem() |
| 2773 |
|
| 2774 |
CheckI := func(name string, i any, inc int) { |
| 2775 |
v := ValueOf(i) |
| 2776 |
CheckV(name, v, inc) |
| 2777 |
CheckV("(i="+name+")", v.Convert(TinterType), inc) |
| 2778 |
} |
| 2779 |
|
| 2780 |
sv := Tsmallv(1) |
| 2781 |
CheckI("sv", sv, 1) |
| 2782 |
CheckI("&sv", &sv, 1) |
| 2783 |
|
| 2784 |
sp := Tsmallp(2) |
| 2785 |
CheckI("&sp", &sp, 2) |
| 2786 |
|
| 2787 |
wv := Twordv(3) |
| 2788 |
CheckI("wv", wv, 3) |
| 2789 |
CheckI("&wv", &wv, 3) |
| 2790 |
|
| 2791 |
wp := Twordp(4) |
| 2792 |
CheckI("&wp", &wp, 4) |
| 2793 |
|
| 2794 |
bv := Tbigv([2]uintptr{5, 6}) |
| 2795 |
CheckI("bv", bv, 11) |
| 2796 |
CheckI("&bv", &bv, 11) |
| 2797 |
|
| 2798 |
bp := Tbigp([2]uintptr{7, 8}) |
| 2799 |
CheckI("&bp", &bp, 15) |
| 2800 |
|
| 2801 |
t4 := Tm4{} |
| 2802 |
t3 := Tm3{&t4} |
| 2803 |
t2 := Tm2{&t3} |
| 2804 |
t1 := Tm1{t2} |
| 2805 |
CheckI("t4", t4, 40) |
| 2806 |
CheckI("&t4", &t4, 40) |
| 2807 |
CheckI("t3", t3, 40) |
| 2808 |
CheckI("&t3", &t3, 40) |
| 2809 |
CheckI("t2", t2, 40) |
| 2810 |
CheckI("&t2", &t2, 40) |
| 2811 |
CheckI("t1", t1, 40) |
| 2812 |
CheckI("&t1", &t1, 40) |
| 2813 |
|
| 2814 |
var tnil Tinter |
| 2815 |
vnil := ValueOf(&tnil).Elem() |
| 2816 |
shouldPanic("Method", func() { vnil.Method(0) }) |
| 2817 |
} |
| 2818 |
|
| 2819 |
func TestInterfaceSet(t *testing.T) { |
| 2820 |
p := &Point{3, 4} |
| 2821 |
|
| 2822 |
var s struct { |
| 2823 |
I any |
| 2824 |
P interface { |
| 2825 |
Dist(int) int |
| 2826 |
} |
| 2827 |
} |
| 2828 |
sv := ValueOf(&s).Elem() |
| 2829 |
sv.Field(0).Set(ValueOf(p)) |
| 2830 |
if q := s.I.(*Point); q != p { |
| 2831 |
t.Errorf("i: have %p want %p", q, p) |
| 2832 |
} |
| 2833 |
|
| 2834 |
pv := sv.Field(1) |
| 2835 |
pv.Set(ValueOf(p)) |
| 2836 |
if q := s.P.(*Point); q != p { |
| 2837 |
t.Errorf("i: have %p want %p", q, p) |
| 2838 |
} |
| 2839 |
|
| 2840 |
i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int() |
| 2841 |
if i != 250 { |
| 2842 |
t.Errorf("Interface Method returned %d; want 250", i) |
| 2843 |
} |
| 2844 |
} |
| 2845 |
|
| 2846 |
type T1 struct { |
| 2847 |
a string |
| 2848 |
int |
| 2849 |
} |
| 2850 |
|
| 2851 |
func TestAnonymousFields(t *testing.T) { |
| 2852 |
var field StructField |
| 2853 |
var ok bool |
| 2854 |
var t1 T1 |
| 2855 |
type1 := TypeOf(t1) |
| 2856 |
if field, ok = type1.FieldByName("int"); !ok { |
| 2857 |
t.Fatal("no field 'int'") |
| 2858 |
} |
| 2859 |
if field.Index[0] != 1 { |
| 2860 |
t.Error("field index should be 1; is", field.Index) |
| 2861 |
} |
| 2862 |
} |
| 2863 |
|
| 2864 |
type FTest struct { |
| 2865 |
s any |
| 2866 |
name string |
| 2867 |
index []int |
| 2868 |
value int |
| 2869 |
} |
| 2870 |
|
| 2871 |
type D1 struct { |
| 2872 |
d int |
| 2873 |
} |
| 2874 |
type D2 struct { |
| 2875 |
d int |
| 2876 |
} |
| 2877 |
|
| 2878 |
type S0 struct { |
| 2879 |
A, B, C int |
| 2880 |
D1 |
| 2881 |
D2 |
| 2882 |
} |
| 2883 |
|
| 2884 |
type S1 struct { |
| 2885 |
B int |
| 2886 |
S0 |
| 2887 |
} |
| 2888 |
|
| 2889 |
type S2 struct { |
| 2890 |
A int |
| 2891 |
*S1 |
| 2892 |
} |
| 2893 |
|
| 2894 |
type S1x struct { |
| 2895 |
S1 |
| 2896 |
} |
| 2897 |
|
| 2898 |
type S1y struct { |
| 2899 |
S1 |
| 2900 |
} |
| 2901 |
|
| 2902 |
type S3 struct { |
| 2903 |
S1x |
| 2904 |
S2 |
| 2905 |
D, E int |
| 2906 |
*S1y |
| 2907 |
} |
| 2908 |
|
| 2909 |
type S4 struct { |
| 2910 |
*S4 |
| 2911 |
A int |
| 2912 |
} |
| 2913 |
|
| 2914 |
// The X in S6 and S7 annihilate, but they also block the X in S8.S9. |
| 2915 |
type S5 struct { |
| 2916 |
S6 |
| 2917 |
S7 |
| 2918 |
S8 |
| 2919 |
} |
| 2920 |
|
| 2921 |
type S6 struct { |
| 2922 |
X int |
| 2923 |
} |
| 2924 |
|
| 2925 |
type S7 S6 |
| 2926 |
|
| 2927 |
type S8 struct { |
| 2928 |
S9 |
| 2929 |
} |
| 2930 |
|
| 2931 |
type S9 struct { |
| 2932 |
X int |
| 2933 |
Y int |
| 2934 |
} |
| 2935 |
|
| 2936 |
// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. |
| 2937 |
type S10 struct { |
| 2938 |
S11 |
| 2939 |
S12 |
| 2940 |
S13 |
| 2941 |
} |
| 2942 |
|
| 2943 |
type S11 struct { |
| 2944 |
S6 |
| 2945 |
} |
| 2946 |
|
| 2947 |
type S12 struct { |
| 2948 |
S6 |
| 2949 |
} |
| 2950 |
|
| 2951 |
type S13 struct { |
| 2952 |
S8 |
| 2953 |
} |
| 2954 |
|
| 2955 |
// The X in S15.S11.S1 and S16.S11.S1 annihilate. |
| 2956 |
type S14 struct { |
| 2957 |
S15 |
| 2958 |
S16 |
| 2959 |
} |
| 2960 |
|
| 2961 |
type S15 struct { |
| 2962 |
S11 |
| 2963 |
} |
| 2964 |
|
| 2965 |
type S16 struct { |
| 2966 |
S11 |
| 2967 |
} |
| 2968 |
|
| 2969 |
var fieldTests = []FTest{ |
| 2970 |
{struct{}{}, "", nil, 0}, |
| 2971 |
{struct{}{}, "Foo", nil, 0}, |
| 2972 |
{S0{A: 'a'}, "A", []int{0}, 'a'}, |
| 2973 |
{S0{}, "D", nil, 0}, |
| 2974 |
{S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'}, |
| 2975 |
{S1{B: 'b'}, "B", []int{0}, 'b'}, |
| 2976 |
{S1{}, "S0", []int{1}, 0}, |
| 2977 |
{S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'}, |
| 2978 |
{S2{A: 'a'}, "A", []int{0}, 'a'}, |
| 2979 |
{S2{}, "S1", []int{1}, 0}, |
| 2980 |
{S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'}, |
| 2981 |
{S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'}, |
| 2982 |
{S2{}, "D", nil, 0}, |
| 2983 |
{S3{}, "S1", nil, 0}, |
| 2984 |
{S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'}, |
| 2985 |
{S3{}, "B", nil, 0}, |
| 2986 |
{S3{D: 'd'}, "D", []int{2}, 0}, |
| 2987 |
{S3{E: 'e'}, "E", []int{3}, 'e'}, |
| 2988 |
{S4{A: 'a'}, "A", []int{1}, 'a'}, |
| 2989 |
{S4{}, "B", nil, 0}, |
| 2990 |
{S5{}, "X", nil, 0}, |
| 2991 |
{S5{}, "Y", []int{2, 0, 1}, 0}, |
| 2992 |
{S10{}, "X", nil, 0}, |
| 2993 |
{S10{}, "Y", []int{2, 0, 0, 1}, 0}, |
| 2994 |
{S14{}, "X", nil, 0}, |
| 2995 |
} |
| 2996 |
|
| 2997 |
func TestFieldByIndex(t *testing.T) { |
| 2998 |
for _, test := range fieldTests { |
| 2999 |
s := TypeOf(test.s) |
| 3000 |
f := s.FieldByIndex(test.index) |
| 3001 |
if f.Name != "" { |
| 3002 |
if test.index != nil { |
| 3003 |
if f.Name != test.name { |
| 3004 |
t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name) |
| 3005 |
} |
| 3006 |
} else { |
| 3007 |
t.Errorf("%s.%s found", s.Name(), f.Name) |
| 3008 |
} |
| 3009 |
} else if len(test.index) > 0 { |
| 3010 |
t.Errorf("%s.%s not found", s.Name(), test.name) |
| 3011 |
} |
| 3012 |
|
| 3013 |
if test.value != 0 { |
| 3014 |
v := ValueOf(test.s).FieldByIndex(test.index) |
| 3015 |
if v.IsValid() { |
| 3016 |
if x, ok := v.Interface().(int); ok { |
| 3017 |
if x != test.value { |
| 3018 |
t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value) |
| 3019 |
} |
| 3020 |
} else { |
| 3021 |
t.Errorf("%s%v value not an int", s.Name(), test.index) |
| 3022 |
} |
| 3023 |
} else { |
| 3024 |
t.Errorf("%s%v value not found", s.Name(), test.index) |
| 3025 |
} |
| 3026 |
} |
| 3027 |
} |
| 3028 |
} |
| 3029 |
|
| 3030 |
func TestFieldByName(t *testing.T) { |
| 3031 |
for _, test := range fieldTests { |
| 3032 |
s := TypeOf(test.s) |
| 3033 |
f, found := s.FieldByName(test.name) |
| 3034 |
if found { |
| 3035 |
if test.index != nil { |
| 3036 |
// Verify field depth and index. |
| 3037 |
if len(f.Index) != len(test.index) { |
| 3038 |
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) |
| 3039 |
} else { |
| 3040 |
for i, x := range f.Index { |
| 3041 |
if x != test.index[i] { |
| 3042 |
t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i]) |
| 3043 |
} |
| 3044 |
} |
| 3045 |
} |
| 3046 |
} else { |
| 3047 |
t.Errorf("%s.%s found", s.Name(), f.Name) |
| 3048 |
} |
| 3049 |
} else if len(test.index) > 0 { |
| 3050 |
t.Errorf("%s.%s not found", s.Name(), test.name) |
| 3051 |
} |
| 3052 |
|
| 3053 |
if test.value != 0 { |
| 3054 |
v := ValueOf(test.s).FieldByName(test.name) |
| 3055 |
if v.IsValid() { |
| 3056 |
if x, ok := v.Interface().(int); ok { |
| 3057 |
if x != test.value { |
| 3058 |
t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value) |
| 3059 |
} |
| 3060 |
} else { |
| 3061 |
t.Errorf("%s.%s value not an int", s.Name(), test.name) |
| 3062 |
} |
| 3063 |
} else { |
| 3064 |
t.Errorf("%s.%s value not found", s.Name(), test.name) |
| 3065 |
} |
| 3066 |
} |
| 3067 |
} |
| 3068 |
} |
| 3069 |
|
| 3070 |
func TestImportPath(t *testing.T) { |
| 3071 |
tests := []struct { |
| 3072 |
t Type |
| 3073 |
path string |
| 3074 |
}{ |
| 3075 |
{TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"}, |
| 3076 |
{TypeOf(int(0)), ""}, |
| 3077 |
{TypeOf(int8(0)), ""}, |
| 3078 |
{TypeOf(int16(0)), ""}, |
| 3079 |
{TypeOf(int32(0)), ""}, |
| 3080 |
{TypeOf(int64(0)), ""}, |
| 3081 |
{TypeOf(uint(0)), ""}, |
| 3082 |
{TypeOf(uint8(0)), ""}, |
| 3083 |
{TypeOf(uint16(0)), ""}, |
| 3084 |
{TypeOf(uint32(0)), ""}, |
| 3085 |
{TypeOf(uint64(0)), ""}, |
| 3086 |
{TypeOf(uintptr(0)), ""}, |
| 3087 |
{TypeOf(float32(0)), ""}, |
| 3088 |
{TypeOf(float64(0)), ""}, |
| 3089 |
{TypeOf(complex64(0)), ""}, |
| 3090 |
{TypeOf(complex128(0)), ""}, |
| 3091 |
{TypeOf(byte(0)), ""}, |
| 3092 |
{TypeOf(rune(0)), ""}, |
| 3093 |
{TypeOf([]byte(nil)), ""}, |
| 3094 |
{TypeOf([]rune(nil)), ""}, |
| 3095 |
{TypeOf(string("")), ""}, |
| 3096 |
{TypeOf((*any)(nil)).Elem(), ""}, |
| 3097 |
{TypeOf((*byte)(nil)), ""}, |
| 3098 |
{TypeOf((*rune)(nil)), ""}, |
| 3099 |
{TypeOf((*int64)(nil)), ""}, |
| 3100 |
{TypeOf(map[string]int{}), ""}, |
| 3101 |
{TypeOf((*error)(nil)).Elem(), ""}, |
| 3102 |
{TypeOf((*Point)(nil)), ""}, |
| 3103 |
{TypeOf((*Point)(nil)).Elem(), "reflect_test"}, |
| 3104 |
} |
| 3105 |
for _, test := range tests { |
| 3106 |
if path := test.t.PkgPath(); path != test.path { |
| 3107 |
t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path) |
| 3108 |
} |
| 3109 |
} |
| 3110 |
} |
| 3111 |
|
| 3112 |
func TestFieldPkgPath(t *testing.T) { |
| 3113 |
type x int |
| 3114 |
typ := TypeOf(struct { |
| 3115 |
Exported string |
| 3116 |
unexported string |
| 3117 |
OtherPkgFields |
| 3118 |
int // issue 21702 |
| 3119 |
*x // issue 21122 |
| 3120 |
}{}) |
| 3121 |
|
| 3122 |
type pkgpathTest struct { |
| 3123 |
index []int |
| 3124 |
pkgPath string |
| 3125 |
embedded bool |
| 3126 |
exported bool |
| 3127 |
} |
| 3128 |
|
| 3129 |
checkPkgPath := func(name string, s []pkgpathTest) { |
| 3130 |
for _, test := range s { |
| 3131 |
f := typ.FieldByIndex(test.index) |
| 3132 |
if got, want := f.PkgPath, test.pkgPath; got != want { |
| 3133 |
t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want) |
| 3134 |
} |
| 3135 |
if got, want := f.Anonymous, test.embedded; got != want { |
| 3136 |
t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want) |
| 3137 |
} |
| 3138 |
if got, want := f.IsExported(), test.exported; got != want { |
| 3139 |
t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want) |
| 3140 |
} |
| 3141 |
} |
| 3142 |
} |
| 3143 |
|
| 3144 |
checkPkgPath("testStruct", []pkgpathTest{ |
| 3145 |
{[]int{0}, "", false, true}, // Exported |
| 3146 |
{[]int{1}, "reflect_test", false, false}, // unexported |
| 3147 |
{[]int{2}, "", true, true}, // OtherPkgFields |
| 3148 |
{[]int{2, 0}, "", false, true}, // OtherExported |
| 3149 |
{[]int{2, 1}, "reflect", false, false}, // otherUnexported |
| 3150 |
{[]int{3}, "reflect_test", true, false}, // int |
| 3151 |
{[]int{4}, "reflect_test", true, false}, // *x |
| 3152 |
}) |
| 3153 |
|
| 3154 |
type localOtherPkgFields OtherPkgFields |
| 3155 |
typ = TypeOf(localOtherPkgFields{}) |
| 3156 |
checkPkgPath("localOtherPkgFields", []pkgpathTest{ |
| 3157 |
{[]int{0}, "", false, true}, // OtherExported |
| 3158 |
{[]int{1}, "reflect", false, false}, // otherUnexported |
| 3159 |
}) |
| 3160 |
} |
| 3161 |
|
| 3162 |
func TestMethodPkgPath(t *testing.T) { |
| 3163 |
type I interface { |
| 3164 |
x() |
| 3165 |
X() |
| 3166 |
} |
| 3167 |
typ := TypeOf((*interface { |
| 3168 |
I |
| 3169 |
y() |
| 3170 |
Y() |
| 3171 |
})(nil)).Elem() |
| 3172 |
|
| 3173 |
tests := []struct { |
| 3174 |
name string |
| 3175 |
pkgPath string |
| 3176 |
exported bool |
| 3177 |
}{ |
| 3178 |
{"X", "", true}, |
| 3179 |
{"Y", "", true}, |
| 3180 |
{"x", "reflect_test", false}, |
| 3181 |
{"y", "reflect_test", false}, |
| 3182 |
} |
| 3183 |
|
| 3184 |
for _, test := range tests { |
| 3185 |
m, _ := typ.MethodByName(test.name) |
| 3186 |
if got, want := m.PkgPath, test.pkgPath; got != want { |
| 3187 |
t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want) |
| 3188 |
} |
| 3189 |
if got, want := m.IsExported(), test.exported; got != want { |
| 3190 |
t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want) |
| 3191 |
} |
| 3192 |
} |
| 3193 |
} |
| 3194 |
|
| 3195 |
func TestVariadicType(t *testing.T) { |
| 3196 |
// Test example from Type documentation. |
| 3197 |
var f func(x int, y ...float64) |
| 3198 |
typ := TypeOf(f) |
| 3199 |
if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) { |
| 3200 |
sl := typ.In(1) |
| 3201 |
if sl.Kind() == Slice { |
| 3202 |
if sl.Elem() == TypeOf(0.0) { |
| 3203 |
// ok |
| 3204 |
return |
| 3205 |
} |
| 3206 |
} |
| 3207 |
} |
| 3208 |
|
| 3209 |
// Failed |
| 3210 |
t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64") |
| 3211 |
s := fmt.Sprintf("have NumIn() = %d", typ.NumIn()) |
| 3212 |
for i := 0; i < typ.NumIn(); i++ { |
| 3213 |
s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i)) |
| 3214 |
} |
| 3215 |
t.Error(s) |
| 3216 |
} |
| 3217 |
|
| 3218 |
type inner struct { |
| 3219 |
x int |
| 3220 |
} |
| 3221 |
|
| 3222 |
type outer struct { |
| 3223 |
y int |
| 3224 |
inner |
| 3225 |
} |
| 3226 |
|
| 3227 |
func (*inner) M() {} |
| 3228 |
func (*outer) M() {} |
| 3229 |
|
| 3230 |
func TestNestedMethods(t *testing.T) { |
| 3231 |
t.Skip("fails on gccgo due to function wrappers") |
| 3232 |
typ := TypeOf((*outer)(nil)) |
| 3233 |
if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() { |
| 3234 |
t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M) |
| 3235 |
for i := 0; i < typ.NumMethod(); i++ { |
| 3236 |
m := typ.Method(i) |
| 3237 |
t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer()) |
| 3238 |
} |
| 3239 |
} |
| 3240 |
} |
| 3241 |
|
| 3242 |
type unexp struct{} |
| 3243 |
|
| 3244 |
func (*unexp) f() (int32, int8) { return 7, 7 } |
| 3245 |
func (*unexp) g() (int64, int8) { return 8, 8 } |
| 3246 |
|
| 3247 |
type unexpI interface { |
| 3248 |
f() (int32, int8) |
| 3249 |
} |
| 3250 |
|
| 3251 |
var unexpi unexpI = new(unexp) |
| 3252 |
|
| 3253 |
func TestUnexportedMethods(t *testing.T) { |
| 3254 |
typ := TypeOf(unexpi) |
| 3255 |
|
| 3256 |
if got := typ.NumMethod(); got != 0 { |
| 3257 |
t.Errorf("NumMethod=%d, want 0 satisfied methods", got) |
| 3258 |
} |
| 3259 |
} |
| 3260 |
|
| 3261 |
type InnerInt struct { |
| 3262 |
X int |
| 3263 |
} |
| 3264 |
|
| 3265 |
type OuterInt struct { |
| 3266 |
Y int |
| 3267 |
InnerInt |
| 3268 |
} |
| 3269 |
|
| 3270 |
func (i *InnerInt) M() int { |
| 3271 |
return i.X |
| 3272 |
} |
| 3273 |
|
| 3274 |
func TestEmbeddedMethods(t *testing.T) { |
| 3275 |
/* This part of the test fails on gccgo due to function wrappers. |
| 3276 |
typ := TypeOf((*OuterInt)(nil)) |
| 3277 |
if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() { |
| 3278 |
t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M) |
| 3279 |
for i := 0; i < typ.NumMethod(); i++ { |
| 3280 |
m := typ.Method(i) |
| 3281 |
t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer()) |
| 3282 |
} |
| 3283 |
} |
| 3284 |
*/ |
| 3285 |
|
| 3286 |
i := &InnerInt{3} |
| 3287 |
if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 { |
| 3288 |
t.Errorf("i.M() = %d, want 3", v) |
| 3289 |
} |
| 3290 |
|
| 3291 |
o := &OuterInt{1, InnerInt{2}} |
| 3292 |
if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 { |
| 3293 |
t.Errorf("i.M() = %d, want 2", v) |
| 3294 |
} |
| 3295 |
|
| 3296 |
f := (*OuterInt).M |
| 3297 |
if v := f(o); v != 2 { |
| 3298 |
t.Errorf("f(o) = %d, want 2", v) |
| 3299 |
} |
| 3300 |
} |
| 3301 |
|
| 3302 |
type FuncDDD func(...any) error |
| 3303 |
|
| 3304 |
func (f FuncDDD) M() {} |
| 3305 |
|
| 3306 |
func TestNumMethodOnDDD(t *testing.T) { |
| 3307 |
rv := ValueOf((FuncDDD)(nil)) |
| 3308 |
if n := rv.NumMethod(); n != 1 { |
| 3309 |
t.Fatalf("NumMethod()=%d, want 1", n) |
| 3310 |
} |
| 3311 |
} |
| 3312 |
|
| 3313 |
func TestPtrTo(t *testing.T) { |
| 3314 |
// This block of code means that the ptrToThis field of the |
| 3315 |
// reflect data for *unsafe.Pointer is non zero, see |
| 3316 |
// https://golang.org/issue/19003 |
| 3317 |
var x unsafe.Pointer |
| 3318 |
var y = &x |
| 3319 |
var z = &y |
| 3320 |
|
| 3321 |
var i int |
| 3322 |
|
| 3323 |
typ := TypeOf(z) |
| 3324 |
for i = 0; i < 100; i++ { |
| 3325 |
typ = PointerTo(typ) |
| 3326 |
} |
| 3327 |
for i = 0; i < 100; i++ { |
| 3328 |
typ = typ.Elem() |
| 3329 |
} |
| 3330 |
if typ != TypeOf(z) { |
| 3331 |
t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z)) |
| 3332 |
} |
| 3333 |
} |
| 3334 |
|
| 3335 |
func TestPtrToGC(t *testing.T) { |
| 3336 |
type T *uintptr |
| 3337 |
tt := TypeOf(T(nil)) |
| 3338 |
pt := PointerTo(tt) |
| 3339 |
const n = 100 |
| 3340 |
var x []any |
| 3341 |
for i := 0; i < n; i++ { |
| 3342 |
v := New(pt) |
| 3343 |
p := new(*uintptr) |
| 3344 |
*p = new(uintptr) |
| 3345 |
**p = uintptr(i) |
| 3346 |
v.Elem().Set(ValueOf(p).Convert(pt)) |
| 3347 |
x = append(x, v.Interface()) |
| 3348 |
} |
| 3349 |
runtime.GC() |
| 3350 |
|
| 3351 |
for i, xi := range x { |
| 3352 |
k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr) |
| 3353 |
if k != uintptr(i) { |
| 3354 |
t.Errorf("lost x[%d] = %d, want %d", i, k, i) |
| 3355 |
} |
| 3356 |
} |
| 3357 |
} |
| 3358 |
|
| 3359 |
func BenchmarkPtrTo(b *testing.B) { |
| 3360 |
// Construct a type with a zero ptrToThis. |
| 3361 |
type T struct{ int } |
| 3362 |
t := SliceOf(TypeOf(T{})) |
| 3363 |
ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis") |
| 3364 |
if !ptrToThis.IsValid() { |
| 3365 |
b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t) |
| 3366 |
} |
| 3367 |
if ptrToThis.Int() != 0 { |
| 3368 |
b.Fatalf("%v.ptrToThis unexpectedly nonzero", t) |
| 3369 |
} |
| 3370 |
b.ResetTimer() |
| 3371 |
|
| 3372 |
// Now benchmark calling PointerTo on it: we'll have to hit the ptrMap cache on |
| 3373 |
// every call. |
| 3374 |
b.RunParallel(func(pb *testing.PB) { |
| 3375 |
for pb.Next() { |
| 3376 |
PointerTo(t) |
| 3377 |
} |
| 3378 |
}) |
| 3379 |
} |
| 3380 |
|
| 3381 |
func TestAddr(t *testing.T) { |
| 3382 |
var p struct { |
| 3383 |
X, Y int |
| 3384 |
} |
| 3385 |
|
| 3386 |
v := ValueOf(&p) |
| 3387 |
v = v.Elem() |
| 3388 |
v = v.Addr() |
| 3389 |
v = v.Elem() |
| 3390 |
v = v.Field(0) |
| 3391 |
v.SetInt(2) |
| 3392 |
if p.X != 2 { |
| 3393 |
t.Errorf("Addr.Elem.Set failed to set value") |
| 3394 |
} |
| 3395 |
|
| 3396 |
// Again but take address of the ValueOf value. |
| 3397 |
// Exercises generation of PtrTypes not present in the binary. |
| 3398 |
q := &p |
| 3399 |
v = ValueOf(&q).Elem() |
| 3400 |
v = v.Addr() |
| 3401 |
v = v.Elem() |
| 3402 |
v = v.Elem() |
| 3403 |
v = v.Addr() |
| 3404 |
v = v.Elem() |
| 3405 |
v = v.Field(0) |
| 3406 |
v.SetInt(3) |
| 3407 |
if p.X != 3 { |
| 3408 |
t.Errorf("Addr.Elem.Set failed to set value") |
| 3409 |
} |
| 3410 |
|
| 3411 |
// Starting without pointer we should get changed value |
| 3412 |
// in interface. |
| 3413 |
qq := p |
| 3414 |
v = ValueOf(&qq).Elem() |
| 3415 |
v0 := v |
| 3416 |
v = v.Addr() |
| 3417 |
v = v.Elem() |
| 3418 |
v = v.Field(0) |
| 3419 |
v.SetInt(4) |
| 3420 |
if p.X != 3 { // should be unchanged from last time |
| 3421 |
t.Errorf("somehow value Set changed original p") |
| 3422 |
} |
| 3423 |
p = v0.Interface().(struct { |
| 3424 |
X, Y int |
| 3425 |
}) |
| 3426 |
if p.X != 4 { |
| 3427 |
t.Errorf("Addr.Elem.Set valued to set value in top value") |
| 3428 |
} |
| 3429 |
|
| 3430 |
// Verify that taking the address of a type gives us a pointer |
| 3431 |
// which we can convert back using the usual interface |
| 3432 |
// notation. |
| 3433 |
var s struct { |
| 3434 |
B *bool |
| 3435 |
} |
| 3436 |
ps := ValueOf(&s).Elem().Field(0).Addr().Interface() |
| 3437 |
*(ps.(**bool)) = new(bool) |
| 3438 |
if s.B == nil { |
| 3439 |
t.Errorf("Addr.Interface direct assignment failed") |
| 3440 |
} |
| 3441 |
} |
| 3442 |
|
| 3443 |
/* gccgo does do allocations here. |
| 3444 |
|
| 3445 |
func noAlloc(t *testing.T, n int, f func(int)) { |
| 3446 |
if testing.Short() { |
| 3447 |
t.Skip("skipping malloc count in short mode") |
| 3448 |
} |
| 3449 |
if runtime.GOMAXPROCS(0) > 1 { |
| 3450 |
t.Skip("skipping; GOMAXPROCS>1") |
| 3451 |
} |
| 3452 |
i := -1 |
| 3453 |
allocs := testing.AllocsPerRun(n, func() { |
| 3454 |
f(i) |
| 3455 |
i++ |
| 3456 |
}) |
| 3457 |
if allocs > 0 { |
| 3458 |
t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs) |
| 3459 |
} |
| 3460 |
} |
| 3461 |
|
| 3462 |
func TestAllocations(t *testing.T) { |
| 3463 |
noAlloc(t, 100, func(j int) { |
| 3464 |
var i any |
| 3465 |
var v Value |
| 3466 |
|
| 3467 |
// We can uncomment this when compiler escape analysis |
| 3468 |
// is good enough to see that the integer assigned to i |
| 3469 |
// does not escape and therefore need not be allocated. |
| 3470 |
// |
| 3471 |
// i = 42 + j |
| 3472 |
// v = ValueOf(i) |
| 3473 |
// if int(v.Int()) != 42+j { |
| 3474 |
// panic("wrong int") |
| 3475 |
// } |
| 3476 |
|
| 3477 |
i = func(j int) int { return j } |
| 3478 |
v = ValueOf(i) |
| 3479 |
if v.Interface().(func(int) int)(j) != j { |
| 3480 |
panic("wrong result") |
| 3481 |
} |
| 3482 |
}) |
| 3483 |
} |
| 3484 |
|
| 3485 |
*/ |
| 3486 |
|
| 3487 |
func TestSmallNegativeInt(t *testing.T) { |
| 3488 |
i := int16(-1) |
| 3489 |
v := ValueOf(i) |
| 3490 |
if v.Int() != -1 { |
| 3491 |
t.Errorf("int16(-1).Int() returned %v", v.Int()) |
| 3492 |
} |
| 3493 |
} |
| 3494 |
|
| 3495 |
func TestIndex(t *testing.T) { |
| 3496 |
xs := []byte{1, 2, 3, 4, 5, 6, 7, 8} |
| 3497 |
v := ValueOf(xs).Index(3).Interface().(byte) |
| 3498 |
if v != xs[3] { |
| 3499 |
t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3]) |
| 3500 |
} |
| 3501 |
xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80} |
| 3502 |
v = ValueOf(xa).Index(2).Interface().(byte) |
| 3503 |
if v != xa[2] { |
| 3504 |
t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2]) |
| 3505 |
} |
| 3506 |
s := "0123456789" |
| 3507 |
v = ValueOf(s).Index(3).Interface().(byte) |
| 3508 |
if v != s[3] { |
| 3509 |
t.Errorf("s.Index(3) = %v; expected %v", v, s[3]) |
| 3510 |
} |
| 3511 |
} |
| 3512 |
|
| 3513 |
func TestSlice(t *testing.T) { |
| 3514 |
xs := []int{1, 2, 3, 4, 5, 6, 7, 8} |
| 3515 |
v := ValueOf(xs).Slice(3, 5).Interface().([]int) |
| 3516 |
if len(v) != 2 { |
| 3517 |
t.Errorf("len(xs.Slice(3, 5)) = %d", len(v)) |
| 3518 |
} |
| 3519 |
if cap(v) != 5 { |
| 3520 |
t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v)) |
| 3521 |
} |
| 3522 |
if !DeepEqual(v[0:5], xs[3:]) { |
| 3523 |
t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5]) |
| 3524 |
} |
| 3525 |
xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} |
| 3526 |
v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int) |
| 3527 |
if len(v) != 3 { |
| 3528 |
t.Errorf("len(xa.Slice(2, 5)) = %d", len(v)) |
| 3529 |
} |
| 3530 |
if cap(v) != 6 { |
| 3531 |
t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v)) |
| 3532 |
} |
| 3533 |
if !DeepEqual(v[0:6], xa[2:]) { |
| 3534 |
t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6]) |
| 3535 |
} |
| 3536 |
s := "0123456789" |
| 3537 |
vs := ValueOf(s).Slice(3, 5).Interface().(string) |
| 3538 |
if vs != s[3:5] { |
| 3539 |
t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5]) |
| 3540 |
} |
| 3541 |
|
| 3542 |
rv := ValueOf(&xs).Elem() |
| 3543 |
rv = rv.Slice(3, 4) |
| 3544 |
ptr2 := rv.UnsafePointer() |
| 3545 |
rv = rv.Slice(5, 5) |
| 3546 |
ptr3 := rv.UnsafePointer() |
| 3547 |
if ptr3 != ptr2 { |
| 3548 |
t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2) |
| 3549 |
} |
| 3550 |
} |
| 3551 |
|
| 3552 |
func TestSlice3(t *testing.T) { |
| 3553 |
xs := []int{1, 2, 3, 4, 5, 6, 7, 8} |
| 3554 |
v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int) |
| 3555 |
if len(v) != 2 { |
| 3556 |
t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v)) |
| 3557 |
} |
| 3558 |
if cap(v) != 4 { |
| 3559 |
t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v)) |
| 3560 |
} |
| 3561 |
if !DeepEqual(v[0:4], xs[3:7:7]) { |
| 3562 |
t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4]) |
| 3563 |
} |
| 3564 |
rv := ValueOf(&xs).Elem() |
| 3565 |
shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) }) |
| 3566 |
shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) }) |
| 3567 |
shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) }) |
| 3568 |
|
| 3569 |
xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} |
| 3570 |
v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int) |
| 3571 |
if len(v) != 3 { |
| 3572 |
t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v)) |
| 3573 |
} |
| 3574 |
if cap(v) != 4 { |
| 3575 |
t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v)) |
| 3576 |
} |
| 3577 |
if !DeepEqual(v[0:4], xa[2:6:6]) { |
| 3578 |
t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4]) |
| 3579 |
} |
| 3580 |
rv = ValueOf(&xa).Elem() |
| 3581 |
shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) }) |
| 3582 |
shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) }) |
| 3583 |
shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) }) |
| 3584 |
|
| 3585 |
s := "hello world" |
| 3586 |
rv = ValueOf(&s).Elem() |
| 3587 |
shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) }) |
| 3588 |
|
| 3589 |
rv = ValueOf(&xs).Elem() |
| 3590 |
rv = rv.Slice3(3, 5, 7) |
| 3591 |
ptr2 := rv.UnsafePointer() |
| 3592 |
rv = rv.Slice3(4, 4, 4) |
| 3593 |
ptr3 := rv.UnsafePointer() |
| 3594 |
if ptr3 != ptr2 { |
| 3595 |
t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2) |
| 3596 |
} |
| 3597 |
} |
| 3598 |
|
| 3599 |
func TestSetLenCap(t *testing.T) { |
| 3600 |
xs := []int{1, 2, 3, 4, 5, 6, 7, 8} |
| 3601 |
xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} |
| 3602 |
|
| 3603 |
vs := ValueOf(&xs).Elem() |
| 3604 |
shouldPanic("SetLen", func() { vs.SetLen(10) }) |
| 3605 |
shouldPanic("SetCap", func() { vs.SetCap(10) }) |
| 3606 |
shouldPanic("SetLen", func() { vs.SetLen(-1) }) |
| 3607 |
shouldPanic("SetCap", func() { vs.SetCap(-1) }) |
| 3608 |
shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len |
| 3609 |
vs.SetLen(5) |
| 3610 |
if len(xs) != 5 || cap(xs) != 8 { |
| 3611 |
t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs)) |
| 3612 |
} |
| 3613 |
vs.SetCap(6) |
| 3614 |
if len(xs) != 5 || cap(xs) != 6 { |
| 3615 |
t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs)) |
| 3616 |
} |
| 3617 |
vs.SetCap(5) |
| 3618 |
if len(xs) != 5 || cap(xs) != 5 { |
| 3619 |
t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs)) |
| 3620 |
} |
| 3621 |
shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len |
| 3622 |
shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap |
| 3623 |
|
| 3624 |
va := ValueOf(&xa).Elem() |
| 3625 |
shouldPanic("SetLen", func() { va.SetLen(8) }) |
| 3626 |
shouldPanic("SetCap", func() { va.SetCap(8) }) |
| 3627 |
} |
| 3628 |
|
| 3629 |
func TestVariadic(t *testing.T) { |
| 3630 |
var b bytes.Buffer |
| 3631 |
V := ValueOf |
| 3632 |
|
| 3633 |
b.Reset() |
| 3634 |
V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)}) |
| 3635 |
if b.String() != "hello, 42 world" { |
| 3636 |
t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world") |
| 3637 |
} |
| 3638 |
|
| 3639 |
b.Reset() |
| 3640 |
V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})}) |
| 3641 |
if b.String() != "hello, 42 world" { |
| 3642 |
t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world") |
| 3643 |
} |
| 3644 |
} |
| 3645 |
|
| 3646 |
func TestFuncArg(t *testing.T) { |
| 3647 |
f1 := func(i int, f func(int) int) int { return f(i) } |
| 3648 |
f2 := func(i int) int { return i + 1 } |
| 3649 |
r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)}) |
| 3650 |
if r[0].Int() != 101 { |
| 3651 |
t.Errorf("function returned %d, want 101", r[0].Int()) |
| 3652 |
} |
| 3653 |
} |
| 3654 |
|
| 3655 |
func TestStructArg(t *testing.T) { |
| 3656 |
type padded struct { |
| 3657 |
B string |
| 3658 |
C int32 |
| 3659 |
} |
| 3660 |
var ( |
| 3661 |
gotA padded |
| 3662 |
gotB uint32 |
| 3663 |
wantA = padded{"3", 4} |
| 3664 |
wantB = uint32(5) |
| 3665 |
) |
| 3666 |
f := func(a padded, b uint32) { |
| 3667 |
gotA, gotB = a, b |
| 3668 |
} |
| 3669 |
ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)}) |
| 3670 |
if gotA != wantA || gotB != wantB { |
| 3671 |
t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB) |
| 3672 |
} |
| 3673 |
} |
| 3674 |
|
| 3675 |
var tagGetTests = []struct { |
| 3676 |
Tag StructTag |
| 3677 |
Key string |
| 3678 |
Value string |
| 3679 |
}{ |
| 3680 |
{`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`}, |
| 3681 |
{`protobuf:"PB(1,2)"`, `foo`, ``}, |
| 3682 |
{`protobuf:"PB(1,2)"`, `rotobuf`, ``}, |
| 3683 |
{`protobuf:"PB(1,2)" json:"name"`, `json`, `name`}, |
| 3684 |
{`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`}, |
| 3685 |
{`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"}, |
| 3686 |
{`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"}, |
| 3687 |
} |
| 3688 |
|
| 3689 |
func TestTagGet(t *testing.T) { |
| 3690 |
for _, tt := range tagGetTests { |
| 3691 |
if v := tt.Tag.Get(tt.Key); v != tt.Value { |
| 3692 |
t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value) |
| 3693 |
} |
| 3694 |
} |
| 3695 |
} |
| 3696 |
|
| 3697 |
func TestBytes(t *testing.T) { |
| 3698 |
type B []byte |
| 3699 |
x := B{1, 2, 3, 4} |
| 3700 |
y := ValueOf(x).Bytes() |
| 3701 |
if !bytes.Equal(x, y) { |
| 3702 |
t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) |
| 3703 |
} |
| 3704 |
if &x[0] != &y[0] { |
| 3705 |
t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) |
| 3706 |
} |
| 3707 |
} |
| 3708 |
|
| 3709 |
func TestSetBytes(t *testing.T) { |
| 3710 |
type B []byte |
| 3711 |
var x B |
| 3712 |
y := []byte{1, 2, 3, 4} |
| 3713 |
ValueOf(&x).Elem().SetBytes(y) |
| 3714 |
if !bytes.Equal(x, y) { |
| 3715 |
t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) |
| 3716 |
} |
| 3717 |
if &x[0] != &y[0] { |
| 3718 |
t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) |
| 3719 |
} |
| 3720 |
} |
| 3721 |
|
| 3722 |
type Private struct { |
| 3723 |
x int |
| 3724 |
y **int |
| 3725 |
Z int |
| 3726 |
} |
| 3727 |
|
| 3728 |
func (p *Private) m() { |
| 3729 |
} |
| 3730 |
|
| 3731 |
type private struct { |
| 3732 |
Z int |
| 3733 |
z int |
| 3734 |
S string |
| 3735 |
A [1]Private |
| 3736 |
T []Private |
| 3737 |
} |
| 3738 |
|
| 3739 |
func (p *private) P() { |
| 3740 |
} |
| 3741 |
|
| 3742 |
type Public struct { |
| 3743 |
X int |
| 3744 |
Y **int |
| 3745 |
private |
| 3746 |
} |
| 3747 |
|
| 3748 |
func (p *Public) M() { |
| 3749 |
} |
| 3750 |
|
| 3751 |
func TestUnexported(t *testing.T) { |
| 3752 |
var pub Public |
| 3753 |
pub.S = "S" |
| 3754 |
pub.T = pub.A[:] |
| 3755 |
v := ValueOf(&pub) |
| 3756 |
isValid(v.Elem().Field(0)) |
| 3757 |
isValid(v.Elem().Field(1)) |
| 3758 |
isValid(v.Elem().Field(2)) |
| 3759 |
isValid(v.Elem().FieldByName("X")) |
| 3760 |
isValid(v.Elem().FieldByName("Y")) |
| 3761 |
isValid(v.Elem().FieldByName("Z")) |
| 3762 |
isValid(v.Type().Method(0).Func) |
| 3763 |
m, _ := v.Type().MethodByName("M") |
| 3764 |
isValid(m.Func) |
| 3765 |
m, _ = v.Type().MethodByName("P") |
| 3766 |
isValid(m.Func) |
| 3767 |
isNonNil(v.Elem().Field(0).Interface()) |
| 3768 |
isNonNil(v.Elem().Field(1).Interface()) |
| 3769 |
isNonNil(v.Elem().Field(2).Field(2).Index(0)) |
| 3770 |
isNonNil(v.Elem().FieldByName("X").Interface()) |
| 3771 |
isNonNil(v.Elem().FieldByName("Y").Interface()) |
| 3772 |
isNonNil(v.Elem().FieldByName("Z").Interface()) |
| 3773 |
isNonNil(v.Elem().FieldByName("S").Index(0).Interface()) |
| 3774 |
isNonNil(v.Type().Method(0).Func.Interface()) |
| 3775 |
m, _ = v.Type().MethodByName("P") |
| 3776 |
isNonNil(m.Func.Interface()) |
| 3777 |
|
| 3778 |
var priv Private |
| 3779 |
v = ValueOf(&priv) |
| 3780 |
isValid(v.Elem().Field(0)) |
| 3781 |
isValid(v.Elem().Field(1)) |
| 3782 |
isValid(v.Elem().FieldByName("x")) |
| 3783 |
isValid(v.Elem().FieldByName("y")) |
| 3784 |
shouldPanic("Interface", func() { v.Elem().Field(0).Interface() }) |
| 3785 |
shouldPanic("Interface", func() { v.Elem().Field(1).Interface() }) |
| 3786 |
shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() }) |
| 3787 |
shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() }) |
| 3788 |
shouldPanic("Method", func() { v.Type().Method(0) }) |
| 3789 |
} |
| 3790 |
|
| 3791 |
func TestSetPanic(t *testing.T) { |
| 3792 |
ok := func(f func()) { f() } |
| 3793 |
bad := func(f func()) { shouldPanic("Set", f) } |
| 3794 |
clear := func(v Value) { v.Set(Zero(v.Type())) } |
| 3795 |
|
| 3796 |
type t0 struct { |
| 3797 |
W int |
| 3798 |
} |
| 3799 |
|
| 3800 |
type t1 struct { |
| 3801 |
Y int |
| 3802 |
t0 |
| 3803 |
} |
| 3804 |
|
| 3805 |
type T2 struct { |
| 3806 |
Z int |
| 3807 |
namedT0 t0 |
| 3808 |
} |
| 3809 |
|
| 3810 |
type T struct { |
| 3811 |
X int |
| 3812 |
t1 |
| 3813 |
T2 |
| 3814 |
NamedT1 t1 |
| 3815 |
NamedT2 T2 |
| 3816 |
namedT1 t1 |
| 3817 |
namedT2 T2 |
| 3818 |
} |
| 3819 |
|
| 3820 |
// not addressable |
| 3821 |
v := ValueOf(T{}) |
| 3822 |
bad(func() { clear(v.Field(0)) }) // .X |
| 3823 |
bad(func() { clear(v.Field(1)) }) // .t1 |
| 3824 |
bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y |
| 3825 |
bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 |
| 3826 |
bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W |
| 3827 |
bad(func() { clear(v.Field(2)) }) // .T2 |
| 3828 |
bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z |
| 3829 |
bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 |
| 3830 |
bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W |
| 3831 |
bad(func() { clear(v.Field(3)) }) // .NamedT1 |
| 3832 |
bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y |
| 3833 |
bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 |
| 3834 |
bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W |
| 3835 |
bad(func() { clear(v.Field(4)) }) // .NamedT2 |
| 3836 |
bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z |
| 3837 |
bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 |
| 3838 |
bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W |
| 3839 |
bad(func() { clear(v.Field(5)) }) // .namedT1 |
| 3840 |
bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y |
| 3841 |
bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 |
| 3842 |
bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W |
| 3843 |
bad(func() { clear(v.Field(6)) }) // .namedT2 |
| 3844 |
bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z |
| 3845 |
bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 |
| 3846 |
bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W |
| 3847 |
|
| 3848 |
// addressable |
| 3849 |
v = ValueOf(&T{}).Elem() |
| 3850 |
ok(func() { clear(v.Field(0)) }) // .X |
| 3851 |
bad(func() { clear(v.Field(1)) }) // .t1 |
| 3852 |
ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y |
| 3853 |
bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 |
| 3854 |
ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W |
| 3855 |
ok(func() { clear(v.Field(2)) }) // .T2 |
| 3856 |
ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z |
| 3857 |
bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 |
| 3858 |
bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W |
| 3859 |
ok(func() { clear(v.Field(3)) }) // .NamedT1 |
| 3860 |
ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y |
| 3861 |
bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 |
| 3862 |
ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W |
| 3863 |
ok(func() { clear(v.Field(4)) }) // .NamedT2 |
| 3864 |
ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z |
| 3865 |
bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 |
| 3866 |
bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W |
| 3867 |
bad(func() { clear(v.Field(5)) }) // .namedT1 |
| 3868 |
bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y |
| 3869 |
bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 |
| 3870 |
bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W |
| 3871 |
bad(func() { clear(v.Field(6)) }) // .namedT2 |
| 3872 |
bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z |
| 3873 |
bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 |
| 3874 |
bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W |
| 3875 |
} |
| 3876 |
|
| 3877 |
type timp int |
| 3878 |
|
| 3879 |
func (t timp) W() {} |
| 3880 |
func (t timp) Y() {} |
| 3881 |
func (t timp) w() {} |
| 3882 |
func (t timp) y() {} |
| 3883 |
|
| 3884 |
func TestCallPanic(t *testing.T) { |
| 3885 |
type t0 interface { |
| 3886 |
W() |
| 3887 |
w() |
| 3888 |
} |
| 3889 |
type T1 interface { |
| 3890 |
Y() |
| 3891 |
y() |
| 3892 |
} |
| 3893 |
type T2 struct { |
| 3894 |
T1 |
| 3895 |
t0 |
| 3896 |
} |
| 3897 |
type T struct { |
| 3898 |
t0 // 0 |
| 3899 |
T1 // 1 |
| 3900 |
|
| 3901 |
NamedT0 t0 // 2 |
| 3902 |
NamedT1 T1 // 3 |
| 3903 |
NamedT2 T2 // 4 |
| 3904 |
|
| 3905 |
namedT0 t0 // 5 |
| 3906 |
namedT1 T1 // 6 |
| 3907 |
namedT2 T2 // 7 |
| 3908 |
} |
| 3909 |
ok := func(f func()) { f() } |
| 3910 |
badCall := func(f func()) { shouldPanic("Call", f) } |
| 3911 |
badMethod := func(f func()) { shouldPanic("Method", f) } |
| 3912 |
call := func(v Value) { v.Call(nil) } |
| 3913 |
|
| 3914 |
i := timp(0) |
| 3915 |
v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}}) |
| 3916 |
badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W |
| 3917 |
badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W |
| 3918 |
badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w |
| 3919 |
badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w |
| 3920 |
ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y |
| 3921 |
ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y |
| 3922 |
badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y |
| 3923 |
badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y |
| 3924 |
|
| 3925 |
ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W |
| 3926 |
ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W |
| 3927 |
badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w |
| 3928 |
badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w |
| 3929 |
|
| 3930 |
ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y |
| 3931 |
ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y |
| 3932 |
badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y |
| 3933 |
badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y |
| 3934 |
|
| 3935 |
ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y |
| 3936 |
ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W |
| 3937 |
badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W |
| 3938 |
badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W |
| 3939 |
|
| 3940 |
badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W |
| 3941 |
badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W |
| 3942 |
badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w |
| 3943 |
badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w |
| 3944 |
|
| 3945 |
badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y |
| 3946 |
badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y |
| 3947 |
badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y |
| 3948 |
badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y |
| 3949 |
|
| 3950 |
badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y |
| 3951 |
badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W |
| 3952 |
badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W |
| 3953 |
badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W |
| 3954 |
} |
| 3955 |
|
| 3956 |
func shouldPanic(expect string, f func()) { |
| 3957 |
defer func() { |
| 3958 |
r := recover() |
| 3959 |
if r == nil { |
| 3960 |
panic("did not panic") |
| 3961 |
} |
| 3962 |
if expect != "" { |
| 3963 |
var s string |
| 3964 |
switch r := r.(type) { |
| 3965 |
case string: |
| 3966 |
s = r |
| 3967 |
case *ValueError: |
| 3968 |
s = r.Error() |
| 3969 |
default: |
| 3970 |
panic(fmt.Sprintf("panicked with unexpected type %T", r)) |
| 3971 |
} |
| 3972 |
if !strings.HasPrefix(s, "reflect") { |
| 3973 |
panic(`panic string does not start with "reflect": ` + s) |
| 3974 |
} |
| 3975 |
if !strings.Contains(s, expect) { |
| 3976 |
panic(`panic string does not contain "` + expect + `": ` + s) |
| 3977 |
} |
| 3978 |
} |
| 3979 |
}() |
| 3980 |
f() |
| 3981 |
} |
| 3982 |
|
| 3983 |
func isNonNil(x any) { |
| 3984 |
if x == nil { |
| 3985 |
panic("nil interface") |
| 3986 |
} |
| 3987 |
} |
| 3988 |
|
| 3989 |
func isValid(v Value) { |
| 3990 |
if !v.IsValid() { |
| 3991 |
panic("zero Value") |
| 3992 |
} |
| 3993 |
} |
| 3994 |
|
| 3995 |
func TestAlias(t *testing.T) { |
| 3996 |
x := string("hello") |
| 3997 |
v := ValueOf(&x).Elem() |
| 3998 |
oldvalue := v.Interface() |
| 3999 |
v.SetString("world") |
| 4000 |
newvalue := v.Interface() |
| 4001 |
|
| 4002 |
if oldvalue != "hello" || newvalue != "world" { |
| 4003 |
t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue) |
| 4004 |
} |
| 4005 |
} |
| 4006 |
|
| 4007 |
var V = ValueOf |
| 4008 |
|
| 4009 |
func EmptyInterfaceV(x any) Value { |
| 4010 |
return ValueOf(&x).Elem() |
| 4011 |
} |
| 4012 |
|
| 4013 |
func ReaderV(x io.Reader) Value { |
| 4014 |
return ValueOf(&x).Elem() |
| 4015 |
} |
| 4016 |
|
| 4017 |
func ReadWriterV(x io.ReadWriter) Value { |
| 4018 |
return ValueOf(&x).Elem() |
| 4019 |
} |
| 4020 |
|
| 4021 |
type Empty struct{} |
| 4022 |
type MyStruct struct { |
| 4023 |
x int `some:"tag"` |
| 4024 |
} |
| 4025 |
type MyStruct1 struct { |
| 4026 |
x struct { |
| 4027 |
int `some:"bar"` |
| 4028 |
} |
| 4029 |
} |
| 4030 |
type MyStruct2 struct { |
| 4031 |
x struct { |
| 4032 |
int `some:"foo"` |
| 4033 |
} |
| 4034 |
} |
| 4035 |
type MyString string |
| 4036 |
type MyBytes []byte |
| 4037 |
type MyBytesArrayPtr0 *[0]byte |
| 4038 |
type MyBytesArrayPtr *[4]byte |
| 4039 |
type MyBytesArray0 [0]byte |
| 4040 |
type MyBytesArray [4]byte |
| 4041 |
type MyRunes []int32 |
| 4042 |
type MyFunc func() |
| 4043 |
type MyByte byte |
| 4044 |
|
| 4045 |
type IntChan chan int |
| 4046 |
type IntChanRecv <-chan int |
| 4047 |
type IntChanSend chan<- int |
| 4048 |
type BytesChan chan []byte |
| 4049 |
type BytesChanRecv <-chan []byte |
| 4050 |
type BytesChanSend chan<- []byte |
| 4051 |
|
| 4052 |
var convertTests = []struct { |
| 4053 |
in Value |
| 4054 |
out Value |
| 4055 |
}{ |
| 4056 |
// numbers |
| 4057 |
/* |
| 4058 |
Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go |
| 4059 |
|
| 4060 |
package main |
| 4061 |
|
| 4062 |
import "fmt" |
| 4063 |
|
| 4064 |
var numbers = []string{ |
| 4065 |
"int8", "uint8", "int16", "uint16", |
| 4066 |
"int32", "uint32", "int64", "uint64", |
| 4067 |
"int", "uint", "uintptr", |
| 4068 |
"float32", "float64", |
| 4069 |
} |
| 4070 |
|
| 4071 |
func main() { |
| 4072 |
// all pairs but in an unusual order, |
| 4073 |
// to emit all the int8, uint8 cases |
| 4074 |
// before n grows too big. |
| 4075 |
n := 1 |
| 4076 |
for i, f := range numbers { |
| 4077 |
for _, g := range numbers[i:] { |
| 4078 |
fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n) |
| 4079 |
n++ |
| 4080 |
if f != g { |
| 4081 |
fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n) |
| 4082 |
n++ |
| 4083 |
} |
| 4084 |
} |
| 4085 |
} |
| 4086 |
} |
| 4087 |
*/ |
| 4088 |
{V(int8(1)), V(int8(1))}, |
| 4089 |
{V(int8(2)), V(uint8(2))}, |
| 4090 |
{V(uint8(3)), V(int8(3))}, |
| 4091 |
{V(int8(4)), V(int16(4))}, |
| 4092 |
{V(int16(5)), V(int8(5))}, |
| 4093 |
{V(int8(6)), V(uint16(6))}, |
| 4094 |
{V(uint16(7)), V(int8(7))}, |
| 4095 |
{V(int8(8)), V(int32(8))}, |
| 4096 |
{V(int32(9)), V(int8(9))}, |
| 4097 |
{V(int8(10)), V(uint32(10))}, |
| 4098 |
{V(uint32(11)), V(int8(11))}, |
| 4099 |
{V(int8(12)), V(int64(12))}, |
| 4100 |
{V(int64(13)), V(int8(13))}, |
| 4101 |
{V(int8(14)), V(uint64(14))}, |
| 4102 |
{V(uint64(15)), V(int8(15))}, |
| 4103 |
{V(int8(16)), V(int(16))}, |
| 4104 |
{V(int(17)), V(int8(17))}, |
| 4105 |
{V(int8(18)), V(uint(18))}, |
| 4106 |
{V(uint(19)), V(int8(19))}, |
| 4107 |
{V(int8(20)), V(uintptr(20))}, |
| 4108 |
{V(uintptr(21)), V(int8(21))}, |
| 4109 |
{V(int8(22)), V(float32(22))}, |
| 4110 |
{V(float32(23)), V(int8(23))}, |
| 4111 |
{V(int8(24)), V(float64(24))}, |
| 4112 |
{V(float64(25)), V(int8(25))}, |
| 4113 |
{V(uint8(26)), V(uint8(26))}, |
| 4114 |
{V(uint8(27)), V(int16(27))}, |
| 4115 |
{V(int16(28)), V(uint8(28))}, |
| 4116 |
{V(uint8(29)), V(uint16(29))}, |
| 4117 |
{V(uint16(30)), V(uint8(30))}, |
| 4118 |
{V(uint8(31)), V(int32(31))}, |
| 4119 |
{V(int32(32)), V(uint8(32))}, |
| 4120 |
{V(uint8(33)), V(uint32(33))}, |
| 4121 |
{V(uint32(34)), V(uint8(34))}, |
| 4122 |
{V(uint8(35)), V(int64(35))}, |
| 4123 |
{V(int64(36)), V(uint8(36))}, |
| 4124 |
{V(uint8(37)), V(uint64(37))}, |
| 4125 |
{V(uint64(38)), V(uint8(38))}, |
| 4126 |
{V(uint8(39)), V(int(39))}, |
| 4127 |
{V(int(40)), V(uint8(40))}, |
| 4128 |
{V(uint8(41)), V(uint(41))}, |
| 4129 |
{V(uint(42)), V(uint8(42))}, |
| 4130 |
{V(uint8(43)), V(uintptr(43))}, |
| 4131 |
{V(uintptr(44)), V(uint8(44))}, |
| 4132 |
{V(uint8(45)), V(float32(45))}, |
| 4133 |
{V(float32(46)), V(uint8(46))}, |
| 4134 |
{V(uint8(47)), V(float64(47))}, |
| 4135 |
{V(float64(48)), V(uint8(48))}, |
| 4136 |
{V(int16(49)), V(int16(49))}, |
| 4137 |
{V(int16(50)), V(uint16(50))}, |
| 4138 |
{V(uint16(51)), V(int16(51))}, |
| 4139 |
{V(int16(52)), V(int32(52))}, |
| 4140 |
{V(int32(53)), V(int16(53))}, |
| 4141 |
{V(int16(54)), V(uint32(54))}, |
| 4142 |
{V(uint32(55)), V(int16(55))}, |
| 4143 |
{V(int16(56)), V(int64(56))}, |
| 4144 |
{V(int64(57)), V(int16(57))}, |
| 4145 |
{V(int16(58)), V(uint64(58))}, |
| 4146 |
{V(uint64(59)), V(int16(59))}, |
| 4147 |
{V(int16(60)), V(int(60))}, |
| 4148 |
{V(int(61)), V(int16(61))}, |
| 4149 |
{V(int16(62)), V(uint(62))}, |
| 4150 |
{V(uint(63)), V(int16(63))}, |
| 4151 |
{V(int16(64)), V(uintptr(64))}, |
| 4152 |
{V(uintptr(65)), V(int16(65))}, |
| 4153 |
{V(int16(66)), V(float32(66))}, |
| 4154 |
{V(float32(67)), V(int16(67))}, |
| 4155 |
{V(int16(68)), V(float64(68))}, |
| 4156 |
{V(float64(69)), V(int16(69))}, |
| 4157 |
{V(uint16(70)), V(uint16(70))}, |
| 4158 |
{V(uint16(71)), V(int32(71))}, |
| 4159 |
{V(int32(72)), V(uint16(72))}, |
| 4160 |
{V(uint16(73)), V(uint32(73))}, |
| 4161 |
{V(uint32(74)), V(uint16(74))}, |
| 4162 |
{V(uint16(75)), V(int64(75))}, |
| 4163 |
{V(int64(76)), V(uint16(76))}, |
| 4164 |
{V(uint16(77)), V(uint64(77))}, |
| 4165 |
{V(uint64(78)), V(uint16(78))}, |
| 4166 |
{V(uint16(79)), V(int(79))}, |
| 4167 |
{V(int(80)), V(uint16(80))}, |
| 4168 |
{V(uint16(81)), V(uint(81))}, |
| 4169 |
{V(uint(82)), V(uint16(82))}, |
| 4170 |
{V(uint16(83)), V(uintptr(83))}, |
| 4171 |
{V(uintptr(84)), V(uint16(84))}, |
| 4172 |
{V(uint16(85)), V(float32(85))}, |
| 4173 |
{V(float32(86)), V(uint16(86))}, |
| 4174 |
{V(uint16(87)), V(float64(87))}, |
| 4175 |
{V(float64(88)), V(uint16(88))}, |
| 4176 |
{V(int32(89)), V(int32(89))}, |
| 4177 |
{V(int32(90)), V(uint32(90))}, |
| 4178 |
{V(uint32(91)), V(int32(91))}, |
| 4179 |
{V(int32(92)), V(int64(92))}, |
| 4180 |
{V(int64(93)), V(int32(93))}, |
| 4181 |
{V(int32(94)), V(uint64(94))}, |
| 4182 |
{V(uint64(95)), V(int32(95))}, |
| 4183 |
{V(int32(96)), V(int(96))}, |
| 4184 |
{V(int(97)), V(int32(97))}, |
| 4185 |
{V(int32(98)), V(uint(98))}, |
| 4186 |
{V(uint(99)), V(int32(99))}, |
| 4187 |
{V(int32(100)), V(uintptr(100))}, |
| 4188 |
{V(uintptr(101)), V(int32(101))}, |
| 4189 |
{V(int32(102)), V(float32(102))}, |
| 4190 |
{V(float32(103)), V(int32(103))}, |
| 4191 |
{V(int32(104)), V(float64(104))}, |
| 4192 |
{V(float64(105)), V(int32(105))}, |
| 4193 |
{V(uint32(106)), V(uint32(106))}, |
| 4194 |
{V(uint32(107)), V(int64(107))}, |
| 4195 |
{V(int64(108)), V(uint32(108))}, |
| 4196 |
{V(uint32(109)), V(uint64(109))}, |
| 4197 |
{V(uint64(110)), V(uint32(110))}, |
| 4198 |
{V(uint32(111)), V(int(111))}, |
| 4199 |
{V(int(112)), V(uint32(112))}, |
| 4200 |
{V(uint32(113)), V(uint(113))}, |
| 4201 |
{V(uint(114)), V(uint32(114))}, |
| 4202 |
{V(uint32(115)), V(uintptr(115))}, |
| 4203 |
{V(uintptr(116)), V(uint32(116))}, |
| 4204 |
{V(uint32(117)), V(float32(117))}, |
| 4205 |
{V(float32(118)), V(uint32(118))}, |
| 4206 |
{V(uint32(119)), V(float64(119))}, |
| 4207 |
{V(float64(120)), V(uint32(120))}, |
| 4208 |
{V(int64(121)), V(int64(121))}, |
| 4209 |
{V(int64(122)), V(uint64(122))}, |
| 4210 |
{V(uint64(123)), V(int64(123))}, |
| 4211 |
{V(int64(124)), V(int(124))}, |
| 4212 |
{V(int(125)), V(int64(125))}, |
| 4213 |
{V(int64(126)), V(uint(126))}, |
| 4214 |
{V(uint(127)), V(int64(127))}, |
| 4215 |
{V(int64(128)), V(uintptr(128))}, |
| 4216 |
{V(uintptr(129)), V(int64(129))}, |
| 4217 |
{V(int64(130)), V(float32(130))}, |
| 4218 |
{V(float32(131)), V(int64(131))}, |
| 4219 |
{V(int64(132)), V(float64(132))}, |
| 4220 |
{V(float64(133)), V(int64(133))}, |
| 4221 |
{V(uint64(134)), V(uint64(134))}, |
| 4222 |
{V(uint64(135)), V(int(135))}, |
| 4223 |
{V(int(136)), V(uint64(136))}, |
| 4224 |
{V(uint64(137)), V(uint(137))}, |
| 4225 |
{V(uint(138)), V(uint64(138))}, |
| 4226 |
{V(uint64(139)), V(uintptr(139))}, |
| 4227 |
{V(uintptr(140)), V(uint64(140))}, |
| 4228 |
{V(uint64(141)), V(float32(141))}, |
| 4229 |
{V(float32(142)), V(uint64(142))}, |
| 4230 |
{V(uint64(143)), V(float64(143))}, |
| 4231 |
{V(float64(144)), V(uint64(144))}, |
| 4232 |
{V(int(145)), V(int(145))}, |
| 4233 |
{V(int(146)), V(uint(146))}, |
| 4234 |
{V(uint(147)), V(int(147))}, |
| 4235 |
{V(int(148)), V(uintptr(148))}, |
| 4236 |
{V(uintptr(149)), V(int(149))}, |
| 4237 |
{V(int(150)), V(float32(150))}, |
| 4238 |
{V(float32(151)), V(int(151))}, |
| 4239 |
{V(int(152)), V(float64(152))}, |
| 4240 |
{V(float64(153)), V(int(153))}, |
| 4241 |
{V(uint(154)), V(uint(154))}, |
| 4242 |
{V(uint(155)), V(uintptr(155))}, |
| 4243 |
{V(uintptr(156)), V(uint(156))}, |
| 4244 |
{V(uint(157)), V(float32(157))}, |
| 4245 |
{V(float32(158)), V(uint(158))}, |
| 4246 |
{V(uint(159)), V(float64(159))}, |
| 4247 |
{V(float64(160)), V(uint(160))}, |
| 4248 |
{V(uintptr(161)), V(uintptr(161))}, |
| 4249 |
{V(uintptr(162)), V(float32(162))}, |
| 4250 |
{V(float32(163)), V(uintptr(163))}, |
| 4251 |
{V(uintptr(164)), V(float64(164))}, |
| 4252 |
{V(float64(165)), V(uintptr(165))}, |
| 4253 |
{V(float32(166)), V(float32(166))}, |
| 4254 |
{V(float32(167)), V(float64(167))}, |
| 4255 |
{V(float64(168)), V(float32(168))}, |
| 4256 |
{V(float64(169)), V(float64(169))}, |
| 4257 |
|
| 4258 |
// truncation |
| 4259 |
{V(float64(1.5)), V(int(1))}, |
| 4260 |
|
| 4261 |
// complex |
| 4262 |
{V(complex64(1i)), V(complex64(1i))}, |
| 4263 |
{V(complex64(2i)), V(complex128(2i))}, |
| 4264 |
{V(complex128(3i)), V(complex64(3i))}, |
| 4265 |
{V(complex128(4i)), V(complex128(4i))}, |
| 4266 |
|
| 4267 |
// string |
| 4268 |
{V(string("hello")), V(string("hello"))}, |
| 4269 |
{V(string("bytes1")), V([]byte("bytes1"))}, |
| 4270 |
{V([]byte("bytes2")), V(string("bytes2"))}, |
| 4271 |
{V([]byte("bytes3")), V([]byte("bytes3"))}, |
| 4272 |
{V(string("runes♝")), V([]rune("runes♝"))}, |
| 4273 |
{V([]rune("runes♕")), V(string("runes♕"))}, |
| 4274 |
{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, |
| 4275 |
{V(int('a')), V(string("a"))}, |
| 4276 |
{V(int8('a')), V(string("a"))}, |
| 4277 |
{V(int16('a')), V(string("a"))}, |
| 4278 |
{V(int32('a')), V(string("a"))}, |
| 4279 |
{V(int64('a')), V(string("a"))}, |
| 4280 |
{V(uint('a')), V(string("a"))}, |
| 4281 |
{V(uint8('a')), V(string("a"))}, |
| 4282 |
{V(uint16('a')), V(string("a"))}, |
| 4283 |
{V(uint32('a')), V(string("a"))}, |
| 4284 |
{V(uint64('a')), V(string("a"))}, |
| 4285 |
{V(uintptr('a')), V(string("a"))}, |
| 4286 |
{V(int(-1)), V(string("\uFFFD"))}, |
| 4287 |
{V(int8(-2)), V(string("\uFFFD"))}, |
| 4288 |
{V(int16(-3)), V(string("\uFFFD"))}, |
| 4289 |
{V(int32(-4)), V(string("\uFFFD"))}, |
| 4290 |
{V(int64(-5)), V(string("\uFFFD"))}, |
| 4291 |
{V(int64(-1 << 32)), V(string("\uFFFD"))}, |
| 4292 |
{V(int64(1 << 32)), V(string("\uFFFD"))}, |
| 4293 |
{V(uint(0x110001)), V(string("\uFFFD"))}, |
| 4294 |
{V(uint32(0x110002)), V(string("\uFFFD"))}, |
| 4295 |
{V(uint64(0x110003)), V(string("\uFFFD"))}, |
| 4296 |
{V(uint64(1 << 32)), V(string("\uFFFD"))}, |
| 4297 |
{V(uintptr(0x110004)), V(string("\uFFFD"))}, |
| 4298 |
|
| 4299 |
// named string |
| 4300 |
{V(MyString("hello")), V(string("hello"))}, |
| 4301 |
{V(string("hello")), V(MyString("hello"))}, |
| 4302 |
{V(string("hello")), V(string("hello"))}, |
| 4303 |
{V(MyString("hello")), V(MyString("hello"))}, |
| 4304 |
{V(MyString("bytes1")), V([]byte("bytes1"))}, |
| 4305 |
{V([]byte("bytes2")), V(MyString("bytes2"))}, |
| 4306 |
{V([]byte("bytes3")), V([]byte("bytes3"))}, |
| 4307 |
{V(MyString("runes♝")), V([]rune("runes♝"))}, |
| 4308 |
{V([]rune("runes♕")), V(MyString("runes♕"))}, |
| 4309 |
{V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, |
| 4310 |
{V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))}, |
| 4311 |
{V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))}, |
| 4312 |
{V(int('a')), V(MyString("a"))}, |
| 4313 |
{V(int8('a')), V(MyString("a"))}, |
| 4314 |
{V(int16('a')), V(MyString("a"))}, |
| 4315 |
{V(int32('a')), V(MyString("a"))}, |
| 4316 |
{V(int64('a')), V(MyString("a"))}, |
| 4317 |
{V(uint('a')), V(MyString("a"))}, |
| 4318 |
{V(uint8('a')), V(MyString("a"))}, |
| 4319 |
{V(uint16('a')), V(MyString("a"))}, |
| 4320 |
{V(uint32('a')), V(MyString("a"))}, |
| 4321 |
{V(uint64('a')), V(MyString("a"))}, |
| 4322 |
{V(uintptr('a')), V(MyString("a"))}, |
| 4323 |
{V(int(-1)), V(MyString("\uFFFD"))}, |
| 4324 |
{V(int8(-2)), V(MyString("\uFFFD"))}, |
| 4325 |
{V(int16(-3)), V(MyString("\uFFFD"))}, |
| 4326 |
{V(int32(-4)), V(MyString("\uFFFD"))}, |
| 4327 |
{V(int64(-5)), V(MyString("\uFFFD"))}, |
| 4328 |
{V(uint(0x110001)), V(MyString("\uFFFD"))}, |
| 4329 |
{V(uint32(0x110002)), V(MyString("\uFFFD"))}, |
| 4330 |
{V(uint64(0x110003)), V(MyString("\uFFFD"))}, |
| 4331 |
{V(uintptr(0x110004)), V(MyString("\uFFFD"))}, |
| 4332 |
|
| 4333 |
// named []byte |
| 4334 |
{V(string("bytes1")), V(MyBytes("bytes1"))}, |
| 4335 |
{V(MyBytes("bytes2")), V(string("bytes2"))}, |
| 4336 |
{V(MyBytes("bytes3")), V(MyBytes("bytes3"))}, |
| 4337 |
{V(MyString("bytes1")), V(MyBytes("bytes1"))}, |
| 4338 |
{V(MyBytes("bytes2")), V(MyString("bytes2"))}, |
| 4339 |
|
| 4340 |
// named []rune |
| 4341 |
{V(string("runes♝")), V(MyRunes("runes♝"))}, |
| 4342 |
{V(MyRunes("runes♕")), V(string("runes♕"))}, |
| 4343 |
{V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))}, |
| 4344 |
{V(MyString("runes♝")), V(MyRunes("runes♝"))}, |
| 4345 |
{V(MyRunes("runes♕")), V(MyString("runes♕"))}, |
| 4346 |
|
| 4347 |
// slice to array pointer |
| 4348 |
{V([]byte(nil)), V((*[0]byte)(nil))}, |
| 4349 |
{V([]byte{}), V(new([0]byte))}, |
| 4350 |
{V([]byte{7}), V(&[1]byte{7})}, |
| 4351 |
{V(MyBytes([]byte(nil))), V((*[0]byte)(nil))}, |
| 4352 |
{V(MyBytes([]byte{})), V(new([0]byte))}, |
| 4353 |
{V(MyBytes([]byte{9})), V(&[1]byte{9})}, |
| 4354 |
{V([]byte(nil)), V(MyBytesArrayPtr0(nil))}, |
| 4355 |
{V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))}, |
| 4356 |
{V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))}, |
| 4357 |
{V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))}, |
| 4358 |
{V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))}, |
| 4359 |
|
| 4360 |
{V([]byte(nil)), V((*MyBytesArray0)(nil))}, |
| 4361 |
{V([]byte{}), V((*MyBytesArray0)(new([0]byte)))}, |
| 4362 |
{V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})}, |
| 4363 |
{V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))}, |
| 4364 |
{V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))}, |
| 4365 |
{V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})}, |
| 4366 |
{V(new([0]byte)), V(new(MyBytesArray0))}, |
| 4367 |
{V(new(MyBytesArray0)), V(new([0]byte))}, |
| 4368 |
{V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))}, |
| 4369 |
{V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))}, |
| 4370 |
|
| 4371 |
// named types and equal underlying types |
| 4372 |
{V(new(int)), V(new(integer))}, |
| 4373 |
{V(new(integer)), V(new(int))}, |
| 4374 |
{V(Empty{}), V(struct{}{})}, |
| 4375 |
{V(new(Empty)), V(new(struct{}))}, |
| 4376 |
{V(struct{}{}), V(Empty{})}, |
| 4377 |
{V(new(struct{})), V(new(Empty))}, |
| 4378 |
{V(Empty{}), V(Empty{})}, |
| 4379 |
{V(MyBytes{}), V([]byte{})}, |
| 4380 |
{V([]byte{}), V(MyBytes{})}, |
| 4381 |
{V((func())(nil)), V(MyFunc(nil))}, |
| 4382 |
{V((MyFunc)(nil)), V((func())(nil))}, |
| 4383 |
|
| 4384 |
// structs with different tags |
| 4385 |
{V(struct { |
| 4386 |
x int `some:"foo"` |
| 4387 |
}{}), V(struct { |
| 4388 |
x int `some:"bar"` |
| 4389 |
}{})}, |
| 4390 |
|
| 4391 |
{V(struct { |
| 4392 |
x int `some:"bar"` |
| 4393 |
}{}), V(struct { |
| 4394 |
x int `some:"foo"` |
| 4395 |
}{})}, |
| 4396 |
|
| 4397 |
{V(MyStruct{}), V(struct { |
| 4398 |
x int `some:"foo"` |
| 4399 |
}{})}, |
| 4400 |
|
| 4401 |
{V(struct { |
| 4402 |
x int `some:"foo"` |
| 4403 |
}{}), V(MyStruct{})}, |
| 4404 |
|
| 4405 |
{V(MyStruct{}), V(struct { |
| 4406 |
x int `some:"bar"` |
| 4407 |
}{})}, |
| 4408 |
|
| 4409 |
{V(struct { |
| 4410 |
x int `some:"bar"` |
| 4411 |
}{}), V(MyStruct{})}, |
| 4412 |
|
| 4413 |
{V(MyStruct1{}), V(MyStruct2{})}, |
| 4414 |
{V(MyStruct2{}), V(MyStruct1{})}, |
| 4415 |
|
| 4416 |
// can convert *byte and *MyByte |
| 4417 |
{V((*byte)(nil)), V((*MyByte)(nil))}, |
| 4418 |
{V((*MyByte)(nil)), V((*byte)(nil))}, |
| 4419 |
|
| 4420 |
// cannot convert mismatched array sizes |
| 4421 |
{V([2]byte{}), V([2]byte{})}, |
| 4422 |
{V([3]byte{}), V([3]byte{})}, |
| 4423 |
|
| 4424 |
// cannot convert other instances |
| 4425 |
{V((**byte)(nil)), V((**byte)(nil))}, |
| 4426 |
{V((**MyByte)(nil)), V((**MyByte)(nil))}, |
| 4427 |
{V((chan byte)(nil)), V((chan byte)(nil))}, |
| 4428 |
{V((chan MyByte)(nil)), V((chan MyByte)(nil))}, |
| 4429 |
{V(([]byte)(nil)), V(([]byte)(nil))}, |
| 4430 |
{V(([]MyByte)(nil)), V(([]MyByte)(nil))}, |
| 4431 |
{V((map[int]byte)(nil)), V((map[int]byte)(nil))}, |
| 4432 |
{V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))}, |
| 4433 |
{V((map[byte]int)(nil)), V((map[byte]int)(nil))}, |
| 4434 |
{V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))}, |
| 4435 |
{V([2]byte{}), V([2]byte{})}, |
| 4436 |
{V([2]MyByte{}), V([2]MyByte{})}, |
| 4437 |
|
| 4438 |
// other |
| 4439 |
{V((***int)(nil)), V((***int)(nil))}, |
| 4440 |
{V((***byte)(nil)), V((***byte)(nil))}, |
| 4441 |
{V((***int32)(nil)), V((***int32)(nil))}, |
| 4442 |
{V((***int64)(nil)), V((***int64)(nil))}, |
| 4443 |
{V((chan byte)(nil)), V((chan byte)(nil))}, |
| 4444 |
{V((chan MyByte)(nil)), V((chan MyByte)(nil))}, |
| 4445 |
{V((map[int]bool)(nil)), V((map[int]bool)(nil))}, |
| 4446 |
{V((map[int]byte)(nil)), V((map[int]byte)(nil))}, |
| 4447 |
{V((map[uint]bool)(nil)), V((map[uint]bool)(nil))}, |
| 4448 |
{V([]uint(nil)), V([]uint(nil))}, |
| 4449 |
{V([]int(nil)), V([]int(nil))}, |
| 4450 |
{V(new(any)), V(new(any))}, |
| 4451 |
{V(new(io.Reader)), V(new(io.Reader))}, |
| 4452 |
{V(new(io.Writer)), V(new(io.Writer))}, |
| 4453 |
|
| 4454 |
// channels |
| 4455 |
{V(IntChan(nil)), V((chan<- int)(nil))}, |
| 4456 |
{V(IntChan(nil)), V((<-chan int)(nil))}, |
| 4457 |
{V((chan int)(nil)), V(IntChanRecv(nil))}, |
| 4458 |
{V((chan int)(nil)), V(IntChanSend(nil))}, |
| 4459 |
{V(IntChanRecv(nil)), V((<-chan int)(nil))}, |
| 4460 |
{V((<-chan int)(nil)), V(IntChanRecv(nil))}, |
| 4461 |
{V(IntChanSend(nil)), V((chan<- int)(nil))}, |
| 4462 |
{V((chan<- int)(nil)), V(IntChanSend(nil))}, |
| 4463 |
{V(IntChan(nil)), V((chan int)(nil))}, |
| 4464 |
{V((chan int)(nil)), V(IntChan(nil))}, |
| 4465 |
{V((chan int)(nil)), V((<-chan int)(nil))}, |
| 4466 |
{V((chan int)(nil)), V((chan<- int)(nil))}, |
| 4467 |
{V(BytesChan(nil)), V((chan<- []byte)(nil))}, |
| 4468 |
{V(BytesChan(nil)), V((<-chan []byte)(nil))}, |
| 4469 |
{V((chan []byte)(nil)), V(BytesChanRecv(nil))}, |
| 4470 |
{V((chan []byte)(nil)), V(BytesChanSend(nil))}, |
| 4471 |
{V(BytesChanRecv(nil)), V((<-chan []byte)(nil))}, |
| 4472 |
{V((<-chan []byte)(nil)), V(BytesChanRecv(nil))}, |
| 4473 |
{V(BytesChanSend(nil)), V((chan<- []byte)(nil))}, |
| 4474 |
{V((chan<- []byte)(nil)), V(BytesChanSend(nil))}, |
| 4475 |
{V(BytesChan(nil)), V((chan []byte)(nil))}, |
| 4476 |
{V((chan []byte)(nil)), V(BytesChan(nil))}, |
| 4477 |
{V((chan []byte)(nil)), V((<-chan []byte)(nil))}, |
| 4478 |
{V((chan []byte)(nil)), V((chan<- []byte)(nil))}, |
| 4479 |
|
| 4480 |
// cannot convert other instances (channels) |
| 4481 |
{V(IntChan(nil)), V(IntChan(nil))}, |
| 4482 |
{V(IntChanRecv(nil)), V(IntChanRecv(nil))}, |
| 4483 |
{V(IntChanSend(nil)), V(IntChanSend(nil))}, |
| 4484 |
{V(BytesChan(nil)), V(BytesChan(nil))}, |
| 4485 |
{V(BytesChanRecv(nil)), V(BytesChanRecv(nil))}, |
| 4486 |
{V(BytesChanSend(nil)), V(BytesChanSend(nil))}, |
| 4487 |
|
| 4488 |
// interfaces |
| 4489 |
{V(int(1)), EmptyInterfaceV(int(1))}, |
| 4490 |
{V(string("hello")), EmptyInterfaceV(string("hello"))}, |
| 4491 |
{V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, |
| 4492 |
{ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, |
| 4493 |
{V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))}, |
| 4494 |
} |
| 4495 |
|
| 4496 |
func TestConvert(t *testing.T) { |
| 4497 |
canConvert := map[[2]Type]bool{} |
| 4498 |
all := map[Type]bool{} |
| 4499 |
|
| 4500 |
for _, tt := range convertTests { |
| 4501 |
t1 := tt.in.Type() |
| 4502 |
if !t1.ConvertibleTo(t1) { |
| 4503 |
t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1) |
| 4504 |
continue |
| 4505 |
} |
| 4506 |
|
| 4507 |
t2 := tt.out.Type() |
| 4508 |
if !t1.ConvertibleTo(t2) { |
| 4509 |
t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2) |
| 4510 |
continue |
| 4511 |
} |
| 4512 |
|
| 4513 |
all[t1] = true |
| 4514 |
all[t2] = true |
| 4515 |
canConvert[[2]Type{t1, t2}] = true |
| 4516 |
|
| 4517 |
// vout1 represents the in value converted to the in type. |
| 4518 |
v1 := tt.in |
| 4519 |
if !v1.CanConvert(t1) { |
| 4520 |
t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1) |
| 4521 |
} |
| 4522 |
vout1 := v1.Convert(t1) |
| 4523 |
out1 := vout1.Interface() |
| 4524 |
if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) { |
| 4525 |
t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface()) |
| 4526 |
} |
| 4527 |
|
| 4528 |
// vout2 represents the in value converted to the out type. |
| 4529 |
if !v1.CanConvert(t2) { |
| 4530 |
t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2) |
| 4531 |
} |
| 4532 |
vout2 := v1.Convert(t2) |
| 4533 |
out2 := vout2.Interface() |
| 4534 |
if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) { |
| 4535 |
t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface()) |
| 4536 |
} |
| 4537 |
if got, want := vout2.Kind(), vout2.Type().Kind(); got != want { |
| 4538 |
t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want) |
| 4539 |
} |
| 4540 |
|
| 4541 |
// vout3 represents a new value of the out type, set to vout2. This makes |
| 4542 |
// sure the converted value vout2 is really usable as a regular value. |
| 4543 |
vout3 := New(t2).Elem() |
| 4544 |
vout3.Set(vout2) |
| 4545 |
out3 := vout3.Interface() |
| 4546 |
if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) { |
| 4547 |
t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface()) |
| 4548 |
} |
| 4549 |
|
| 4550 |
if IsRO(v1) { |
| 4551 |
t.Errorf("table entry %v is RO, should not be", v1) |
| 4552 |
} |
| 4553 |
if IsRO(vout1) { |
| 4554 |
t.Errorf("self-conversion output %v is RO, should not be", vout1) |
| 4555 |
} |
| 4556 |
if IsRO(vout2) { |
| 4557 |
t.Errorf("conversion output %v is RO, should not be", vout2) |
| 4558 |
} |
| 4559 |
if IsRO(vout3) { |
| 4560 |
t.Errorf("set(conversion output) %v is RO, should not be", vout3) |
| 4561 |
} |
| 4562 |
if !IsRO(MakeRO(v1).Convert(t1)) { |
| 4563 |
t.Errorf("RO self-conversion output %v is not RO, should be", v1) |
| 4564 |
} |
| 4565 |
if !IsRO(MakeRO(v1).Convert(t2)) { |
| 4566 |
t.Errorf("RO conversion output %v is not RO, should be", v1) |
| 4567 |
} |
| 4568 |
} |
| 4569 |
|
| 4570 |
// Assume that of all the types we saw during the tests, |
| 4571 |
// if there wasn't an explicit entry for a conversion between |
| 4572 |
// a pair of types, then it's not to be allowed. This checks for |
| 4573 |
// things like 'int64' converting to '*int'. |
| 4574 |
for t1 := range all { |
| 4575 |
for t2 := range all { |
| 4576 |
expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0 |
| 4577 |
if ok := t1.ConvertibleTo(t2); ok != expectOK { |
| 4578 |
t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK) |
| 4579 |
} |
| 4580 |
} |
| 4581 |
} |
| 4582 |
} |
| 4583 |
|
| 4584 |
func TestConvertPanic(t *testing.T) { |
| 4585 |
s := make([]byte, 4) |
| 4586 |
p := new([8]byte) |
| 4587 |
v := ValueOf(s) |
| 4588 |
pt := TypeOf(p) |
| 4589 |
if !v.Type().ConvertibleTo(pt) { |
| 4590 |
t.Errorf("[]byte should be convertible to *[8]byte") |
| 4591 |
} |
| 4592 |
if v.CanConvert(pt) { |
| 4593 |
t.Errorf("slice with length 4 should not be convertible to *[8]byte") |
| 4594 |
} |
| 4595 |
shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() { |
| 4596 |
_ = v.Convert(pt) |
| 4597 |
}) |
| 4598 |
} |
| 4599 |
|
| 4600 |
var gFloat32 float32 |
| 4601 |
|
| 4602 |
const snan uint32 = 0x7f800001 |
| 4603 |
|
| 4604 |
func TestConvertNaNs(t *testing.T) { |
| 4605 |
// Test to see if a store followed by a load of a signaling NaN |
| 4606 |
// maintains the signaling bit. (This used to fail on the 387 port.) |
| 4607 |
gFloat32 = math.Float32frombits(snan) |
| 4608 |
runtime.Gosched() // make sure we don't optimize the store/load away |
| 4609 |
if got := math.Float32bits(gFloat32); got != snan { |
| 4610 |
t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan) |
| 4611 |
} |
| 4612 |
// Test reflect's conversion between float32s. See issue 36400. |
| 4613 |
type myFloat32 float32 |
| 4614 |
x := V(myFloat32(math.Float32frombits(snan))) |
| 4615 |
y := x.Convert(TypeOf(float32(0))) |
| 4616 |
z := y.Interface().(float32) |
| 4617 |
if got := math.Float32bits(z); got != snan { |
| 4618 |
if runtime.GOARCH == "386" { |
| 4619 |
t.Skip("skipping test, float conversion not faithful") |
| 4620 |
} |
| 4621 |
t.Errorf("signaling nan conversion got %x, want %x", got, snan) |
| 4622 |
} |
| 4623 |
} |
| 4624 |
|
| 4625 |
type ComparableStruct struct { |
| 4626 |
X int |
| 4627 |
} |
| 4628 |
|
| 4629 |
type NonComparableStruct struct { |
| 4630 |
X int |
| 4631 |
Y map[string]int |
| 4632 |
} |
| 4633 |
|
| 4634 |
var comparableTests = []struct { |
| 4635 |
typ Type |
| 4636 |
ok bool |
| 4637 |
}{ |
| 4638 |
{TypeOf(1), true}, |
| 4639 |
{TypeOf("hello"), true}, |
| 4640 |
{TypeOf(new(byte)), true}, |
| 4641 |
{TypeOf((func())(nil)), false}, |
| 4642 |
{TypeOf([]byte{}), false}, |
| 4643 |
{TypeOf(map[string]int{}), false}, |
| 4644 |
{TypeOf(make(chan int)), true}, |
| 4645 |
{TypeOf(1.5), true}, |
| 4646 |
{TypeOf(false), true}, |
| 4647 |
{TypeOf(1i), true}, |
| 4648 |
{TypeOf(ComparableStruct{}), true}, |
| 4649 |
{TypeOf(NonComparableStruct{}), false}, |
| 4650 |
{TypeOf([10]map[string]int{}), false}, |
| 4651 |
{TypeOf([10]string{}), true}, |
| 4652 |
{TypeOf(new(any)).Elem(), true}, |
| 4653 |
} |
| 4654 |
|
| 4655 |
func TestComparable(t *testing.T) { |
| 4656 |
for _, tt := range comparableTests { |
| 4657 |
if ok := tt.typ.Comparable(); ok != tt.ok { |
| 4658 |
t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok) |
| 4659 |
} |
| 4660 |
} |
| 4661 |
} |
| 4662 |
|
| 4663 |
func TestOverflow(t *testing.T) { |
| 4664 |
if ovf := V(float64(0)).OverflowFloat(1e300); ovf { |
| 4665 |
t.Errorf("%v wrongly overflows float64", 1e300) |
| 4666 |
} |
| 4667 |
|
| 4668 |
maxFloat32 := float64((1<<24 - 1) << (127 - 23)) |
| 4669 |
if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf { |
| 4670 |
t.Errorf("%v wrongly overflows float32", maxFloat32) |
| 4671 |
} |
| 4672 |
ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52)) |
| 4673 |
if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf { |
| 4674 |
t.Errorf("%v should overflow float32", ovfFloat32) |
| 4675 |
} |
| 4676 |
if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf { |
| 4677 |
t.Errorf("%v should overflow float32", -ovfFloat32) |
| 4678 |
} |
| 4679 |
|
| 4680 |
maxInt32 := int64(0x7fffffff) |
| 4681 |
if ovf := V(int32(0)).OverflowInt(maxInt32); ovf { |
| 4682 |
t.Errorf("%v wrongly overflows int32", maxInt32) |
| 4683 |
} |
| 4684 |
if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf { |
| 4685 |
t.Errorf("%v wrongly overflows int32", -int64(1)<<31) |
| 4686 |
} |
| 4687 |
ovfInt32 := int64(1 << 31) |
| 4688 |
if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf { |
| 4689 |
t.Errorf("%v should overflow int32", ovfInt32) |
| 4690 |
} |
| 4691 |
|
| 4692 |
maxUint32 := uint64(0xffffffff) |
| 4693 |
if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf { |
| 4694 |
t.Errorf("%v wrongly overflows uint32", maxUint32) |
| 4695 |
} |
| 4696 |
ovfUint32 := uint64(1 << 32) |
| 4697 |
if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf { |
| 4698 |
t.Errorf("%v should overflow uint32", ovfUint32) |
| 4699 |
} |
| 4700 |
} |
| 4701 |
|
| 4702 |
func checkSameType(t *testing.T, x Type, y any) { |
| 4703 |
if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) { |
| 4704 |
t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y)) |
| 4705 |
} |
| 4706 |
} |
| 4707 |
|
| 4708 |
func TestArrayOf(t *testing.T) { |
| 4709 |
// check construction and use of type not in binary |
| 4710 |
tests := []struct { |
| 4711 |
n int |
| 4712 |
value func(i int) any |
| 4713 |
comparable bool |
| 4714 |
want string |
| 4715 |
}{ |
| 4716 |
{ |
| 4717 |
n: 0, |
| 4718 |
value: func(i int) any { type Tint int; return Tint(i) }, |
| 4719 |
comparable: true, |
| 4720 |
want: "[]", |
| 4721 |
}, |
| 4722 |
{ |
| 4723 |
n: 10, |
| 4724 |
value: func(i int) any { type Tint int; return Tint(i) }, |
| 4725 |
comparable: true, |
| 4726 |
want: "[0 1 2 3 4 5 6 7 8 9]", |
| 4727 |
}, |
| 4728 |
{ |
| 4729 |
n: 10, |
| 4730 |
value: func(i int) any { type Tfloat float64; return Tfloat(i) }, |
| 4731 |
comparable: true, |
| 4732 |
want: "[0 1 2 3 4 5 6 7 8 9]", |
| 4733 |
}, |
| 4734 |
{ |
| 4735 |
n: 10, |
| 4736 |
value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) }, |
| 4737 |
comparable: true, |
| 4738 |
want: "[0 1 2 3 4 5 6 7 8 9]", |
| 4739 |
}, |
| 4740 |
{ |
| 4741 |
n: 10, |
| 4742 |
value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} }, |
| 4743 |
comparable: true, |
| 4744 |
want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]", |
| 4745 |
}, |
| 4746 |
{ |
| 4747 |
n: 10, |
| 4748 |
value: func(i int) any { type Tint int; return []Tint{Tint(i)} }, |
| 4749 |
comparable: false, |
| 4750 |
want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", |
| 4751 |
}, |
| 4752 |
{ |
| 4753 |
n: 10, |
| 4754 |
value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} }, |
| 4755 |
comparable: true, |
| 4756 |
want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", |
| 4757 |
}, |
| 4758 |
{ |
| 4759 |
n: 10, |
| 4760 |
value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} }, |
| 4761 |
comparable: true, |
| 4762 |
want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", |
| 4763 |
}, |
| 4764 |
{ |
| 4765 |
n: 10, |
| 4766 |
value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} }, |
| 4767 |
comparable: false, |
| 4768 |
want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", |
| 4769 |
}, |
| 4770 |
{ |
| 4771 |
n: 10, |
| 4772 |
value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} }, |
| 4773 |
comparable: true, |
| 4774 |
want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", |
| 4775 |
}, |
| 4776 |
{ |
| 4777 |
n: 10, |
| 4778 |
value: func(i int) any { |
| 4779 |
type TstructUV struct { |
| 4780 |
U int |
| 4781 |
V float64 |
| 4782 |
} |
| 4783 |
return TstructUV{i, float64(i)} |
| 4784 |
}, |
| 4785 |
comparable: true, |
| 4786 |
want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", |
| 4787 |
}, |
| 4788 |
} |
| 4789 |
|
| 4790 |
for _, table := range tests { |
| 4791 |
at := ArrayOf(table.n, TypeOf(table.value(0))) |
| 4792 |
v := New(at).Elem() |
| 4793 |
vok := New(at).Elem() |
| 4794 |
vnot := New(at).Elem() |
| 4795 |
for i := 0; i < v.Len(); i++ { |
| 4796 |
v.Index(i).Set(ValueOf(table.value(i))) |
| 4797 |
vok.Index(i).Set(ValueOf(table.value(i))) |
| 4798 |
j := i |
| 4799 |
if i+1 == v.Len() { |
| 4800 |
j = i + 1 |
| 4801 |
} |
| 4802 |
vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element |
| 4803 |
} |
| 4804 |
s := fmt.Sprint(v.Interface()) |
| 4805 |
if s != table.want { |
| 4806 |
t.Errorf("constructed array = %s, want %s", s, table.want) |
| 4807 |
} |
| 4808 |
|
| 4809 |
if table.comparable != at.Comparable() { |
| 4810 |
t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable) |
| 4811 |
} |
| 4812 |
if table.comparable { |
| 4813 |
if table.n > 0 { |
| 4814 |
if DeepEqual(vnot.Interface(), v.Interface()) { |
| 4815 |
t.Errorf( |
| 4816 |
"arrays (%#v) compare ok (but should not)", |
| 4817 |
v.Interface(), |
| 4818 |
) |
| 4819 |
} |
| 4820 |
} |
| 4821 |
if !DeepEqual(vok.Interface(), v.Interface()) { |
| 4822 |
t.Errorf( |
| 4823 |
"arrays (%#v) compare NOT-ok (but should)", |
| 4824 |
v.Interface(), |
| 4825 |
) |
| 4826 |
} |
| 4827 |
} |
| 4828 |
} |
| 4829 |
|
| 4830 |
// check that type already in binary is found |
| 4831 |
type T int |
| 4832 |
checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{}) |
| 4833 |
} |
| 4834 |
|
| 4835 |
func TestArrayOfGC(t *testing.T) { |
| 4836 |
type T *uintptr |
| 4837 |
tt := TypeOf(T(nil)) |
| 4838 |
const n = 100 |
| 4839 |
var x []any |
| 4840 |
for i := 0; i < n; i++ { |
| 4841 |
v := New(ArrayOf(n, tt)).Elem() |
| 4842 |
for j := 0; j < v.Len(); j++ { |
| 4843 |
p := new(uintptr) |
| 4844 |
*p = uintptr(i*n + j) |
| 4845 |
v.Index(j).Set(ValueOf(p).Convert(tt)) |
| 4846 |
} |
| 4847 |
x = append(x, v.Interface()) |
| 4848 |
} |
| 4849 |
runtime.GC() |
| 4850 |
|
| 4851 |
for i, xi := range x { |
| 4852 |
v := ValueOf(xi) |
| 4853 |
for j := 0; j < v.Len(); j++ { |
| 4854 |
k := v.Index(j).Elem().Interface() |
| 4855 |
if k != uintptr(i*n+j) { |
| 4856 |
t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) |
| 4857 |
} |
| 4858 |
} |
| 4859 |
} |
| 4860 |
} |
| 4861 |
|
| 4862 |
func TestArrayOfAlg(t *testing.T) { |
| 4863 |
at := ArrayOf(6, TypeOf(byte(0))) |
| 4864 |
v1 := New(at).Elem() |
| 4865 |
v2 := New(at).Elem() |
| 4866 |
if v1.Interface() != v1.Interface() { |
| 4867 |
t.Errorf("constructed array %v not equal to itself", v1.Interface()) |
| 4868 |
} |
| 4869 |
v1.Index(5).Set(ValueOf(byte(1))) |
| 4870 |
if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { |
| 4871 |
t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) |
| 4872 |
} |
| 4873 |
|
| 4874 |
at = ArrayOf(6, TypeOf([]int(nil))) |
| 4875 |
v1 = New(at).Elem() |
| 4876 |
shouldPanic("", func() { _ = v1.Interface() == v1.Interface() }) |
| 4877 |
} |
| 4878 |
|
| 4879 |
func TestArrayOfGenericAlg(t *testing.T) { |
| 4880 |
at1 := ArrayOf(5, TypeOf(string(""))) |
| 4881 |
at := ArrayOf(6, at1) |
| 4882 |
v1 := New(at).Elem() |
| 4883 |
v2 := New(at).Elem() |
| 4884 |
if v1.Interface() != v1.Interface() { |
| 4885 |
t.Errorf("constructed array %v not equal to itself", v1.Interface()) |
| 4886 |
} |
| 4887 |
|
| 4888 |
v1.Index(0).Index(0).Set(ValueOf("abc")) |
| 4889 |
v2.Index(0).Index(0).Set(ValueOf("efg")) |
| 4890 |
if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { |
| 4891 |
t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) |
| 4892 |
} |
| 4893 |
|
| 4894 |
v1.Index(0).Index(0).Set(ValueOf("abc")) |
| 4895 |
v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3])) |
| 4896 |
if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 { |
| 4897 |
t.Errorf("constructed arrays %v and %v should be equal", i1, i2) |
| 4898 |
} |
| 4899 |
|
| 4900 |
// Test hash |
| 4901 |
m := MakeMap(MapOf(at, TypeOf(int(0)))) |
| 4902 |
m.SetMapIndex(v1, ValueOf(1)) |
| 4903 |
if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { |
| 4904 |
t.Errorf("constructed arrays %v and %v have different hashes", i1, i2) |
| 4905 |
} |
| 4906 |
} |
| 4907 |
|
| 4908 |
func TestArrayOfDirectIface(t *testing.T) { |
| 4909 |
{ |
| 4910 |
type T [1]*byte |
| 4911 |
i1 := Zero(TypeOf(T{})).Interface() |
| 4912 |
v1 := ValueOf(&i1).Elem() |
| 4913 |
p1 := v1.InterfaceData()[1] |
| 4914 |
|
| 4915 |
i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface() |
| 4916 |
v2 := ValueOf(&i2).Elem() |
| 4917 |
p2 := v2.InterfaceData()[1] |
| 4918 |
|
| 4919 |
if p1 != 0 { |
| 4920 |
t.Errorf("got p1=%v. want=%v", p1, nil) |
| 4921 |
} |
| 4922 |
|
| 4923 |
if p2 != 0 { |
| 4924 |
t.Errorf("got p2=%v. want=%v", p2, nil) |
| 4925 |
} |
| 4926 |
} |
| 4927 |
{ |
| 4928 |
type T [0]*byte |
| 4929 |
i1 := Zero(TypeOf(T{})).Interface() |
| 4930 |
v1 := ValueOf(&i1).Elem() |
| 4931 |
p1 := v1.InterfaceData()[1] |
| 4932 |
|
| 4933 |
i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface() |
| 4934 |
v2 := ValueOf(&i2).Elem() |
| 4935 |
p2 := v2.InterfaceData()[1] |
| 4936 |
|
| 4937 |
if p1 == 0 { |
| 4938 |
t.Errorf("got p1=%v. want=not-%v", p1, nil) |
| 4939 |
} |
| 4940 |
|
| 4941 |
if p2 == 0 { |
| 4942 |
t.Errorf("got p2=%v. want=not-%v", p2, nil) |
| 4943 |
} |
| 4944 |
} |
| 4945 |
} |
| 4946 |
|
| 4947 |
// Ensure passing in negative lengths panics. |
| 4948 |
// See https://golang.org/issue/43603 |
| 4949 |
func TestArrayOfPanicOnNegativeLength(t *testing.T) { |
| 4950 |
shouldPanic("reflect: negative length passed to ArrayOf", func() { |
| 4951 |
ArrayOf(-1, TypeOf(byte(0))) |
| 4952 |
}) |
| 4953 |
} |
| 4954 |
|
| 4955 |
func TestSliceOf(t *testing.T) { |
| 4956 |
// check construction and use of type not in binary |
| 4957 |
type T int |
| 4958 |
st := SliceOf(TypeOf(T(1))) |
| 4959 |
if got, want := st.String(), "[]reflect_test.T"; got != want { |
| 4960 |
t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want) |
| 4961 |
} |
| 4962 |
v := MakeSlice(st, 10, 10) |
| 4963 |
runtime.GC() |
| 4964 |
for i := 0; i < v.Len(); i++ { |
| 4965 |
v.Index(i).Set(ValueOf(T(i))) |
| 4966 |
runtime.GC() |
| 4967 |
} |
| 4968 |
s := fmt.Sprint(v.Interface()) |
| 4969 |
want := "[0 1 2 3 4 5 6 7 8 9]" |
| 4970 |
if s != want { |
| 4971 |
t.Errorf("constructed slice = %s, want %s", s, want) |
| 4972 |
} |
| 4973 |
|
| 4974 |
// check that type already in binary is found |
| 4975 |
type T1 int |
| 4976 |
checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{}) |
| 4977 |
} |
| 4978 |
|
| 4979 |
func TestSliceOverflow(t *testing.T) { |
| 4980 |
// check that MakeSlice panics when size of slice overflows uint |
| 4981 |
const S = 1e6 |
| 4982 |
s := uint(S) |
| 4983 |
l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1 |
| 4984 |
if l*s >= s { |
| 4985 |
t.Fatal("slice size does not overflow") |
| 4986 |
} |
| 4987 |
var x [S]byte |
| 4988 |
st := SliceOf(TypeOf(x)) |
| 4989 |
defer func() { |
| 4990 |
err := recover() |
| 4991 |
if err == nil { |
| 4992 |
t.Fatal("slice overflow does not panic") |
| 4993 |
} |
| 4994 |
}() |
| 4995 |
MakeSlice(st, int(l), int(l)) |
| 4996 |
} |
| 4997 |
|
| 4998 |
func TestSliceOfGC(t *testing.T) { |
| 4999 |
type T *uintptr |
| 5000 |
tt := TypeOf(T(nil)) |
| 5001 |
st := SliceOf(tt) |
| 5002 |
const n = 100 |
| 5003 |
var x []any |
| 5004 |
for i := 0; i < n; i++ { |
| 5005 |
v := MakeSlice(st, n, n) |
| 5006 |
for j := 0; j < v.Len(); j++ { |
| 5007 |
p := new(uintptr) |
| 5008 |
*p = uintptr(i*n + j) |
| 5009 |
v.Index(j).Set(ValueOf(p).Convert(tt)) |
| 5010 |
} |
| 5011 |
x = append(x, v.Interface()) |
| 5012 |
} |
| 5013 |
runtime.GC() |
| 5014 |
|
| 5015 |
for i, xi := range x { |
| 5016 |
v := ValueOf(xi) |
| 5017 |
for j := 0; j < v.Len(); j++ { |
| 5018 |
k := v.Index(j).Elem().Interface() |
| 5019 |
if k != uintptr(i*n+j) { |
| 5020 |
t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) |
| 5021 |
} |
| 5022 |
} |
| 5023 |
} |
| 5024 |
} |
| 5025 |
|
| 5026 |
func TestStructOfFieldName(t *testing.T) { |
| 5027 |
// invalid field name "1nvalid" |
| 5028 |
shouldPanic("has invalid name", func() { |
| 5029 |
StructOf([]StructField{ |
| 5030 |
{Name: "Valid", Type: TypeOf("")}, |
| 5031 |
{Name: "1nvalid", Type: TypeOf("")}, |
| 5032 |
}) |
| 5033 |
}) |
| 5034 |
|
| 5035 |
// invalid field name "+" |
| 5036 |
shouldPanic("has invalid name", func() { |
| 5037 |
StructOf([]StructField{ |
| 5038 |
{Name: "Val1d", Type: TypeOf("")}, |
| 5039 |
{Name: "+", Type: TypeOf("")}, |
| 5040 |
}) |
| 5041 |
}) |
| 5042 |
|
| 5043 |
// no field name |
| 5044 |
shouldPanic("has no name", func() { |
| 5045 |
StructOf([]StructField{ |
| 5046 |
{Name: "", Type: TypeOf("")}, |
| 5047 |
}) |
| 5048 |
}) |
| 5049 |
|
| 5050 |
// verify creation of a struct with valid struct fields |
| 5051 |
validFields := []StructField{ |
| 5052 |
{ |
| 5053 |
Name: "φ", |
| 5054 |
Type: TypeOf(""), |
| 5055 |
}, |
| 5056 |
{ |
| 5057 |
Name: "ValidName", |
| 5058 |
Type: TypeOf(""), |
| 5059 |
}, |
| 5060 |
{ |
| 5061 |
Name: "Val1dNam5", |
| 5062 |
Type: TypeOf(""), |
| 5063 |
}, |
| 5064 |
} |
| 5065 |
|
| 5066 |
validStruct := StructOf(validFields) |
| 5067 |
|
| 5068 |
const structStr = `struct { φ string; ValidName string; Val1dNam5 string }` |
| 5069 |
if got, want := validStruct.String(), structStr; got != want { |
| 5070 |
t.Errorf("StructOf(validFields).String()=%q, want %q", got, want) |
| 5071 |
} |
| 5072 |
} |
| 5073 |
|
| 5074 |
func TestStructOf(t *testing.T) { |
| 5075 |
// check construction and use of type not in binary |
| 5076 |
fields := []StructField{ |
| 5077 |
{ |
| 5078 |
Name: "S", |
| 5079 |
Tag: "s", |
| 5080 |
Type: TypeOf(""), |
| 5081 |
}, |
| 5082 |
{ |
| 5083 |
Name: "X", |
| 5084 |
Tag: "x", |
| 5085 |
Type: TypeOf(byte(0)), |
| 5086 |
}, |
| 5087 |
{ |
| 5088 |
Name: "Y", |
| 5089 |
Type: TypeOf(uint64(0)), |
| 5090 |
}, |
| 5091 |
{ |
| 5092 |
Name: "Z", |
| 5093 |
Type: TypeOf([3]uint16{}), |
| 5094 |
}, |
| 5095 |
} |
| 5096 |
|
| 5097 |
st := StructOf(fields) |
| 5098 |
v := New(st).Elem() |
| 5099 |
runtime.GC() |
| 5100 |
v.FieldByName("X").Set(ValueOf(byte(2))) |
| 5101 |
v.FieldByIndex([]int{1}).Set(ValueOf(byte(1))) |
| 5102 |
runtime.GC() |
| 5103 |
|
| 5104 |
s := fmt.Sprint(v.Interface()) |
| 5105 |
want := `{ 1 0 [0 0 0]}` |
| 5106 |
if s != want { |
| 5107 |
t.Errorf("constructed struct = %s, want %s", s, want) |
| 5108 |
} |
| 5109 |
const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }` |
| 5110 |
if got, want := st.String(), stStr; got != want { |
| 5111 |
t.Errorf("StructOf(fields).String()=%q, want %q", got, want) |
| 5112 |
} |
| 5113 |
|
| 5114 |
// check the size, alignment and field offsets |
| 5115 |
stt := TypeOf(struct { |
| 5116 |
String string |
| 5117 |
X byte |
| 5118 |
Y uint64 |
| 5119 |
Z [3]uint16 |
| 5120 |
}{}) |
| 5121 |
if st.Size() != stt.Size() { |
| 5122 |
t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size()) |
| 5123 |
} |
| 5124 |
if st.Align() != stt.Align() { |
| 5125 |
t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align()) |
| 5126 |
} |
| 5127 |
if st.FieldAlign() != stt.FieldAlign() { |
| 5128 |
t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign()) |
| 5129 |
} |
| 5130 |
for i := 0; i < st.NumField(); i++ { |
| 5131 |
o1 := st.Field(i).Offset |
| 5132 |
o2 := stt.Field(i).Offset |
| 5133 |
if o1 != o2 { |
| 5134 |
t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2) |
| 5135 |
} |
| 5136 |
} |
| 5137 |
|
| 5138 |
// Check size and alignment with a trailing zero-sized field. |
| 5139 |
st = StructOf([]StructField{ |
| 5140 |
{ |
| 5141 |
Name: "F1", |
| 5142 |
Type: TypeOf(byte(0)), |
| 5143 |
}, |
| 5144 |
{ |
| 5145 |
Name: "F2", |
| 5146 |
Type: TypeOf([0]*byte{}), |
| 5147 |
}, |
| 5148 |
}) |
| 5149 |
stt = TypeOf(struct { |
| 5150 |
G1 byte |
| 5151 |
G2 [0]*byte |
| 5152 |
}{}) |
| 5153 |
// Broken with gccgo for now--gccgo does not pad structs yet. |
| 5154 |
// if st.Size() != stt.Size() { |
| 5155 |
// t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size()) |
| 5156 |
// } |
| 5157 |
if st.Align() != stt.Align() { |
| 5158 |
t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align()) |
| 5159 |
} |
| 5160 |
if st.FieldAlign() != stt.FieldAlign() { |
| 5161 |
t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign()) |
| 5162 |
} |
| 5163 |
for i := 0; i < st.NumField(); i++ { |
| 5164 |
o1 := st.Field(i).Offset |
| 5165 |
o2 := stt.Field(i).Offset |
| 5166 |
if o1 != o2 { |
| 5167 |
t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2) |
| 5168 |
} |
| 5169 |
} |
| 5170 |
|
| 5171 |
// check duplicate names |
| 5172 |
shouldPanic("duplicate field", func() { |
| 5173 |
StructOf([]StructField{ |
| 5174 |
{Name: "string", PkgPath: "p", Type: TypeOf("")}, |
| 5175 |
{Name: "string", PkgPath: "p", Type: TypeOf("")}, |
| 5176 |
}) |
| 5177 |
}) |
| 5178 |
shouldPanic("has no name", func() { |
| 5179 |
StructOf([]StructField{ |
| 5180 |
{Type: TypeOf("")}, |
| 5181 |
{Name: "string", PkgPath: "p", Type: TypeOf("")}, |
| 5182 |
}) |
| 5183 |
}) |
| 5184 |
shouldPanic("has no name", func() { |
| 5185 |
StructOf([]StructField{ |
| 5186 |
{Type: TypeOf("")}, |
| 5187 |
{Type: TypeOf("")}, |
| 5188 |
}) |
| 5189 |
}) |
| 5190 |
// check that type already in binary is found |
| 5191 |
checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{}) |
| 5192 |
|
| 5193 |
// gccgo used to fail this test. |
| 5194 |
type structFieldType any |
| 5195 |
checkSameType(t, |
| 5196 |
StructOf([]StructField{ |
| 5197 |
{ |
| 5198 |
Name: "F", |
| 5199 |
Type: TypeOf((*structFieldType)(nil)).Elem(), |
| 5200 |
}, |
| 5201 |
}), |
| 5202 |
struct{ F structFieldType }{}) |
| 5203 |
} |
| 5204 |
|
| 5205 |
func TestStructOfExportRules(t *testing.T) { |
| 5206 |
type S1 struct{} |
| 5207 |
type s2 struct{} |
| 5208 |
type ΦType struct{} |
| 5209 |
type φType struct{} |
| 5210 |
|
| 5211 |
testPanic := func(i int, mustPanic bool, f func()) { |
| 5212 |
defer func() { |
| 5213 |
err := recover() |
| 5214 |
if err == nil && mustPanic { |
| 5215 |
t.Errorf("test-%d did not panic", i) |
| 5216 |
} |
| 5217 |
if err != nil && !mustPanic { |
| 5218 |
t.Errorf("test-%d panicked: %v\n", i, err) |
| 5219 |
} |
| 5220 |
}() |
| 5221 |
f() |
| 5222 |
} |
| 5223 |
|
| 5224 |
tests := []struct { |
| 5225 |
field StructField |
| 5226 |
mustPanic bool |
| 5227 |
exported bool |
| 5228 |
}{ |
| 5229 |
{ |
| 5230 |
field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})}, |
| 5231 |
exported: true, |
| 5232 |
}, |
| 5233 |
{ |
| 5234 |
field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))}, |
| 5235 |
exported: true, |
| 5236 |
}, |
| 5237 |
{ |
| 5238 |
field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})}, |
| 5239 |
mustPanic: true, |
| 5240 |
}, |
| 5241 |
{ |
| 5242 |
field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))}, |
| 5243 |
mustPanic: true, |
| 5244 |
}, |
| 5245 |
{ |
| 5246 |
field: StructField{Name: "Name", Type: nil, PkgPath: ""}, |
| 5247 |
mustPanic: true, |
| 5248 |
}, |
| 5249 |
{ |
| 5250 |
field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""}, |
| 5251 |
mustPanic: true, |
| 5252 |
}, |
| 5253 |
{ |
| 5254 |
field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"}, |
| 5255 |
mustPanic: true, |
| 5256 |
}, |
| 5257 |
{ |
| 5258 |
field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, |
| 5259 |
mustPanic: true, |
| 5260 |
}, |
| 5261 |
{ |
| 5262 |
field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"}, |
| 5263 |
mustPanic: true, |
| 5264 |
}, |
| 5265 |
{ |
| 5266 |
field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, |
| 5267 |
mustPanic: true, |
| 5268 |
}, |
| 5269 |
{ |
| 5270 |
field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"}, |
| 5271 |
}, |
| 5272 |
{ |
| 5273 |
field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"}, |
| 5274 |
}, |
| 5275 |
{ |
| 5276 |
field: StructField{Name: "S", Type: TypeOf(S1{})}, |
| 5277 |
exported: true, |
| 5278 |
}, |
| 5279 |
{ |
| 5280 |
field: StructField{Name: "S", Type: TypeOf((*S1)(nil))}, |
| 5281 |
exported: true, |
| 5282 |
}, |
| 5283 |
{ |
| 5284 |
field: StructField{Name: "S", Type: TypeOf(s2{})}, |
| 5285 |
exported: true, |
| 5286 |
}, |
| 5287 |
{ |
| 5288 |
field: StructField{Name: "S", Type: TypeOf((*s2)(nil))}, |
| 5289 |
exported: true, |
| 5290 |
}, |
| 5291 |
{ |
| 5292 |
field: StructField{Name: "s", Type: TypeOf(S1{})}, |
| 5293 |
mustPanic: true, |
| 5294 |
}, |
| 5295 |
{ |
| 5296 |
field: StructField{Name: "s", Type: TypeOf((*S1)(nil))}, |
| 5297 |
mustPanic: true, |
| 5298 |
}, |
| 5299 |
{ |
| 5300 |
field: StructField{Name: "s", Type: TypeOf(s2{})}, |
| 5301 |
mustPanic: true, |
| 5302 |
}, |
| 5303 |
{ |
| 5304 |
field: StructField{Name: "s", Type: TypeOf((*s2)(nil))}, |
| 5305 |
mustPanic: true, |
| 5306 |
}, |
| 5307 |
{ |
| 5308 |
field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"}, |
| 5309 |
}, |
| 5310 |
{ |
| 5311 |
field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, |
| 5312 |
}, |
| 5313 |
{ |
| 5314 |
field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"}, |
| 5315 |
}, |
| 5316 |
{ |
| 5317 |
field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, |
| 5318 |
}, |
| 5319 |
{ |
| 5320 |
field: StructField{Name: "", Type: TypeOf(ΦType{})}, |
| 5321 |
mustPanic: true, |
| 5322 |
}, |
| 5323 |
{ |
| 5324 |
field: StructField{Name: "", Type: TypeOf(φType{})}, |
| 5325 |
mustPanic: true, |
| 5326 |
}, |
| 5327 |
{ |
| 5328 |
field: StructField{Name: "Φ", Type: TypeOf(0)}, |
| 5329 |
exported: true, |
| 5330 |
}, |
| 5331 |
{ |
| 5332 |
field: StructField{Name: "φ", Type: TypeOf(0)}, |
| 5333 |
exported: false, |
| 5334 |
}, |
| 5335 |
} |
| 5336 |
|
| 5337 |
for i, test := range tests { |
| 5338 |
testPanic(i, test.mustPanic, func() { |
| 5339 |
typ := StructOf([]StructField{test.field}) |
| 5340 |
if typ == nil { |
| 5341 |
t.Errorf("test-%d: error creating struct type", i) |
| 5342 |
return |
| 5343 |
} |
| 5344 |
field := typ.Field(0) |
| 5345 |
n := field.Name |
| 5346 |
if n == "" { |
| 5347 |
panic("field.Name must not be empty") |
| 5348 |
} |
| 5349 |
exported := token.IsExported(n) |
| 5350 |
if exported != test.exported { |
| 5351 |
t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported) |
| 5352 |
} |
| 5353 |
if field.PkgPath != test.field.PkgPath { |
| 5354 |
t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath) |
| 5355 |
} |
| 5356 |
}) |
| 5357 |
} |
| 5358 |
} |
| 5359 |
|
| 5360 |
func TestStructOfGC(t *testing.T) { |
| 5361 |
type T *uintptr |
| 5362 |
tt := TypeOf(T(nil)) |
| 5363 |
fields := []StructField{ |
| 5364 |
{Name: "X", Type: tt}, |
| 5365 |
{Name: "Y", Type: tt}, |
| 5366 |
} |
| 5367 |
st := StructOf(fields) |
| 5368 |
|
| 5369 |
const n = 10000 |
| 5370 |
var x []any |
| 5371 |
for i := 0; i < n; i++ { |
| 5372 |
v := New(st).Elem() |
| 5373 |
for j := 0; j < v.NumField(); j++ { |
| 5374 |
p := new(uintptr) |
| 5375 |
*p = uintptr(i*n + j) |
| 5376 |
v.Field(j).Set(ValueOf(p).Convert(tt)) |
| 5377 |
} |
| 5378 |
x = append(x, v.Interface()) |
| 5379 |
} |
| 5380 |
runtime.GC() |
| 5381 |
|
| 5382 |
for i, xi := range x { |
| 5383 |
v := ValueOf(xi) |
| 5384 |
for j := 0; j < v.NumField(); j++ { |
| 5385 |
k := v.Field(j).Elem().Interface() |
| 5386 |
if k != uintptr(i*n+j) { |
| 5387 |
t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j) |
| 5388 |
} |
| 5389 |
} |
| 5390 |
} |
| 5391 |
} |
| 5392 |
|
| 5393 |
func TestStructOfAlg(t *testing.T) { |
| 5394 |
st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}}) |
| 5395 |
v1 := New(st).Elem() |
| 5396 |
v2 := New(st).Elem() |
| 5397 |
if !DeepEqual(v1.Interface(), v1.Interface()) { |
| 5398 |
t.Errorf("constructed struct %v not equal to itself", v1.Interface()) |
| 5399 |
} |
| 5400 |
v1.FieldByName("X").Set(ValueOf(int(1))) |
| 5401 |
if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { |
| 5402 |
t.Errorf("constructed structs %v and %v should not be equal", i1, i2) |
| 5403 |
} |
| 5404 |
|
| 5405 |
st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}}) |
| 5406 |
v1 = New(st).Elem() |
| 5407 |
shouldPanic("", func() { _ = v1.Interface() == v1.Interface() }) |
| 5408 |
} |
| 5409 |
|
| 5410 |
func TestStructOfGenericAlg(t *testing.T) { |
| 5411 |
st1 := StructOf([]StructField{ |
| 5412 |
{Name: "X", Tag: "x", Type: TypeOf(int64(0))}, |
| 5413 |
{Name: "Y", Type: TypeOf(string(""))}, |
| 5414 |
}) |
| 5415 |
st := StructOf([]StructField{ |
| 5416 |
{Name: "S0", Type: st1}, |
| 5417 |
{Name: "S1", Type: st1}, |
| 5418 |
}) |
| 5419 |
|
| 5420 |
tests := []struct { |
| 5421 |
rt Type |
| 5422 |
idx []int |
| 5423 |
}{ |
| 5424 |
{ |
| 5425 |
rt: st, |
| 5426 |
idx: []int{0, 1}, |
| 5427 |
}, |
| 5428 |
{ |
| 5429 |
rt: st1, |
| 5430 |
idx: []int{1}, |
| 5431 |
}, |
| 5432 |
{ |
| 5433 |
rt: StructOf( |
| 5434 |
[]StructField{ |
| 5435 |
{Name: "XX", Type: TypeOf([0]int{})}, |
| 5436 |
{Name: "YY", Type: TypeOf("")}, |
| 5437 |
}, |
| 5438 |
), |
| 5439 |
idx: []int{1}, |
| 5440 |
}, |
| 5441 |
{ |
| 5442 |
rt: StructOf( |
| 5443 |
[]StructField{ |
| 5444 |
{Name: "XX", Type: TypeOf([0]int{})}, |
| 5445 |
{Name: "YY", Type: TypeOf("")}, |
| 5446 |
{Name: "ZZ", Type: TypeOf([2]int{})}, |
| 5447 |
}, |
| 5448 |
), |
| 5449 |
idx: []int{1}, |
| 5450 |
}, |
| 5451 |
{ |
| 5452 |
rt: StructOf( |
| 5453 |
[]StructField{ |
| 5454 |
{Name: "XX", Type: TypeOf([1]int{})}, |
| 5455 |
{Name: "YY", Type: TypeOf("")}, |
| 5456 |
}, |
| 5457 |
), |
| 5458 |
idx: []int{1}, |
| 5459 |
}, |
| 5460 |
{ |
| 5461 |
rt: StructOf( |
| 5462 |
[]StructField{ |
| 5463 |
{Name: "XX", Type: TypeOf([1]int{})}, |
| 5464 |
{Name: "YY", Type: TypeOf("")}, |
| 5465 |
{Name: "ZZ", Type: TypeOf([1]int{})}, |
| 5466 |
}, |
| 5467 |
), |
| 5468 |
idx: []int{1}, |
| 5469 |
}, |
| 5470 |
{ |
| 5471 |
rt: StructOf( |
| 5472 |
[]StructField{ |
| 5473 |
{Name: "XX", Type: TypeOf([2]int{})}, |
| 5474 |
{Name: "YY", Type: TypeOf("")}, |
| 5475 |
{Name: "ZZ", Type: TypeOf([2]int{})}, |
| 5476 |
}, |
| 5477 |
), |
| 5478 |
idx: []int{1}, |
| 5479 |
}, |
| 5480 |
{ |
| 5481 |
rt: StructOf( |
| 5482 |
[]StructField{ |
| 5483 |
{Name: "XX", Type: TypeOf(int64(0))}, |
| 5484 |
{Name: "YY", Type: TypeOf(byte(0))}, |
| 5485 |
{Name: "ZZ", Type: TypeOf("")}, |
| 5486 |
}, |
| 5487 |
), |
| 5488 |
idx: []int{2}, |
| 5489 |
}, |
| 5490 |
{ |
| 5491 |
rt: StructOf( |
| 5492 |
[]StructField{ |
| 5493 |
{Name: "XX", Type: TypeOf(int64(0))}, |
| 5494 |
{Name: "YY", Type: TypeOf(int64(0))}, |
| 5495 |
{Name: "ZZ", Type: TypeOf("")}, |
| 5496 |
{Name: "AA", Type: TypeOf([1]int64{})}, |
| 5497 |
}, |
| 5498 |
), |
| 5499 |
idx: []int{2}, |
| 5500 |
}, |
| 5501 |
} |
| 5502 |
|
| 5503 |
for _, table := range tests { |
| 5504 |
v1 := New(table.rt).Elem() |
| 5505 |
v2 := New(table.rt).Elem() |
| 5506 |
|
| 5507 |
if !DeepEqual(v1.Interface(), v1.Interface()) { |
| 5508 |
t.Errorf("constructed struct %v not equal to itself", v1.Interface()) |
| 5509 |
} |
| 5510 |
|
| 5511 |
v1.FieldByIndex(table.idx).Set(ValueOf("abc")) |
| 5512 |
v2.FieldByIndex(table.idx).Set(ValueOf("def")) |
| 5513 |
if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { |
| 5514 |
t.Errorf("constructed structs %v and %v should not be equal", i1, i2) |
| 5515 |
} |
| 5516 |
|
| 5517 |
abc := "abc" |
| 5518 |
v1.FieldByIndex(table.idx).Set(ValueOf(abc)) |
| 5519 |
val := "+" + abc + "-" |
| 5520 |
v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4])) |
| 5521 |
if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { |
| 5522 |
t.Errorf("constructed structs %v and %v should be equal", i1, i2) |
| 5523 |
} |
| 5524 |
|
| 5525 |
// Test hash |
| 5526 |
m := MakeMap(MapOf(table.rt, TypeOf(int(0)))) |
| 5527 |
m.SetMapIndex(v1, ValueOf(1)) |
| 5528 |
if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { |
| 5529 |
t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2) |
| 5530 |
} |
| 5531 |
|
| 5532 |
v2.FieldByIndex(table.idx).Set(ValueOf("abc")) |
| 5533 |
if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { |
| 5534 |
t.Errorf("constructed structs %v and %v should be equal", i1, i2) |
| 5535 |
} |
| 5536 |
|
| 5537 |
if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { |
| 5538 |
t.Errorf("constructed structs %v and %v have different hashes", i1, i2) |
| 5539 |
} |
| 5540 |
} |
| 5541 |
} |
| 5542 |
|
| 5543 |
func TestStructOfDirectIface(t *testing.T) { |
| 5544 |
{ |
| 5545 |
type T struct{ X [1]*byte } |
| 5546 |
i1 := Zero(TypeOf(T{})).Interface() |
| 5547 |
v1 := ValueOf(&i1).Elem() |
| 5548 |
p1 := v1.InterfaceData()[1] |
| 5549 |
|
| 5550 |
i2 := Zero(StructOf([]StructField{ |
| 5551 |
{ |
| 5552 |
Name: "X", |
| 5553 |
Type: ArrayOf(1, TypeOf((*int8)(nil))), |
| 5554 |
}, |
| 5555 |
})).Interface() |
| 5556 |
v2 := ValueOf(&i2).Elem() |
| 5557 |
p2 := v2.InterfaceData()[1] |
| 5558 |
|
| 5559 |
if p1 != 0 { |
| 5560 |
t.Errorf("got p1=%v. want=%v", p1, nil) |
| 5561 |
} |
| 5562 |
|
| 5563 |
if p2 != 0 { |
| 5564 |
t.Errorf("got p2=%v. want=%v", p2, nil) |
| 5565 |
} |
| 5566 |
} |
| 5567 |
{ |
| 5568 |
type T struct{ X [0]*byte } |
| 5569 |
i1 := Zero(TypeOf(T{})).Interface() |
| 5570 |
v1 := ValueOf(&i1).Elem() |
| 5571 |
p1 := v1.InterfaceData()[1] |
| 5572 |
|
| 5573 |
i2 := Zero(StructOf([]StructField{ |
| 5574 |
{ |
| 5575 |
Name: "X", |
| 5576 |
Type: ArrayOf(0, TypeOf((*int8)(nil))), |
| 5577 |
}, |
| 5578 |
})).Interface() |
| 5579 |
v2 := ValueOf(&i2).Elem() |
| 5580 |
p2 := v2.InterfaceData()[1] |
| 5581 |
|
| 5582 |
if p1 == 0 { |
| 5583 |
t.Errorf("got p1=%v. want=not-%v", p1, nil) |
| 5584 |
} |
| 5585 |
|
| 5586 |
if p2 == 0 { |
| 5587 |
t.Errorf("got p2=%v. want=not-%v", p2, nil) |
| 5588 |
} |
| 5589 |
} |
| 5590 |
} |
| 5591 |
|
| 5592 |
type StructI int |
| 5593 |
|
| 5594 |
func (i StructI) Get() int { return int(i) } |
| 5595 |
|
| 5596 |
type StructIPtr int |
| 5597 |
|
| 5598 |
func (i *StructIPtr) Get() int { return int(*i) } |
| 5599 |
func (i *StructIPtr) Set(v int) { *(*int)(i) = v } |
| 5600 |
|
| 5601 |
type SettableStruct struct { |
| 5602 |
SettableField int |
| 5603 |
} |
| 5604 |
|
| 5605 |
func (p *SettableStruct) Set(v int) { p.SettableField = v } |
| 5606 |
|
| 5607 |
type SettablePointer struct { |
| 5608 |
SettableField *int |
| 5609 |
} |
| 5610 |
|
| 5611 |
func (p *SettablePointer) Set(v int) { *p.SettableField = v } |
| 5612 |
|
| 5613 |
/* |
| 5614 |
gccgo does not yet support StructOf with methods. |
| 5615 |
|
| 5616 |
func TestStructOfWithInterface(t *testing.T) { |
| 5617 |
const want = 42 |
| 5618 |
type Iface interface { |
| 5619 |
Get() int |
| 5620 |
} |
| 5621 |
type IfaceSet interface { |
| 5622 |
Set(int) |
| 5623 |
} |
| 5624 |
tests := []struct { |
| 5625 |
name string |
| 5626 |
typ Type |
| 5627 |
val Value |
| 5628 |
impl bool |
| 5629 |
}{ |
| 5630 |
{ |
| 5631 |
name: "StructI", |
| 5632 |
typ: TypeOf(StructI(want)), |
| 5633 |
val: ValueOf(StructI(want)), |
| 5634 |
impl: true, |
| 5635 |
}, |
| 5636 |
{ |
| 5637 |
name: "StructI", |
| 5638 |
typ: PointerTo(TypeOf(StructI(want))), |
| 5639 |
val: ValueOf(func() any { |
| 5640 |
v := StructI(want) |
| 5641 |
return &v |
| 5642 |
}()), |
| 5643 |
impl: true, |
| 5644 |
}, |
| 5645 |
{ |
| 5646 |
name: "StructIPtr", |
| 5647 |
typ: PointerTo(TypeOf(StructIPtr(want))), |
| 5648 |
val: ValueOf(func() any { |
| 5649 |
v := StructIPtr(want) |
| 5650 |
return &v |
| 5651 |
}()), |
| 5652 |
impl: true, |
| 5653 |
}, |
| 5654 |
{ |
| 5655 |
name: "StructIPtr", |
| 5656 |
typ: TypeOf(StructIPtr(want)), |
| 5657 |
val: ValueOf(StructIPtr(want)), |
| 5658 |
impl: false, |
| 5659 |
}, |
| 5660 |
// { |
| 5661 |
// typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn |
| 5662 |
// val: ValueOf(StructI(want)), |
| 5663 |
// impl: true, |
| 5664 |
// }, |
| 5665 |
} |
| 5666 |
|
| 5667 |
for i, table := range tests { |
| 5668 |
for j := 0; j < 2; j++ { |
| 5669 |
var fields []StructField |
| 5670 |
if j == 1 { |
| 5671 |
fields = append(fields, StructField{ |
| 5672 |
Name: "Dummy", |
| 5673 |
PkgPath: "", |
| 5674 |
Type: TypeOf(int(0)), |
| 5675 |
}) |
| 5676 |
} |
| 5677 |
fields = append(fields, StructField{ |
| 5678 |
Name: table.name, |
| 5679 |
Anonymous: true, |
| 5680 |
PkgPath: "", |
| 5681 |
Type: table.typ, |
| 5682 |
}) |
| 5683 |
|
| 5684 |
// We currently do not correctly implement methods |
| 5685 |
// for embedded fields other than the first. |
| 5686 |
// Therefore, for now, we expect those methods |
| 5687 |
// to not exist. See issues 15924 and 20824. |
| 5688 |
// When those issues are fixed, this test of panic |
| 5689 |
// should be removed. |
| 5690 |
if j == 1 && table.impl { |
| 5691 |
func() { |
| 5692 |
defer func() { |
| 5693 |
if err := recover(); err == nil { |
| 5694 |
t.Errorf("test-%d-%d did not panic", i, j) |
| 5695 |
} |
| 5696 |
}() |
| 5697 |
_ = StructOf(fields) |
| 5698 |
}() |
| 5699 |
continue |
| 5700 |
} |
| 5701 |
|
| 5702 |
rt := StructOf(fields) |
| 5703 |
rv := New(rt).Elem() |
| 5704 |
rv.Field(j).Set(table.val) |
| 5705 |
|
| 5706 |
if _, ok := rv.Interface().(Iface); ok != table.impl { |
| 5707 |
if table.impl { |
| 5708 |
t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ) |
| 5709 |
} else { |
| 5710 |
t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ) |
| 5711 |
} |
| 5712 |
continue |
| 5713 |
} |
| 5714 |
|
| 5715 |
if !table.impl { |
| 5716 |
continue |
| 5717 |
} |
| 5718 |
|
| 5719 |
v := rv.Interface().(Iface).Get() |
| 5720 |
if v != want { |
| 5721 |
t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want) |
| 5722 |
} |
| 5723 |
|
| 5724 |
fct := rv.MethodByName("Get") |
| 5725 |
out := fct.Call(nil) |
| 5726 |
if !DeepEqual(out[0].Interface(), want) { |
| 5727 |
t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want) |
| 5728 |
} |
| 5729 |
} |
| 5730 |
} |
| 5731 |
|
| 5732 |
// Test an embedded nil pointer with pointer methods. |
| 5733 |
fields := []StructField{{ |
| 5734 |
Name: "StructIPtr", |
| 5735 |
Anonymous: true, |
| 5736 |
Type: PointerTo(TypeOf(StructIPtr(want))), |
| 5737 |
}} |
| 5738 |
rt := StructOf(fields) |
| 5739 |
rv := New(rt).Elem() |
| 5740 |
// This should panic since the pointer is nil. |
| 5741 |
shouldPanic("", func() { |
| 5742 |
rv.Interface().(IfaceSet).Set(want) |
| 5743 |
}) |
| 5744 |
|
| 5745 |
// Test an embedded nil pointer to a struct with pointer methods. |
| 5746 |
|
| 5747 |
fields = []StructField{{ |
| 5748 |
Name: "SettableStruct", |
| 5749 |
Anonymous: true, |
| 5750 |
Type: PointerTo(TypeOf(SettableStruct{})), |
| 5751 |
}} |
| 5752 |
rt = StructOf(fields) |
| 5753 |
rv = New(rt).Elem() |
| 5754 |
// This should panic since the pointer is nil. |
| 5755 |
shouldPanic("", func() { |
| 5756 |
rv.Interface().(IfaceSet).Set(want) |
| 5757 |
}) |
| 5758 |
|
| 5759 |
// The behavior is different if there is a second field, |
| 5760 |
// since now an interface value holds a pointer to the struct |
| 5761 |
// rather than just holding a copy of the struct. |
| 5762 |
fields = []StructField{ |
| 5763 |
{ |
| 5764 |
Name: "SettableStruct", |
| 5765 |
Anonymous: true, |
| 5766 |
Type: PointerTo(TypeOf(SettableStruct{})), |
| 5767 |
}, |
| 5768 |
{ |
| 5769 |
Name: "EmptyStruct", |
| 5770 |
Anonymous: true, |
| 5771 |
Type: StructOf(nil), |
| 5772 |
}, |
| 5773 |
} |
| 5774 |
// With the current implementation this is expected to panic. |
| 5775 |
// Ideally it should work and we should be able to see a panic |
| 5776 |
// if we call the Set method. |
| 5777 |
shouldPanic("", func() { |
| 5778 |
StructOf(fields) |
| 5779 |
}) |
| 5780 |
|
| 5781 |
// Embed a field that can be stored directly in an interface, |
| 5782 |
// with a second field. |
| 5783 |
fields = []StructField{ |
| 5784 |
{ |
| 5785 |
Name: "SettablePointer", |
| 5786 |
Anonymous: true, |
| 5787 |
Type: TypeOf(SettablePointer{}), |
| 5788 |
}, |
| 5789 |
{ |
| 5790 |
Name: "EmptyStruct", |
| 5791 |
Anonymous: true, |
| 5792 |
Type: StructOf(nil), |
| 5793 |
}, |
| 5794 |
} |
| 5795 |
// With the current implementation this is expected to panic. |
| 5796 |
// Ideally it should work and we should be able to call the |
| 5797 |
// Set and Get methods. |
| 5798 |
shouldPanic("", func() { |
| 5799 |
StructOf(fields) |
| 5800 |
}) |
| 5801 |
} |
| 5802 |
*/ |
| 5803 |
|
| 5804 |
func TestStructOfTooManyFields(t *testing.T) { |
| 5805 |
if runtime.Compiler == "gccgo" { |
| 5806 |
t.Skip("gccgo does not yet implement embedded fields with methods") |
| 5807 |
} |
| 5808 |
|
| 5809 |
// Bug Fix: #25402 - this should not panic |
| 5810 |
tt := StructOf([]StructField{ |
| 5811 |
{Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true}, |
| 5812 |
}) |
| 5813 |
|
| 5814 |
if _, present := tt.MethodByName("After"); !present { |
| 5815 |
t.Errorf("Expected method `After` to be found") |
| 5816 |
} |
| 5817 |
} |
| 5818 |
|
| 5819 |
func TestStructOfDifferentPkgPath(t *testing.T) { |
| 5820 |
fields := []StructField{ |
| 5821 |
{ |
| 5822 |
Name: "f1", |
| 5823 |
PkgPath: "p1", |
| 5824 |
Type: TypeOf(int(0)), |
| 5825 |
}, |
| 5826 |
{ |
| 5827 |
Name: "f2", |
| 5828 |
PkgPath: "p2", |
| 5829 |
Type: TypeOf(int(0)), |
| 5830 |
}, |
| 5831 |
} |
| 5832 |
shouldPanic("different PkgPath", func() { |
| 5833 |
StructOf(fields) |
| 5834 |
}) |
| 5835 |
} |
| 5836 |
|
| 5837 |
func TestChanOf(t *testing.T) { |
| 5838 |
// check construction and use of type not in binary |
| 5839 |
type T string |
| 5840 |
ct := ChanOf(BothDir, TypeOf(T(""))) |
| 5841 |
v := MakeChan(ct, 2) |
| 5842 |
runtime.GC() |
| 5843 |
v.Send(ValueOf(T("hello"))) |
| 5844 |
runtime.GC() |
| 5845 |
v.Send(ValueOf(T("world"))) |
| 5846 |
runtime.GC() |
| 5847 |
|
| 5848 |
sv1, _ := v.Recv() |
| 5849 |
sv2, _ := v.Recv() |
| 5850 |
s1 := sv1.String() |
| 5851 |
s2 := sv2.String() |
| 5852 |
if s1 != "hello" || s2 != "world" { |
| 5853 |
t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world") |
| 5854 |
} |
| 5855 |
|
| 5856 |
// check that type already in binary is found |
| 5857 |
type T1 int |
| 5858 |
checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil)) |
| 5859 |
|
| 5860 |
// Check arrow token association in undefined chan types. |
| 5861 |
var left chan<- chan T |
| 5862 |
var right chan (<-chan T) |
| 5863 |
tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T("")))) |
| 5864 |
tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T("")))) |
| 5865 |
if tLeft != TypeOf(left) { |
| 5866 |
t.Errorf("chan<-chan: have %s, want %T", tLeft, left) |
| 5867 |
} |
| 5868 |
if tRight != TypeOf(right) { |
| 5869 |
t.Errorf("chan<-chan: have %s, want %T", tRight, right) |
| 5870 |
} |
| 5871 |
} |
| 5872 |
|
| 5873 |
func TestChanOfDir(t *testing.T) { |
| 5874 |
// check construction and use of type not in binary |
| 5875 |
type T string |
| 5876 |
crt := ChanOf(RecvDir, TypeOf(T(""))) |
| 5877 |
cst := ChanOf(SendDir, TypeOf(T(""))) |
| 5878 |
|
| 5879 |
// check that type already in binary is found |
| 5880 |
type T1 int |
| 5881 |
checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil)) |
| 5882 |
checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil)) |
| 5883 |
|
| 5884 |
// check String form of ChanDir |
| 5885 |
if crt.ChanDir().String() != "<-chan" { |
| 5886 |
t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan") |
| 5887 |
} |
| 5888 |
if cst.ChanDir().String() != "chan<-" { |
| 5889 |
t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-") |
| 5890 |
} |
| 5891 |
} |
| 5892 |
|
| 5893 |
func TestChanOfGC(t *testing.T) { |
| 5894 |
done := make(chan bool, 1) |
| 5895 |
go func() { |
| 5896 |
select { |
| 5897 |
case <-done: |
| 5898 |
case <-time.After(5 * time.Second): |
| 5899 |
panic("deadlock in TestChanOfGC") |
| 5900 |
} |
| 5901 |
}() |
| 5902 |
|
| 5903 |
defer func() { |
| 5904 |
done <- true |
| 5905 |
}() |
| 5906 |
|
| 5907 |
type T *uintptr |
| 5908 |
tt := TypeOf(T(nil)) |
| 5909 |
ct := ChanOf(BothDir, tt) |
| 5910 |
|
| 5911 |
// NOTE: The garbage collector handles allocated channels specially, |
| 5912 |
// so we have to save pointers to channels in x; the pointer code will |
| 5913 |
// use the gc info in the newly constructed chan type. |
| 5914 |
const n = 100 |
| 5915 |
var x []any |
| 5916 |
for i := 0; i < n; i++ { |
| 5917 |
v := MakeChan(ct, n) |
| 5918 |
for j := 0; j < n; j++ { |
| 5919 |
p := new(uintptr) |
| 5920 |
*p = uintptr(i*n + j) |
| 5921 |
v.Send(ValueOf(p).Convert(tt)) |
| 5922 |
} |
| 5923 |
pv := New(ct) |
| 5924 |
pv.Elem().Set(v) |
| 5925 |
x = append(x, pv.Interface()) |
| 5926 |
} |
| 5927 |
runtime.GC() |
| 5928 |
|
| 5929 |
for i, xi := range x { |
| 5930 |
v := ValueOf(xi).Elem() |
| 5931 |
for j := 0; j < n; j++ { |
| 5932 |
pv, _ := v.Recv() |
| 5933 |
k := pv.Elem().Interface() |
| 5934 |
if k != uintptr(i*n+j) { |
| 5935 |
t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) |
| 5936 |
} |
| 5937 |
} |
| 5938 |
} |
| 5939 |
} |
| 5940 |
|
| 5941 |
func TestMapOf(t *testing.T) { |
| 5942 |
// check construction and use of type not in binary |
| 5943 |
type K string |
| 5944 |
type V float64 |
| 5945 |
|
| 5946 |
v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0)))) |
| 5947 |
runtime.GC() |
| 5948 |
v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1))) |
| 5949 |
runtime.GC() |
| 5950 |
|
| 5951 |
s := fmt.Sprint(v.Interface()) |
| 5952 |
want := "map[a:1]" |
| 5953 |
if s != want { |
| 5954 |
t.Errorf("constructed map = %s, want %s", s, want) |
| 5955 |
} |
| 5956 |
|
| 5957 |
// check that type already in binary is found |
| 5958 |
checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil)) |
| 5959 |
|
| 5960 |
// check that invalid key type panics |
| 5961 |
shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) }) |
| 5962 |
} |
| 5963 |
|
| 5964 |
func TestMapOfGCKeys(t *testing.T) { |
| 5965 |
type T *uintptr |
| 5966 |
tt := TypeOf(T(nil)) |
| 5967 |
mt := MapOf(tt, TypeOf(false)) |
| 5968 |
|
| 5969 |
// NOTE: The garbage collector handles allocated maps specially, |
| 5970 |
// so we have to save pointers to maps in x; the pointer code will |
| 5971 |
// use the gc info in the newly constructed map type. |
| 5972 |
const n = 100 |
| 5973 |
var x []any |
| 5974 |
for i := 0; i < n; i++ { |
| 5975 |
v := MakeMap(mt) |
| 5976 |
for j := 0; j < n; j++ { |
| 5977 |
p := new(uintptr) |
| 5978 |
*p = uintptr(i*n + j) |
| 5979 |
v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true)) |
| 5980 |
} |
| 5981 |
pv := New(mt) |
| 5982 |
pv.Elem().Set(v) |
| 5983 |
x = append(x, pv.Interface()) |
| 5984 |
} |
| 5985 |
runtime.GC() |
| 5986 |
|
| 5987 |
for i, xi := range x { |
| 5988 |
v := ValueOf(xi).Elem() |
| 5989 |
var out []int |
| 5990 |
for _, kv := range v.MapKeys() { |
| 5991 |
out = append(out, int(kv.Elem().Interface().(uintptr))) |
| 5992 |
} |
| 5993 |
sort.Ints(out) |
| 5994 |
for j, k := range out { |
| 5995 |
if k != i*n+j { |
| 5996 |
t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) |
| 5997 |
} |
| 5998 |
} |
| 5999 |
} |
| 6000 |
} |
| 6001 |
|
| 6002 |
func TestMapOfGCValues(t *testing.T) { |
| 6003 |
type T *uintptr |
| 6004 |
tt := TypeOf(T(nil)) |
| 6005 |
mt := MapOf(TypeOf(1), tt) |
| 6006 |
|
| 6007 |
// NOTE: The garbage collector handles allocated maps specially, |
| 6008 |
// so we have to save pointers to maps in x; the pointer code will |
| 6009 |
// use the gc info in the newly constructed map type. |
| 6010 |
const n = 100 |
| 6011 |
var x []any |
| 6012 |
for i := 0; i < n; i++ { |
| 6013 |
v := MakeMap(mt) |
| 6014 |
for j := 0; j < n; j++ { |
| 6015 |
p := new(uintptr) |
| 6016 |
*p = uintptr(i*n + j) |
| 6017 |
v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt)) |
| 6018 |
} |
| 6019 |
pv := New(mt) |
| 6020 |
pv.Elem().Set(v) |
| 6021 |
x = append(x, pv.Interface()) |
| 6022 |
} |
| 6023 |
runtime.GC() |
| 6024 |
|
| 6025 |
for i, xi := range x { |
| 6026 |
v := ValueOf(xi).Elem() |
| 6027 |
for j := 0; j < n; j++ { |
| 6028 |
k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr) |
| 6029 |
if k != uintptr(i*n+j) { |
| 6030 |
t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) |
| 6031 |
} |
| 6032 |
} |
| 6033 |
} |
| 6034 |
} |
| 6035 |
|
| 6036 |
func TestTypelinksSorted(t *testing.T) { |
| 6037 |
var last string |
| 6038 |
for i, n := range TypeLinks() { |
| 6039 |
if n < last { |
| 6040 |
t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i) |
| 6041 |
} |
| 6042 |
last = n |
| 6043 |
} |
| 6044 |
} |
| 6045 |
|
| 6046 |
func TestFuncOf(t *testing.T) { |
| 6047 |
// check construction and use of type not in binary |
| 6048 |
type K string |
| 6049 |
type V float64 |
| 6050 |
|
| 6051 |
fn := func(args []Value) []Value { |
| 6052 |
if len(args) != 1 { |
| 6053 |
t.Errorf("args == %v, want exactly one arg", args) |
| 6054 |
} else if args[0].Type() != TypeOf(K("")) { |
| 6055 |
t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K(""))) |
| 6056 |
} else if args[0].String() != "gopher" { |
| 6057 |
t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher") |
| 6058 |
} |
| 6059 |
return []Value{ValueOf(V(3.14))} |
| 6060 |
} |
| 6061 |
v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn) |
| 6062 |
|
| 6063 |
outs := v.Call([]Value{ValueOf(K("gopher"))}) |
| 6064 |
if len(outs) != 1 { |
| 6065 |
t.Fatalf("v.Call returned %v, want exactly one result", outs) |
| 6066 |
} else if outs[0].Type() != TypeOf(V(0)) { |
| 6067 |
t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0))) |
| 6068 |
} |
| 6069 |
f := outs[0].Float() |
| 6070 |
if f != 3.14 { |
| 6071 |
t.Errorf("constructed func returned %f, want %f", f, 3.14) |
| 6072 |
} |
| 6073 |
|
| 6074 |
// check that types already in binary are found |
| 6075 |
type T1 int |
| 6076 |
testCases := []struct { |
| 6077 |
in, out []Type |
| 6078 |
variadic bool |
| 6079 |
want any |
| 6080 |
}{ |
| 6081 |
{in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)}, |
| 6082 |
{in: []Type{TypeOf(int(0))}, want: (func(int))(nil)}, |
| 6083 |
{in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)}, |
| 6084 |
{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)}, |
| 6085 |
{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)}, |
| 6086 |
} |
| 6087 |
for _, tt := range testCases { |
| 6088 |
checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want) |
| 6089 |
} |
| 6090 |
|
| 6091 |
// check that variadic requires last element be a slice. |
| 6092 |
FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true) |
| 6093 |
shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) }) |
| 6094 |
shouldPanic("must be slice", func() { FuncOf(nil, nil, true) }) |
| 6095 |
} |
| 6096 |
|
| 6097 |
type B1 struct { |
| 6098 |
X int |
| 6099 |
Y int |
| 6100 |
Z int |
| 6101 |
} |
| 6102 |
|
| 6103 |
func BenchmarkFieldByName1(b *testing.B) { |
| 6104 |
t := TypeOf(B1{}) |
| 6105 |
b.RunParallel(func(pb *testing.PB) { |
| 6106 |
for pb.Next() { |
| 6107 |
t.FieldByName("Z") |
| 6108 |
} |
| 6109 |
}) |
| 6110 |
} |
| 6111 |
|
| 6112 |
func BenchmarkFieldByName2(b *testing.B) { |
| 6113 |
t := TypeOf(S3{}) |
| 6114 |
b.RunParallel(func(pb *testing.PB) { |
| 6115 |
for pb.Next() { |
| 6116 |
t.FieldByName("B") |
| 6117 |
} |
| 6118 |
}) |
| 6119 |
} |
| 6120 |
|
| 6121 |
type R0 struct { |
| 6122 |
*R1 |
| 6123 |
*R2 |
| 6124 |
*R3 |
| 6125 |
*R4 |
| 6126 |
} |
| 6127 |
|
| 6128 |
type R1 struct { |
| 6129 |
*R5 |
| 6130 |
*R6 |
| 6131 |
*R7 |
| 6132 |
*R8 |
| 6133 |
} |
| 6134 |
|
| 6135 |
type R2 R1 |
| 6136 |
type R3 R1 |
| 6137 |
type R4 R1 |
| 6138 |
|
| 6139 |
type R5 struct { |
| 6140 |
*R9 |
| 6141 |
*R10 |
| 6142 |
*R11 |
| 6143 |
*R12 |
| 6144 |
} |
| 6145 |
|
| 6146 |
type R6 R5 |
| 6147 |
type R7 R5 |
| 6148 |
type R8 R5 |
| 6149 |
|
| 6150 |
type R9 struct { |
| 6151 |
*R13 |
| 6152 |
*R14 |
| 6153 |
*R15 |
| 6154 |
*R16 |
| 6155 |
} |
| 6156 |
|
| 6157 |
type R10 R9 |
| 6158 |
type R11 R9 |
| 6159 |
type R12 R9 |
| 6160 |
|
| 6161 |
type R13 struct { |
| 6162 |
*R17 |
| 6163 |
*R18 |
| 6164 |
*R19 |
| 6165 |
*R20 |
| 6166 |
} |
| 6167 |
|
| 6168 |
type R14 R13 |
| 6169 |
type R15 R13 |
| 6170 |
type R16 R13 |
| 6171 |
|
| 6172 |
type R17 struct { |
| 6173 |
*R21 |
| 6174 |
*R22 |
| 6175 |
*R23 |
| 6176 |
*R24 |
| 6177 |
} |
| 6178 |
|
| 6179 |
type R18 R17 |
| 6180 |
type R19 R17 |
| 6181 |
type R20 R17 |
| 6182 |
|
| 6183 |
type R21 struct { |
| 6184 |
X int |
| 6185 |
} |
| 6186 |
|
| 6187 |
type R22 R21 |
| 6188 |
type R23 R21 |
| 6189 |
type R24 R21 |
| 6190 |
|
| 6191 |
func TestEmbed(t *testing.T) { |
| 6192 |
typ := TypeOf(R0{}) |
| 6193 |
f, ok := typ.FieldByName("X") |
| 6194 |
if ok { |
| 6195 |
t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index) |
| 6196 |
} |
| 6197 |
} |
| 6198 |
|
| 6199 |
func BenchmarkFieldByName3(b *testing.B) { |
| 6200 |
t := TypeOf(R0{}) |
| 6201 |
b.RunParallel(func(pb *testing.PB) { |
| 6202 |
for pb.Next() { |
| 6203 |
t.FieldByName("X") |
| 6204 |
} |
| 6205 |
}) |
| 6206 |
} |
| 6207 |
|
| 6208 |
type S struct { |
| 6209 |
i1 int64 |
| 6210 |
i2 int64 |
| 6211 |
} |
| 6212 |
|
| 6213 |
func BenchmarkInterfaceBig(b *testing.B) { |
| 6214 |
v := ValueOf(S{}) |
| 6215 |
b.RunParallel(func(pb *testing.PB) { |
| 6216 |
for pb.Next() { |
| 6217 |
v.Interface() |
| 6218 |
} |
| 6219 |
}) |
| 6220 |
b.StopTimer() |
| 6221 |
} |
| 6222 |
|
| 6223 |
func TestAllocsInterfaceBig(t *testing.T) { |
| 6224 |
if testing.Short() { |
| 6225 |
t.Skip("skipping malloc count in short mode") |
| 6226 |
} |
| 6227 |
v := ValueOf(S{}) |
| 6228 |
if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { |
| 6229 |
t.Error("allocs:", allocs) |
| 6230 |
} |
| 6231 |
} |
| 6232 |
|
| 6233 |
func BenchmarkInterfaceSmall(b *testing.B) { |
| 6234 |
v := ValueOf(int64(0)) |
| 6235 |
b.RunParallel(func(pb *testing.PB) { |
| 6236 |
for pb.Next() { |
| 6237 |
v.Interface() |
| 6238 |
} |
| 6239 |
}) |
| 6240 |
} |
| 6241 |
|
| 6242 |
func TestAllocsInterfaceSmall(t *testing.T) { |
| 6243 |
if testing.Short() { |
| 6244 |
t.Skip("skipping malloc count in short mode") |
| 6245 |
} |
| 6246 |
v := ValueOf(int64(0)) |
| 6247 |
if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { |
| 6248 |
t.Error("allocs:", allocs) |
| 6249 |
} |
| 6250 |
} |
| 6251 |
|
| 6252 |
// An exhaustive is a mechanism for writing exhaustive or stochastic tests. |
| 6253 |
// The basic usage is: |
| 6254 |
// |
| 6255 |
// for x.Next() { |
| 6256 |
// ... code using x.Maybe() or x.Choice(n) to create test cases ... |
| 6257 |
// } |
| 6258 |
// |
| 6259 |
// Each iteration of the loop returns a different set of results, until all |
| 6260 |
// possible result sets have been explored. It is okay for different code paths |
| 6261 |
// to make different method call sequences on x, but there must be no |
| 6262 |
// other source of non-determinism in the call sequences. |
| 6263 |
// |
| 6264 |
// When faced with a new decision, x chooses randomly. Future explorations |
| 6265 |
// of that path will choose successive values for the result. Thus, stopping |
| 6266 |
// the loop after a fixed number of iterations gives somewhat stochastic |
| 6267 |
// testing. |
| 6268 |
// |
| 6269 |
// Example: |
| 6270 |
// |
| 6271 |
// for x.Next() { |
| 6272 |
// v := make([]bool, x.Choose(4)) |
| 6273 |
// for i := range v { |
| 6274 |
// v[i] = x.Maybe() |
| 6275 |
// } |
| 6276 |
// fmt.Println(v) |
| 6277 |
// } |
| 6278 |
// |
| 6279 |
// prints (in some order): |
| 6280 |
// |
| 6281 |
// [] |
| 6282 |
// [false] |
| 6283 |
// [true] |
| 6284 |
// [false false] |
| 6285 |
// [false true] |
| 6286 |
// ... |
| 6287 |
// [true true] |
| 6288 |
// [false false false] |
| 6289 |
// ... |
| 6290 |
// [true true true] |
| 6291 |
// [false false false false] |
| 6292 |
// ... |
| 6293 |
// [true true true true] |
| 6294 |
// |
| 6295 |
type exhaustive struct { |
| 6296 |
r *rand.Rand |
| 6297 |
pos int |
| 6298 |
last []choice |
| 6299 |
} |
| 6300 |
|
| 6301 |
type choice struct { |
| 6302 |
off int |
| 6303 |
n int |
| 6304 |
max int |
| 6305 |
} |
| 6306 |
|
| 6307 |
func (x *exhaustive) Next() bool { |
| 6308 |
if x.r == nil { |
| 6309 |
x.r = rand.New(rand.NewSource(time.Now().UnixNano())) |
| 6310 |
} |
| 6311 |
x.pos = 0 |
| 6312 |
if x.last == nil { |
| 6313 |
x.last = []choice{} |
| 6314 |
return true |
| 6315 |
} |
| 6316 |
for i := len(x.last) - 1; i >= 0; i-- { |
| 6317 |
c := &x.last[i] |
| 6318 |
if c.n+1 < c.max { |
| 6319 |
c.n++ |
| 6320 |
x.last = x.last[:i+1] |
| 6321 |
return true |
| 6322 |
} |
| 6323 |
} |
| 6324 |
return false |
| 6325 |
} |
| 6326 |
|
| 6327 |
func (x *exhaustive) Choose(max int) int { |
| 6328 |
if x.pos >= len(x.last) { |
| 6329 |
x.last = append(x.last, choice{x.r.Intn(max), 0, max}) |
| 6330 |
} |
| 6331 |
c := &x.last[x.pos] |
| 6332 |
x.pos++ |
| 6333 |
if c.max != max { |
| 6334 |
panic("inconsistent use of exhaustive tester") |
| 6335 |
} |
| 6336 |
return (c.n + c.off) % max |
| 6337 |
} |
| 6338 |
|
| 6339 |
func (x *exhaustive) Maybe() bool { |
| 6340 |
return x.Choose(2) == 1 |
| 6341 |
} |
| 6342 |
|
| 6343 |
func GCFunc(args []Value) []Value { |
| 6344 |
runtime.GC() |
| 6345 |
return []Value{} |
| 6346 |
} |
| 6347 |
|
| 6348 |
func TestReflectFuncTraceback(t *testing.T) { |
| 6349 |
f := MakeFunc(TypeOf(func() {}), GCFunc) |
| 6350 |
f.Call([]Value{}) |
| 6351 |
} |
| 6352 |
|
| 6353 |
func TestReflectMethodTraceback(t *testing.T) { |
| 6354 |
p := Point{3, 4} |
| 6355 |
m := ValueOf(p).MethodByName("GCMethod") |
| 6356 |
i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int() |
| 6357 |
if i != 8 { |
| 6358 |
t.Errorf("Call returned %d; want 8", i) |
| 6359 |
} |
| 6360 |
} |
| 6361 |
|
| 6362 |
func TestSmallZero(t *testing.T) { |
| 6363 |
type T [10]byte |
| 6364 |
typ := TypeOf(T{}) |
| 6365 |
if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 { |
| 6366 |
t.Errorf("Creating small zero values caused %f allocs, want 0", allocs) |
| 6367 |
} |
| 6368 |
} |
| 6369 |
|
| 6370 |
func TestBigZero(t *testing.T) { |
| 6371 |
const size = 1 << 10 |
| 6372 |
var v [size]byte |
| 6373 |
z := Zero(ValueOf(v).Type()).Interface().([size]byte) |
| 6374 |
for i := 0; i < size; i++ { |
| 6375 |
if z[i] != 0 { |
| 6376 |
t.Fatalf("Zero object not all zero, index %d", i) |
| 6377 |
} |
| 6378 |
} |
| 6379 |
} |
| 6380 |
|
| 6381 |
func TestZeroSet(t *testing.T) { |
| 6382 |
type T [16]byte |
| 6383 |
type S struct { |
| 6384 |
a uint64 |
| 6385 |
T T |
| 6386 |
b uint64 |
| 6387 |
} |
| 6388 |
v := S{ |
| 6389 |
a: 0xaaaaaaaaaaaaaaaa, |
| 6390 |
T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, |
| 6391 |
b: 0xbbbbbbbbbbbbbbbb, |
| 6392 |
} |
| 6393 |
ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{}))) |
| 6394 |
if v != (S{ |
| 6395 |
a: 0xaaaaaaaaaaaaaaaa, |
| 6396 |
b: 0xbbbbbbbbbbbbbbbb, |
| 6397 |
}) { |
| 6398 |
t.Fatalf("Setting a field to a Zero value didn't work") |
| 6399 |
} |
| 6400 |
} |
| 6401 |
|
| 6402 |
func TestFieldByIndexNil(t *testing.T) { |
| 6403 |
type P struct { |
| 6404 |
F int |
| 6405 |
} |
| 6406 |
type T struct { |
| 6407 |
*P |
| 6408 |
} |
| 6409 |
v := ValueOf(T{}) |
| 6410 |
|
| 6411 |
v.FieldByName("P") // should be fine |
| 6412 |
|
| 6413 |
defer func() { |
| 6414 |
if err := recover(); err == nil { |
| 6415 |
t.Fatalf("no error") |
| 6416 |
} else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") { |
| 6417 |
t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err) |
| 6418 |
} |
| 6419 |
}() |
| 6420 |
v.FieldByName("F") // should panic |
| 6421 |
|
| 6422 |
t.Fatalf("did not panic") |
| 6423 |
} |
| 6424 |
|
| 6425 |
// Given |
| 6426 |
// type Outer struct { |
| 6427 |
// *Inner |
| 6428 |
// ... |
| 6429 |
// } |
| 6430 |
// the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner. |
| 6431 |
// The implementation is logically: |
| 6432 |
// func (p *Outer) M() { |
| 6433 |
// (p.Inner).M() |
| 6434 |
// } |
| 6435 |
// but since the only change here is the replacement of one pointer receiver with another, |
| 6436 |
// the actual generated code overwrites the original receiver with the p.Inner pointer and |
| 6437 |
// then jumps to the M method expecting the *Inner receiver. |
| 6438 |
// |
| 6439 |
// During reflect.Value.Call, we create an argument frame and the associated data structures |
| 6440 |
// to describe it to the garbage collector, populate the frame, call reflect.call to |
| 6441 |
// run a function call using that frame, and then copy the results back out of the frame. |
| 6442 |
// The reflect.call function does a memmove of the frame structure onto the |
| 6443 |
// stack (to set up the inputs), runs the call, and the memmoves the stack back to |
| 6444 |
// the frame structure (to preserve the outputs). |
| 6445 |
// |
| 6446 |
// Originally reflect.call did not distinguish inputs from outputs: both memmoves |
| 6447 |
// were for the full stack frame. However, in the case where the called function was |
| 6448 |
// one of these wrappers, the rewritten receiver is almost certainly a different type |
| 6449 |
// than the original receiver. This is not a problem on the stack, where we use the |
| 6450 |
// program counter to determine the type information and understand that |
| 6451 |
// during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same |
| 6452 |
// memory word is now an *Inner. But in the statically typed argument frame created |
| 6453 |
// by reflect, the receiver is always an *Outer. Copying the modified receiver pointer |
| 6454 |
// off the stack into the frame will store an *Inner there, and then if a garbage collection |
| 6455 |
// happens to scan that argument frame before it is discarded, it will scan the *Inner |
| 6456 |
// memory as if it were an *Outer. If the two have different memory layouts, the |
| 6457 |
// collection will interpret the memory incorrectly. |
| 6458 |
// |
| 6459 |
// One such possible incorrect interpretation is to treat two arbitrary memory words |
| 6460 |
// (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting |
| 6461 |
// an interface requires dereferencing the itab word, the misinterpretation will try to |
| 6462 |
// deference Inner.P1, causing a crash during garbage collection. |
| 6463 |
// |
| 6464 |
// This came up in a real program in issue 7725. |
| 6465 |
|
| 6466 |
type Outer struct { |
| 6467 |
*Inner |
| 6468 |
R io.Reader |
| 6469 |
} |
| 6470 |
|
| 6471 |
type Inner struct { |
| 6472 |
X *Outer |
| 6473 |
P1 uintptr |
| 6474 |
P2 uintptr |
| 6475 |
} |
| 6476 |
|
| 6477 |
func (pi *Inner) M() { |
| 6478 |
// Clear references to pi so that the only way the |
| 6479 |
// garbage collection will find the pointer is in the |
| 6480 |
// argument frame, typed as a *Outer. |
| 6481 |
pi.X.Inner = nil |
| 6482 |
|
| 6483 |
// Set up an interface value that will cause a crash. |
| 6484 |
// P1 = 1 is a non-zero, so the interface looks non-nil. |
| 6485 |
// P2 = pi ensures that the data word points into the |
| 6486 |
// allocated heap; if not the collection skips the interface |
| 6487 |
// value as irrelevant, without dereferencing P1. |
| 6488 |
pi.P1 = 1 |
| 6489 |
pi.P2 = uintptr(unsafe.Pointer(pi)) |
| 6490 |
} |
| 6491 |
|
| 6492 |
func TestCallMethodJump(t *testing.T) { |
| 6493 |
// In reflect.Value.Call, trigger a garbage collection after reflect.call |
| 6494 |
// returns but before the args frame has been discarded. |
| 6495 |
// This is a little clumsy but makes the failure repeatable. |
| 6496 |
*CallGC = true |
| 6497 |
|
| 6498 |
p := &Outer{Inner: new(Inner)} |
| 6499 |
p.Inner.X = p |
| 6500 |
ValueOf(p).Method(0).Call(nil) |
| 6501 |
|
| 6502 |
// Stop garbage collecting during reflect.call. |
| 6503 |
*CallGC = false |
| 6504 |
} |
| 6505 |
|
| 6506 |
func TestCallArgLive(t *testing.T) { |
| 6507 |
type T struct{ X, Y *string } // pointerful aggregate |
| 6508 |
|
| 6509 |
F := func(t T) { *t.X = "ok" } |
| 6510 |
|
| 6511 |
// In reflect.Value.Call, trigger a garbage collection in reflect.call |
| 6512 |
// between marshaling argument and the actual call. |
| 6513 |
*CallGC = true |
| 6514 |
|
| 6515 |
x := new(string) |
| 6516 |
runtime.SetFinalizer(x, func(p *string) { |
| 6517 |
if *p != "ok" { |
| 6518 |
t.Errorf("x dead prematurely") |
| 6519 |
} |
| 6520 |
}) |
| 6521 |
v := T{x, nil} |
| 6522 |
|
| 6523 |
ValueOf(F).Call([]Value{ValueOf(v)}) |
| 6524 |
|
| 6525 |
// Stop garbage collecting during reflect.call. |
| 6526 |
*CallGC = false |
| 6527 |
} |
| 6528 |
|
| 6529 |
func TestMakeFuncStackCopy(t *testing.T) { |
| 6530 |
target := func(in []Value) []Value { |
| 6531 |
runtime.GC() |
| 6532 |
useStack(16) |
| 6533 |
return []Value{ValueOf(9)} |
| 6534 |
} |
| 6535 |
|
| 6536 |
var concrete func(*int, int) int |
| 6537 |
fn := MakeFunc(ValueOf(concrete).Type(), target) |
| 6538 |
ValueOf(&concrete).Elem().Set(fn) |
| 6539 |
x := concrete(nil, 7) |
| 6540 |
if x != 9 { |
| 6541 |
t.Errorf("have %#q want 9", x) |
| 6542 |
} |
| 6543 |
} |
| 6544 |
|
| 6545 |
// use about n KB of stack |
| 6546 |
func useStack(n int) { |
| 6547 |
if n == 0 { |
| 6548 |
return |
| 6549 |
} |
| 6550 |
var b [1024]byte // makes frame about 1KB |
| 6551 |
useStack(n - 1 + int(b[99])) |
| 6552 |
} |
| 6553 |
|
| 6554 |
type Impl struct{} |
| 6555 |
|
| 6556 |
func (Impl) F() {} |
| 6557 |
|
| 6558 |
func TestValueString(t *testing.T) { |
| 6559 |
rv := ValueOf(Impl{}) |
| 6560 |
if rv.String() != "<reflect_test.Impl Value>" { |
| 6561 |
t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>") |
| 6562 |
} |
| 6563 |
|
| 6564 |
method := rv.Method(0) |
| 6565 |
if method.String() != "<func() Value>" { |
| 6566 |
t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>") |
| 6567 |
} |
| 6568 |
} |
| 6569 |
|
| 6570 |
func TestInvalid(t *testing.T) { |
| 6571 |
// Used to have inconsistency between IsValid() and Kind() != Invalid. |
| 6572 |
type T struct{ v any } |
| 6573 |
|
| 6574 |
v := ValueOf(T{}).Field(0) |
| 6575 |
if v.IsValid() != true || v.Kind() != Interface { |
| 6576 |
t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind()) |
| 6577 |
} |
| 6578 |
v = v.Elem() |
| 6579 |
if v.IsValid() != false || v.Kind() != Invalid { |
| 6580 |
t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind()) |
| 6581 |
} |
| 6582 |
} |
| 6583 |
|
| 6584 |
// Issue 8917. |
| 6585 |
func TestLargeGCProg(t *testing.T) { |
| 6586 |
fv := ValueOf(func([256]*byte) {}) |
| 6587 |
fv.Call([]Value{ValueOf([256]*byte{})}) |
| 6588 |
} |
| 6589 |
|
| 6590 |
func fieldIndexRecover(t Type, i int) (recovered any) { |
| 6591 |
defer func() { |
| 6592 |
recovered = recover() |
| 6593 |
}() |
| 6594 |
|
| 6595 |
t.Field(i) |
| 6596 |
return |
| 6597 |
} |
| 6598 |
|
| 6599 |
// Issue 15046. |
| 6600 |
func TestTypeFieldOutOfRangePanic(t *testing.T) { |
| 6601 |
typ := TypeOf(struct{ X int }{10}) |
| 6602 |
testIndices := [...]struct { |
| 6603 |
i int |
| 6604 |
mustPanic bool |
| 6605 |
}{ |
| 6606 |
0: {-2, true}, |
| 6607 |
1: {0, false}, |
| 6608 |
2: {1, true}, |
| 6609 |
3: {1 << 10, true}, |
| 6610 |
} |
| 6611 |
for i, tt := range testIndices { |
| 6612 |
recoveredErr := fieldIndexRecover(typ, tt.i) |
| 6613 |
if tt.mustPanic { |
| 6614 |
if recoveredErr == nil { |
| 6615 |
t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i) |
| 6616 |
} |
| 6617 |
} else { |
| 6618 |
if recoveredErr != nil { |
| 6619 |
t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr) |
| 6620 |
} |
| 6621 |
} |
| 6622 |
} |
| 6623 |
} |
| 6624 |
|
| 6625 |
// Issue 9179. |
| 6626 |
func TestCallGC(t *testing.T) { |
| 6627 |
f := func(a, b, c, d, e string) { |
| 6628 |
} |
| 6629 |
g := func(in []Value) []Value { |
| 6630 |
runtime.GC() |
| 6631 |
return nil |
| 6632 |
} |
| 6633 |
typ := ValueOf(f).Type() |
| 6634 |
f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string)) |
| 6635 |
f2("four", "five5", "six666", "seven77", "eight888") |
| 6636 |
} |
| 6637 |
|
| 6638 |
// Issue 18635 (function version). |
| 6639 |
func TestKeepFuncLive(t *testing.T) { |
| 6640 |
// Test that we keep makeFuncImpl live as long as it is |
| 6641 |
// referenced on the stack. |
| 6642 |
typ := TypeOf(func(i int) {}) |
| 6643 |
var f, g func(in []Value) []Value |
| 6644 |
f = func(in []Value) []Value { |
| 6645 |
clobber() |
| 6646 |
i := int(in[0].Int()) |
| 6647 |
if i > 0 { |
| 6648 |
// We can't use Value.Call here because |
| 6649 |
// runtime.call* will keep the makeFuncImpl |
| 6650 |
// alive. However, by converting it to an |
| 6651 |
// interface value and calling that, |
| 6652 |
// reflect.callReflect is the only thing that |
| 6653 |
// can keep the makeFuncImpl live. |
| 6654 |
// |
| 6655 |
// Alternate between f and g so that if we do |
| 6656 |
// reuse the memory prematurely it's more |
| 6657 |
// likely to get obviously corrupted. |
| 6658 |
MakeFunc(typ, g).Interface().(func(i int))(i - 1) |
| 6659 |
} |
| 6660 |
return nil |
| 6661 |
} |
| 6662 |
g = func(in []Value) []Value { |
| 6663 |
clobber() |
| 6664 |
i := int(in[0].Int()) |
| 6665 |
MakeFunc(typ, f).Interface().(func(i int))(i) |
| 6666 |
return nil |
| 6667 |
} |
| 6668 |
MakeFunc(typ, f).Call([]Value{ValueOf(10)}) |
| 6669 |
} |
| 6670 |
|
| 6671 |
type UnExportedFirst int |
| 6672 |
|
| 6673 |
func (i UnExportedFirst) ΦExported() {} |
| 6674 |
func (i UnExportedFirst) unexported() {} |
| 6675 |
|
| 6676 |
// Issue 21177 |
| 6677 |
func TestMethodByNameUnExportedFirst(t *testing.T) { |
| 6678 |
defer func() { |
| 6679 |
if recover() != nil { |
| 6680 |
t.Errorf("should not panic") |
| 6681 |
} |
| 6682 |
}() |
| 6683 |
typ := TypeOf(UnExportedFirst(0)) |
| 6684 |
m, _ := typ.MethodByName("ΦExported") |
| 6685 |
if m.Name != "ΦExported" { |
| 6686 |
t.Errorf("got %s, expected ΦExported", m.Name) |
| 6687 |
} |
| 6688 |
} |
| 6689 |
|
| 6690 |
// Issue 18635 (method version). |
| 6691 |
type KeepMethodLive struct{} |
| 6692 |
|
| 6693 |
func (k KeepMethodLive) Method1(i int) { |
| 6694 |
clobber() |
| 6695 |
if i > 0 { |
| 6696 |
ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1) |
| 6697 |
} |
| 6698 |
} |
| 6699 |
|
| 6700 |
func (k KeepMethodLive) Method2(i int) { |
| 6701 |
clobber() |
| 6702 |
ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i) |
| 6703 |
} |
| 6704 |
|
| 6705 |
func TestKeepMethodLive(t *testing.T) { |
| 6706 |
// Test that we keep methodValue live as long as it is |
| 6707 |
// referenced on the stack. |
| 6708 |
KeepMethodLive{}.Method1(10) |
| 6709 |
} |
| 6710 |
|
| 6711 |
// clobber tries to clobber unreachable memory. |
| 6712 |
func clobber() { |
| 6713 |
runtime.GC() |
| 6714 |
for i := 1; i < 32; i++ { |
| 6715 |
for j := 0; j < 10; j++ { |
| 6716 |
obj := make([]*byte, i) |
| 6717 |
sink = obj |
| 6718 |
} |
| 6719 |
} |
| 6720 |
runtime.GC() |
| 6721 |
} |
| 6722 |
|
| 6723 |
/* |
| 6724 |
|
| 6725 |
func TestFuncLayout(t *testing.T) { |
| 6726 |
align := func(x uintptr) uintptr { |
| 6727 |
return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1) |
| 6728 |
} |
| 6729 |
var r []byte |
| 6730 |
if goarch.PtrSize == 4 { |
| 6731 |
r = []byte{0, 0, 0, 1} |
| 6732 |
} else { |
| 6733 |
r = []byte{0, 0, 1} |
| 6734 |
} |
| 6735 |
|
| 6736 |
type S struct { |
| 6737 |
a, b uintptr |
| 6738 |
c, d *byte |
| 6739 |
} |
| 6740 |
|
| 6741 |
type test struct { |
| 6742 |
rcvr, typ Type |
| 6743 |
size, argsize, retOffset uintptr |
| 6744 |
stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar |
| 6745 |
intRegs, floatRegs int |
| 6746 |
floatRegSize uintptr |
| 6747 |
} |
| 6748 |
tests := []test{ |
| 6749 |
{ |
| 6750 |
typ: ValueOf(func(a, b string) string { return "" }).Type(), |
| 6751 |
size: 6 * goarch.PtrSize, |
| 6752 |
argsize: 4 * goarch.PtrSize, |
| 6753 |
retOffset: 4 * goarch.PtrSize, |
| 6754 |
stack: []byte{1, 0, 1, 0, 1}, |
| 6755 |
gc: []byte{1, 0, 1, 0, 1}, |
| 6756 |
}, |
| 6757 |
{ |
| 6758 |
typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(), |
| 6759 |
size: align(align(3*4) + goarch.PtrSize + 2), |
| 6760 |
argsize: align(3*4) + goarch.PtrSize + 2, |
| 6761 |
retOffset: align(align(3*4) + goarch.PtrSize + 2), |
| 6762 |
stack: r, |
| 6763 |
gc: r, |
| 6764 |
}, |
| 6765 |
{ |
| 6766 |
typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(), |
| 6767 |
size: 4 * goarch.PtrSize, |
| 6768 |
argsize: 4 * goarch.PtrSize, |
| 6769 |
retOffset: 4 * goarch.PtrSize, |
| 6770 |
stack: []byte{1, 0, 1, 1}, |
| 6771 |
gc: []byte{1, 0, 1, 1}, |
| 6772 |
}, |
| 6773 |
{ |
| 6774 |
typ: ValueOf(func(a S) {}).Type(), |
| 6775 |
size: 4 * goarch.PtrSize, |
| 6776 |
argsize: 4 * goarch.PtrSize, |
| 6777 |
retOffset: 4 * goarch.PtrSize, |
| 6778 |
stack: []byte{0, 0, 1, 1}, |
| 6779 |
gc: []byte{0, 0, 1, 1}, |
| 6780 |
}, |
| 6781 |
{ |
| 6782 |
rcvr: ValueOf((*byte)(nil)).Type(), |
| 6783 |
typ: ValueOf(func(a uintptr, b *int) {}).Type(), |
| 6784 |
size: 3 * goarch.PtrSize, |
| 6785 |
argsize: 3 * goarch.PtrSize, |
| 6786 |
retOffset: 3 * goarch.PtrSize, |
| 6787 |
stack: []byte{1, 0, 1}, |
| 6788 |
gc: []byte{1, 0, 1}, |
| 6789 |
}, |
| 6790 |
{ |
| 6791 |
typ: ValueOf(func(a uintptr) {}).Type(), |
| 6792 |
size: goarch.PtrSize, |
| 6793 |
argsize: goarch.PtrSize, |
| 6794 |
retOffset: goarch.PtrSize, |
| 6795 |
stack: []byte{}, |
| 6796 |
gc: []byte{}, |
| 6797 |
}, |
| 6798 |
{ |
| 6799 |
typ: ValueOf(func() uintptr { return 0 }).Type(), |
| 6800 |
size: goarch.PtrSize, |
| 6801 |
argsize: 0, |
| 6802 |
retOffset: 0, |
| 6803 |
stack: []byte{}, |
| 6804 |
gc: []byte{}, |
| 6805 |
}, |
| 6806 |
{ |
| 6807 |
rcvr: ValueOf(uintptr(0)).Type(), |
| 6808 |
typ: ValueOf(func(a uintptr) {}).Type(), |
| 6809 |
size: 2 * goarch.PtrSize, |
| 6810 |
argsize: 2 * goarch.PtrSize, |
| 6811 |
retOffset: 2 * goarch.PtrSize, |
| 6812 |
stack: []byte{1}, |
| 6813 |
gc: []byte{1}, |
| 6814 |
// Note: this one is tricky, as the receiver is not a pointer. But we |
| 6815 |
// pass the receiver by reference to the autogenerated pointer-receiver |
| 6816 |
// version of the function. |
| 6817 |
}, |
| 6818 |
// TODO(mknyszek): Add tests for non-zero register count. |
| 6819 |
} |
| 6820 |
for _, lt := range tests { |
| 6821 |
name := lt.typ.String() |
| 6822 |
if lt.rcvr != nil { |
| 6823 |
name = lt.rcvr.String() + "." + name |
| 6824 |
} |
| 6825 |
t.Run(name, func(t *testing.T) { |
| 6826 |
defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize)) |
| 6827 |
|
| 6828 |
typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr) |
| 6829 |
if typ.Size() != lt.size { |
| 6830 |
t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size) |
| 6831 |
} |
| 6832 |
if argsize != lt.argsize { |
| 6833 |
t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize) |
| 6834 |
} |
| 6835 |
if retOffset != lt.retOffset { |
| 6836 |
t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset) |
| 6837 |
} |
| 6838 |
if !bytes.Equal(stack, lt.stack) { |
| 6839 |
t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack) |
| 6840 |
} |
| 6841 |
if !bytes.Equal(gc, lt.gc) { |
| 6842 |
t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc) |
| 6843 |
} |
| 6844 |
if !bytes.Equal(inRegs, lt.inRegs) { |
| 6845 |
t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs) |
| 6846 |
} |
| 6847 |
if !bytes.Equal(outRegs, lt.outRegs) { |
| 6848 |
t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs) |
| 6849 |
} |
| 6850 |
if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 { |
| 6851 |
t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs) |
| 6852 |
} |
| 6853 |
}) |
| 6854 |
} |
| 6855 |
} |
| 6856 |
|
| 6857 |
*/ |
| 6858 |
|
| 6859 |
func verifyGCBits(t *testing.T, typ Type, bits []byte) { |
| 6860 |
heapBits := GCBits(New(typ).Interface()) |
| 6861 |
if !bytes.Equal(heapBits, bits) { |
| 6862 |
_, _, line, _ := runtime.Caller(1) |
| 6863 |
t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits) |
| 6864 |
} |
| 6865 |
} |
| 6866 |
|
| 6867 |
func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) { |
| 6868 |
// Creating a slice causes the runtime to repeat a bitmap, |
| 6869 |
// which exercises a different path from making the compiler |
| 6870 |
// repeat a bitmap for a small array or executing a repeat in |
| 6871 |
// a GC program. |
| 6872 |
val := MakeSlice(typ, 0, cap) |
| 6873 |
data := NewAt(ArrayOf(cap, typ), val.UnsafePointer()) |
| 6874 |
heapBits := GCBits(data.Interface()) |
| 6875 |
// Repeat the bitmap for the slice size, trimming scalars in |
| 6876 |
// the last element. |
| 6877 |
bits = rep(cap, bits) |
| 6878 |
for len(bits) > 0 && bits[len(bits)-1] == 0 { |
| 6879 |
bits = bits[:len(bits)-1] |
| 6880 |
} |
| 6881 |
if !bytes.Equal(heapBits, bits) { |
| 6882 |
t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits) |
| 6883 |
} |
| 6884 |
} |
| 6885 |
|
| 6886 |
func TestGCBits(t *testing.T) { |
| 6887 |
t.Skip("gccgo does not use gcbits yet") |
| 6888 |
|
| 6889 |
verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1}) |
| 6890 |
|
| 6891 |
// Building blocks for types seen by the compiler (like [2]Xscalar). |
| 6892 |
// The compiler will create the type structures for the derived types, |
| 6893 |
// including their GC metadata. |
| 6894 |
type Xscalar struct{ x uintptr } |
| 6895 |
type Xptr struct{ x *byte } |
| 6896 |
type Xptrscalar struct { |
| 6897 |
*byte |
| 6898 |
uintptr |
| 6899 |
} |
| 6900 |
type Xscalarptr struct { |
| 6901 |
uintptr |
| 6902 |
*byte |
| 6903 |
} |
| 6904 |
type Xbigptrscalar struct { |
| 6905 |
_ [100]*byte |
| 6906 |
_ [100]uintptr |
| 6907 |
} |
| 6908 |
|
| 6909 |
var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type |
| 6910 |
{ |
| 6911 |
// Building blocks for types constructed by reflect. |
| 6912 |
// This code is in a separate block so that code below |
| 6913 |
// cannot accidentally refer to these. |
| 6914 |
// The compiler must NOT see types derived from these |
| 6915 |
// (for example, [2]Scalar must NOT appear in the program), |
| 6916 |
// or else reflect will use it instead of having to construct one. |
| 6917 |
// The goal is to test the construction. |
| 6918 |
type Scalar struct{ x uintptr } |
| 6919 |
type Ptr struct{ x *byte } |
| 6920 |
type Ptrscalar struct { |
| 6921 |
*byte |
| 6922 |
uintptr |
| 6923 |
} |
| 6924 |
type Scalarptr struct { |
| 6925 |
uintptr |
| 6926 |
*byte |
| 6927 |
} |
| 6928 |
type Bigptrscalar struct { |
| 6929 |
_ [100]*byte |
| 6930 |
_ [100]uintptr |
| 6931 |
} |
| 6932 |
type Int64 int64 |
| 6933 |
Tscalar = TypeOf(Scalar{}) |
| 6934 |
Tint64 = TypeOf(Int64(0)) |
| 6935 |
Tptr = TypeOf(Ptr{}) |
| 6936 |
Tscalarptr = TypeOf(Scalarptr{}) |
| 6937 |
Tptrscalar = TypeOf(Ptrscalar{}) |
| 6938 |
Tbigptrscalar = TypeOf(Bigptrscalar{}) |
| 6939 |
} |
| 6940 |
|
| 6941 |
empty := []byte{} |
| 6942 |
|
| 6943 |
verifyGCBits(t, TypeOf(Xscalar{}), empty) |
| 6944 |
verifyGCBits(t, Tscalar, empty) |
| 6945 |
verifyGCBits(t, TypeOf(Xptr{}), lit(1)) |
| 6946 |
verifyGCBits(t, Tptr, lit(1)) |
| 6947 |
verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1)) |
| 6948 |
verifyGCBits(t, Tscalarptr, lit(0, 1)) |
| 6949 |
verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1)) |
| 6950 |
verifyGCBits(t, Tptrscalar, lit(1)) |
| 6951 |
|
| 6952 |
verifyGCBits(t, TypeOf([0]Xptr{}), empty) |
| 6953 |
verifyGCBits(t, ArrayOf(0, Tptr), empty) |
| 6954 |
verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1)) |
| 6955 |
verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1)) |
| 6956 |
verifyGCBits(t, TypeOf([2]Xscalar{}), empty) |
| 6957 |
verifyGCBits(t, ArrayOf(2, Tscalar), empty) |
| 6958 |
verifyGCBits(t, TypeOf([10000]Xscalar{}), empty) |
| 6959 |
verifyGCBits(t, ArrayOf(10000, Tscalar), empty) |
| 6960 |
verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1)) |
| 6961 |
verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1)) |
| 6962 |
verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1))) |
| 6963 |
verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1))) |
| 6964 |
verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1)) |
| 6965 |
verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1)) |
| 6966 |
verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1))) |
| 6967 |
verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1))) |
| 6968 |
verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1)) |
| 6969 |
verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1)) |
| 6970 |
verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0))) |
| 6971 |
verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0))) |
| 6972 |
verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0))) |
| 6973 |
verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0))) |
| 6974 |
verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0))) |
| 6975 |
verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0))) |
| 6976 |
verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) |
| 6977 |
verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) |
| 6978 |
|
| 6979 |
verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty) |
| 6980 |
verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty) |
| 6981 |
verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1)) |
| 6982 |
verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1)) |
| 6983 |
verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0)) |
| 6984 |
verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0)) |
| 6985 |
verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0)) |
| 6986 |
verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0)) |
| 6987 |
verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1)) |
| 6988 |
verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1)) |
| 6989 |
verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1)) |
| 6990 |
verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1)) |
| 6991 |
verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1)) |
| 6992 |
verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1)) |
| 6993 |
verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1)) |
| 6994 |
verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1)) |
| 6995 |
verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0)) |
| 6996 |
verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0)) |
| 6997 |
verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0)) |
| 6998 |
verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0)) |
| 6999 |
verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0))) |
| 7000 |
verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0))) |
| 7001 |
verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0))) |
| 7002 |
verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0))) |
| 7003 |
verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0)))) |
| 7004 |
verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0)))) |
| 7005 |
|
| 7006 |
verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1)) |
| 7007 |
verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1)) |
| 7008 |
|
| 7009 |
verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1)) |
| 7010 |
verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1)) |
| 7011 |
|
| 7012 |
verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1)) |
| 7013 |
verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1)) |
| 7014 |
|
| 7015 |
verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1)) |
| 7016 |
verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1)) |
| 7017 |
|
| 7018 |
verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1)) |
| 7019 |
verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1)) |
| 7020 |
|
| 7021 |
hdr := make([]byte, 8/goarch.PtrSize) |
| 7022 |
|
| 7023 |
verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) { |
| 7024 |
verifyGCBits(t, MapBucketOf(k, e), want) |
| 7025 |
verifyGCBits(t, CachedBucketOf(TypeOf(m)), want) |
| 7026 |
} |
| 7027 |
verifyMapBucket(t, |
| 7028 |
Tscalar, Tptr, |
| 7029 |
map[Xscalar]Xptr(nil), |
| 7030 |
join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1))) |
| 7031 |
verifyMapBucket(t, |
| 7032 |
Tscalarptr, Tptr, |
| 7033 |
map[Xscalarptr]Xptr(nil), |
| 7034 |
join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1))) |
| 7035 |
verifyMapBucket(t, Tint64, Tptr, |
| 7036 |
map[int64]Xptr(nil), |
| 7037 |
join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1))) |
| 7038 |
verifyMapBucket(t, |
| 7039 |
Tscalar, Tscalar, |
| 7040 |
map[Xscalar]Xscalar(nil), |
| 7041 |
empty) |
| 7042 |
verifyMapBucket(t, |
| 7043 |
ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar), |
| 7044 |
map[[2]Xscalarptr][3]Xptrscalar(nil), |
| 7045 |
join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1))) |
| 7046 |
verifyMapBucket(t, |
| 7047 |
ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar), |
| 7048 |
map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil), |
| 7049 |
join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1))) |
| 7050 |
verifyMapBucket(t, |
| 7051 |
ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar), |
| 7052 |
map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil), |
| 7053 |
join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1))) |
| 7054 |
verifyMapBucket(t, |
| 7055 |
ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar), |
| 7056 |
map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil), |
| 7057 |
join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1))) |
| 7058 |
verifyMapBucket(t, |
| 7059 |
ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar), |
| 7060 |
map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil), |
| 7061 |
join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1))) |
| 7062 |
} |
| 7063 |
|
| 7064 |
func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) } |
| 7065 |
func join(b ...[]byte) []byte { return bytes.Join(b, nil) } |
| 7066 |
func lit(x ...byte) []byte { return x } |
| 7067 |
|
| 7068 |
func TestTypeOfTypeOf(t *testing.T) { |
| 7069 |
// Check that all the type constructors return concrete *rtype implementations. |
| 7070 |
// It's difficult to test directly because the reflect package is only at arm's length. |
| 7071 |
// The easiest thing to do is just call a function that crashes if it doesn't get an *rtype. |
| 7072 |
check := func(name string, typ Type) { |
| 7073 |
if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" { |
| 7074 |
t.Errorf("%v returned %v, not *reflect.rtype", name, underlying) |
| 7075 |
} |
| 7076 |
} |
| 7077 |
|
| 7078 |
type T struct{ int } |
| 7079 |
check("TypeOf", TypeOf(T{})) |
| 7080 |
|
| 7081 |
check("ArrayOf", ArrayOf(10, TypeOf(T{}))) |
| 7082 |
check("ChanOf", ChanOf(BothDir, TypeOf(T{}))) |
| 7083 |
check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false)) |
| 7084 |
check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{}))) |
| 7085 |
check("PtrTo", PointerTo(TypeOf(T{}))) |
| 7086 |
check("SliceOf", SliceOf(TypeOf(T{}))) |
| 7087 |
} |
| 7088 |
|
| 7089 |
type XM struct{ _ bool } |
| 7090 |
|
| 7091 |
func (*XM) String() string { return "" } |
| 7092 |
|
| 7093 |
func TestPtrToMethods(t *testing.T) { |
| 7094 |
var y struct{ XM } |
| 7095 |
yp := New(TypeOf(y)).Interface() |
| 7096 |
_, ok := yp.(fmt.Stringer) |
| 7097 |
if !ok { |
| 7098 |
t.Fatal("does not implement Stringer, but should") |
| 7099 |
} |
| 7100 |
} |
| 7101 |
|
| 7102 |
func TestMapAlloc(t *testing.T) { |
| 7103 |
m := ValueOf(make(map[int]int, 10)) |
| 7104 |
k := ValueOf(5) |
| 7105 |
v := ValueOf(7) |
| 7106 |
allocs := testing.AllocsPerRun(100, func() { |
| 7107 |
m.SetMapIndex(k, v) |
| 7108 |
}) |
| 7109 |
if allocs > 0.5 { |
| 7110 |
t.Errorf("allocs per map assignment: want 0 got %f", allocs) |
| 7111 |
} |
| 7112 |
|
| 7113 |
const size = 1000 |
| 7114 |
tmp := 0 |
| 7115 |
val := ValueOf(&tmp).Elem() |
| 7116 |
allocs = testing.AllocsPerRun(100, func() { |
| 7117 |
mv := MakeMapWithSize(TypeOf(map[int]int{}), size) |
| 7118 |
// Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets. |
| 7119 |
for i := 0; i < size/2; i++ { |
| 7120 |
val.SetInt(int64(i)) |
| 7121 |
mv.SetMapIndex(val, val) |
| 7122 |
} |
| 7123 |
}) |
| 7124 |
if allocs > 10 { |
| 7125 |
t.Errorf("allocs per map assignment: want at most 10 got %f", allocs) |
| 7126 |
} |
| 7127 |
// Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set |
| 7128 |
// the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the |
| 7129 |
// map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added. |
| 7130 |
} |
| 7131 |
|
| 7132 |
func TestChanAlloc(t *testing.T) { |
| 7133 |
// Note: for a chan int, the return Value must be allocated, so we |
| 7134 |
// use a chan *int instead. |
| 7135 |
c := ValueOf(make(chan *int, 1)) |
| 7136 |
v := ValueOf(new(int)) |
| 7137 |
allocs := testing.AllocsPerRun(100, func() { |
| 7138 |
c.Send(v) |
| 7139 |
_, _ = c.Recv() |
| 7140 |
}) |
| 7141 |
if allocs < 0.5 || allocs > 1.5 { |
| 7142 |
t.Errorf("allocs per chan send/recv: want 1 got %f", allocs) |
| 7143 |
} |
| 7144 |
// Note: there is one allocation in reflect.recv which seems to be |
| 7145 |
// a limitation of escape analysis. If that is ever fixed the |
| 7146 |
// allocs < 0.5 condition will trigger and this test should be fixed. |
| 7147 |
} |
| 7148 |
|
| 7149 |
type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int |
| 7150 |
|
| 7151 |
type nameTest struct { |
| 7152 |
v any |
| 7153 |
want string |
| 7154 |
} |
| 7155 |
|
| 7156 |
var nameTests = []nameTest{ |
| 7157 |
{(*int32)(nil), "int32"}, |
| 7158 |
{(*D1)(nil), "D1"}, |
| 7159 |
{(*[]D1)(nil), ""}, |
| 7160 |
{(*chan D1)(nil), ""}, |
| 7161 |
{(*func() D1)(nil), ""}, |
| 7162 |
{(*<-chan D1)(nil), ""}, |
| 7163 |
{(*chan<- D1)(nil), ""}, |
| 7164 |
{(*any)(nil), ""}, |
| 7165 |
{(*interface { |
| 7166 |
F() |
| 7167 |
})(nil), ""}, |
| 7168 |
{(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"}, |
| 7169 |
} |
| 7170 |
|
| 7171 |
func TestNames(t *testing.T) { |
| 7172 |
for _, test := range nameTests { |
| 7173 |
typ := TypeOf(test.v).Elem() |
| 7174 |
if got := typ.Name(); got != test.want { |
| 7175 |
t.Errorf("%v Name()=%q, want %q", typ, got, test.want) |
| 7176 |
} |
| 7177 |
} |
| 7178 |
} |
| 7179 |
|
| 7180 |
/* |
| 7181 |
gccgo doesn't really record whether a type is exported. |
| 7182 |
It's not in the reflect API anyhow. |
| 7183 |
|
| 7184 |
func TestExported(t *testing.T) { |
| 7185 |
type ΦExported struct{} |
| 7186 |
type φUnexported struct{} |
| 7187 |
type BigP *big |
| 7188 |
type P int |
| 7189 |
type p *P |
| 7190 |
type P2 p |
| 7191 |
type p3 p |
| 7192 |
|
| 7193 |
type exportTest struct { |
| 7194 |
v any |
| 7195 |
want bool |
| 7196 |
} |
| 7197 |
exportTests := []exportTest{ |
| 7198 |
{D1{}, true}, |
| 7199 |
{(*D1)(nil), true}, |
| 7200 |
{big{}, false}, |
| 7201 |
{(*big)(nil), false}, |
| 7202 |
{(BigP)(nil), true}, |
| 7203 |
{(*BigP)(nil), true}, |
| 7204 |
{ΦExported{}, true}, |
| 7205 |
{φUnexported{}, false}, |
| 7206 |
{P(0), true}, |
| 7207 |
{(p)(nil), false}, |
| 7208 |
{(P2)(nil), true}, |
| 7209 |
{(p3)(nil), false}, |
| 7210 |
} |
| 7211 |
|
| 7212 |
for i, test := range exportTests { |
| 7213 |
typ := TypeOf(test.v) |
| 7214 |
if got := IsExported(typ); got != test.want { |
| 7215 |
t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want) |
| 7216 |
} |
| 7217 |
} |
| 7218 |
} |
| 7219 |
*/ |
| 7220 |
|
| 7221 |
func TestTypeStrings(t *testing.T) { |
| 7222 |
type stringTest struct { |
| 7223 |
typ Type |
| 7224 |
want string |
| 7225 |
} |
| 7226 |
stringTests := []stringTest{ |
| 7227 |
{TypeOf(func(int) {}), "func(int)"}, |
| 7228 |
{FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"}, |
| 7229 |
{TypeOf(XM{}), "reflect_test.XM"}, |
| 7230 |
{TypeOf(new(XM)), "*reflect_test.XM"}, |
| 7231 |
{TypeOf(new(XM).String), "func() string"}, |
| 7232 |
{TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"}, |
| 7233 |
{ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"}, |
| 7234 |
{MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"}, |
| 7235 |
{ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"}, |
| 7236 |
{ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"}, |
| 7237 |
} |
| 7238 |
|
| 7239 |
for i, test := range stringTests { |
| 7240 |
if got, want := test.typ.String(), test.want; got != want { |
| 7241 |
t.Errorf("type %d String()=%q, want %q", i, got, want) |
| 7242 |
} |
| 7243 |
} |
| 7244 |
} |
| 7245 |
|
| 7246 |
/* |
| 7247 |
gccgo does not have resolveReflectName. |
| 7248 |
|
| 7249 |
func TestOffsetLock(t *testing.T) { |
| 7250 |
var wg sync.WaitGroup |
| 7251 |
for i := 0; i < 4; i++ { |
| 7252 |
i := i |
| 7253 |
wg.Add(1) |
| 7254 |
go func() { |
| 7255 |
for j := 0; j < 50; j++ { |
| 7256 |
ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j)) |
| 7257 |
} |
| 7258 |
wg.Done() |
| 7259 |
}() |
| 7260 |
} |
| 7261 |
wg.Wait() |
| 7262 |
} |
| 7263 |
*/ |
| 7264 |
|
| 7265 |
func BenchmarkNew(b *testing.B) { |
| 7266 |
v := TypeOf(XM{}) |
| 7267 |
b.RunParallel(func(pb *testing.PB) { |
| 7268 |
for pb.Next() { |
| 7269 |
New(v) |
| 7270 |
} |
| 7271 |
}) |
| 7272 |
} |
| 7273 |
|
| 7274 |
func BenchmarkMap(b *testing.B) { |
| 7275 |
type V *int |
| 7276 |
value := ValueOf((V)(nil)) |
| 7277 |
stringKeys := []string{} |
| 7278 |
mapOfStrings := map[string]V{} |
| 7279 |
uint64Keys := []uint64{} |
| 7280 |
mapOfUint64s := map[uint64]V{} |
| 7281 |
for i := 0; i < 100; i++ { |
| 7282 |
stringKey := fmt.Sprintf("key%d", i) |
| 7283 |
stringKeys = append(stringKeys, stringKey) |
| 7284 |
mapOfStrings[stringKey] = nil |
| 7285 |
|
| 7286 |
uint64Key := uint64(i) |
| 7287 |
uint64Keys = append(uint64Keys, uint64Key) |
| 7288 |
mapOfUint64s[uint64Key] = nil |
| 7289 |
} |
| 7290 |
|
| 7291 |
tests := []struct { |
| 7292 |
label string |
| 7293 |
m, keys, value Value |
| 7294 |
}{ |
| 7295 |
{"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value}, |
| 7296 |
{"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value}, |
| 7297 |
} |
| 7298 |
|
| 7299 |
for _, tt := range tests { |
| 7300 |
b.Run(tt.label, func(b *testing.B) { |
| 7301 |
b.Run("MapIndex", func(b *testing.B) { |
| 7302 |
b.ReportAllocs() |
| 7303 |
for i := 0; i < b.N; i++ { |
| 7304 |
for j := tt.keys.Len() - 1; j >= 0; j-- { |
| 7305 |
tt.m.MapIndex(tt.keys.Index(j)) |
| 7306 |
} |
| 7307 |
} |
| 7308 |
}) |
| 7309 |
b.Run("SetMapIndex", func(b *testing.B) { |
| 7310 |
b.ReportAllocs() |
| 7311 |
for i := 0; i < b.N; i++ { |
| 7312 |
for j := tt.keys.Len() - 1; j >= 0; j-- { |
| 7313 |
tt.m.SetMapIndex(tt.keys.Index(j), tt.value) |
| 7314 |
} |
| 7315 |
} |
| 7316 |
}) |
| 7317 |
}) |
| 7318 |
} |
| 7319 |
} |
| 7320 |
|
| 7321 |
func TestSwapper(t *testing.T) { |
| 7322 |
type I int |
| 7323 |
var a, b, c I |
| 7324 |
type pair struct { |
| 7325 |
x, y int |
| 7326 |
} |
| 7327 |
type pairPtr struct { |
| 7328 |
x, y int |
| 7329 |
p *I |
| 7330 |
} |
| 7331 |
type S string |
| 7332 |
|
| 7333 |
tests := []struct { |
| 7334 |
in any |
| 7335 |
i, j int |
| 7336 |
want any |
| 7337 |
}{ |
| 7338 |
{ |
| 7339 |
in: []int{1, 20, 300}, |
| 7340 |
i: 0, |
| 7341 |
j: 2, |
| 7342 |
want: []int{300, 20, 1}, |
| 7343 |
}, |
| 7344 |
{ |
| 7345 |
in: []uintptr{1, 20, 300}, |
| 7346 |
i: 0, |
| 7347 |
j: 2, |
| 7348 |
want: []uintptr{300, 20, 1}, |
| 7349 |
}, |
| 7350 |
{ |
| 7351 |
in: []int16{1, 20, 300}, |
| 7352 |
i: 0, |
| 7353 |
j: 2, |
| 7354 |
want: []int16{300, 20, 1}, |
| 7355 |
}, |
| 7356 |
{ |
| 7357 |
in: []int8{1, 20, 100}, |
| 7358 |
i: 0, |
| 7359 |
j: 2, |
| 7360 |
want: []int8{100, 20, 1}, |
| 7361 |
}, |
| 7362 |
{ |
| 7363 |
in: []*I{&a, &b, &c}, |
| 7364 |
i: 0, |
| 7365 |
j: 2, |
| 7366 |
want: []*I{&c, &b, &a}, |
| 7367 |
}, |
| 7368 |
{ |
| 7369 |
in: []string{"eric", "sergey", "larry"}, |
| 7370 |
i: 0, |
| 7371 |
j: 2, |
| 7372 |
want: []string{"larry", "sergey", "eric"}, |
| 7373 |
}, |
| 7374 |
{ |
| 7375 |
in: []S{"eric", "sergey", "larry"}, |
| 7376 |
i: 0, |
| 7377 |
j: 2, |
| 7378 |
want: []S{"larry", "sergey", "eric"}, |
| 7379 |
}, |
| 7380 |
{ |
| 7381 |
in: []pair{{1, 2}, {3, 4}, {5, 6}}, |
| 7382 |
i: 0, |
| 7383 |
j: 2, |
| 7384 |
want: []pair{{5, 6}, {3, 4}, {1, 2}}, |
| 7385 |
}, |
| 7386 |
{ |
| 7387 |
in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}}, |
| 7388 |
i: 0, |
| 7389 |
j: 2, |
| 7390 |
want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}}, |
| 7391 |
}, |
| 7392 |
} |
| 7393 |
|
| 7394 |
for i, tt := range tests { |
| 7395 |
inStr := fmt.Sprint(tt.in) |
| 7396 |
Swapper(tt.in)(tt.i, tt.j) |
| 7397 |
if !DeepEqual(tt.in, tt.want) { |
| 7398 |
t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want) |
| 7399 |
} |
| 7400 |
} |
| 7401 |
} |
| 7402 |
|
| 7403 |
// TestUnaddressableField tests that the reflect package will not allow |
| 7404 |
// a type from another package to be used as a named type with an |
| 7405 |
// unexported field. |
| 7406 |
// |
| 7407 |
// This ensures that unexported fields cannot be modified by other packages. |
| 7408 |
func TestUnaddressableField(t *testing.T) { |
| 7409 |
var b Buffer // type defined in reflect, a different package |
| 7410 |
var localBuffer struct { |
| 7411 |
buf []byte |
| 7412 |
} |
| 7413 |
lv := ValueOf(&localBuffer).Elem() |
| 7414 |
rv := ValueOf(b) |
| 7415 |
shouldPanic("Set", func() { |
| 7416 |
lv.Set(rv) |
| 7417 |
}) |
| 7418 |
} |
| 7419 |
|
| 7420 |
type Tint int |
| 7421 |
|
| 7422 |
type Tint2 = Tint |
| 7423 |
|
| 7424 |
type Talias1 struct { |
| 7425 |
byte |
| 7426 |
uint8 |
| 7427 |
int |
| 7428 |
int32 |
| 7429 |
rune |
| 7430 |
} |
| 7431 |
|
| 7432 |
type Talias2 struct { |
| 7433 |
Tint |
| 7434 |
Tint2 |
| 7435 |
} |
| 7436 |
|
| 7437 |
func TestAliasNames(t *testing.T) { |
| 7438 |
t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5} |
| 7439 |
out := fmt.Sprintf("%#v", t1) |
| 7440 |
want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}" |
| 7441 |
if out != want { |
| 7442 |
t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want) |
| 7443 |
} |
| 7444 |
|
| 7445 |
t2 := Talias2{Tint: 1, Tint2: 2} |
| 7446 |
out = fmt.Sprintf("%#v", t2) |
| 7447 |
want = "reflect_test.Talias2{Tint:1, Tint2:2}" |
| 7448 |
if out != want { |
| 7449 |
t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want) |
| 7450 |
} |
| 7451 |
} |
| 7452 |
|
| 7453 |
func TestIssue22031(t *testing.T) { |
| 7454 |
type s []struct{ C int } |
| 7455 |
|
| 7456 |
type t1 struct{ s } |
| 7457 |
type t2 struct{ f s } |
| 7458 |
|
| 7459 |
tests := []Value{ |
| 7460 |
ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0), |
| 7461 |
ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0), |
| 7462 |
} |
| 7463 |
|
| 7464 |
for i, test := range tests { |
| 7465 |
if test.CanSet() { |
| 7466 |
t.Errorf("%d: CanSet: got true, want false", i) |
| 7467 |
} |
| 7468 |
} |
| 7469 |
} |
| 7470 |
|
| 7471 |
type NonExportedFirst int |
| 7472 |
|
| 7473 |
func (i NonExportedFirst) ΦExported() {} |
| 7474 |
func (i NonExportedFirst) nonexported() int { panic("wrong") } |
| 7475 |
|
| 7476 |
func TestIssue22073(t *testing.T) { |
| 7477 |
m := ValueOf(NonExportedFirst(0)).Method(0) |
| 7478 |
|
| 7479 |
if got := m.Type().NumOut(); got != 0 { |
| 7480 |
t.Errorf("NumOut: got %v, want 0", got) |
| 7481 |
} |
| 7482 |
|
| 7483 |
// Shouldn't panic. |
| 7484 |
m.Call(nil) |
| 7485 |
} |
| 7486 |
|
| 7487 |
func TestMapIterNonEmptyMap(t *testing.T) { |
| 7488 |
m := map[string]int{"one": 1, "two": 2, "three": 3} |
| 7489 |
iter := ValueOf(m).MapRange() |
| 7490 |
if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want { |
| 7491 |
t.Errorf("iterator returned %s (after sorting), want %s", got, want) |
| 7492 |
} |
| 7493 |
} |
| 7494 |
|
| 7495 |
func TestMapIterNilMap(t *testing.T) { |
| 7496 |
var m map[string]int |
| 7497 |
iter := ValueOf(m).MapRange() |
| 7498 |
if got, want := iterateToString(iter), `[]`; got != want { |
| 7499 |
t.Errorf("non-empty result iteratoring nil map: %s", got) |
| 7500 |
} |
| 7501 |
} |
| 7502 |
|
| 7503 |
func TestMapIterReset(t *testing.T) { |
| 7504 |
iter := new(MapIter) |
| 7505 |
|
| 7506 |
// Use of zero iterator should panic. |
| 7507 |
func() { |
| 7508 |
defer func() { recover() }() |
| 7509 |
iter.Next() |
| 7510 |
t.Error("Next did not panic") |
| 7511 |
}() |
| 7512 |
|
| 7513 |
// Reset to new Map should work. |
| 7514 |
m := map[string]int{"one": 1, "two": 2, "three": 3} |
| 7515 |
iter.Reset(ValueOf(m)) |
| 7516 |
if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want { |
| 7517 |
t.Errorf("iterator returned %s (after sorting), want %s", got, want) |
| 7518 |
} |
| 7519 |
|
| 7520 |
// Reset to Zero value should work, but iterating over it should panic. |
| 7521 |
iter.Reset(Value{}) |
| 7522 |
func() { |
| 7523 |
defer func() { recover() }() |
| 7524 |
iter.Next() |
| 7525 |
t.Error("Next did not panic") |
| 7526 |
}() |
| 7527 |
|
| 7528 |
// Reset to a different Map with different types should work. |
| 7529 |
m2 := map[int]string{1: "one", 2: "two", 3: "three"} |
| 7530 |
iter.Reset(ValueOf(m2)) |
| 7531 |
if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want { |
| 7532 |
t.Errorf("iterator returned %s (after sorting), want %s", got, want) |
| 7533 |
} |
| 7534 |
|
| 7535 |
// Check that Reset, Next, and SetKey/SetValue play nicely together. |
| 7536 |
m3 := map[uint64]uint64{ |
| 7537 |
1 << 0: 1 << 1, |
| 7538 |
1 << 1: 1 << 2, |
| 7539 |
1 << 2: 1 << 3, |
| 7540 |
} |
| 7541 |
kv := New(TypeOf(uint64(0))).Elem() |
| 7542 |
for i := 0; i < 5; i++ { |
| 7543 |
var seenk, seenv uint64 |
| 7544 |
iter.Reset(ValueOf(m3)) |
| 7545 |
for iter.Next() { |
| 7546 |
kv.SetIterKey(iter) |
| 7547 |
seenk ^= kv.Uint() |
| 7548 |
kv.SetIterValue(iter) |
| 7549 |
seenv ^= kv.Uint() |
| 7550 |
} |
| 7551 |
if seenk != 0b111 { |
| 7552 |
t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111) |
| 7553 |
} |
| 7554 |
if seenv != 0b1110 { |
| 7555 |
t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110) |
| 7556 |
} |
| 7557 |
} |
| 7558 |
|
| 7559 |
// Reset should not allocate. |
| 7560 |
n := int(testing.AllocsPerRun(10, func() { |
| 7561 |
iter.Reset(ValueOf(m2)) |
| 7562 |
iter.Reset(Value{}) |
| 7563 |
})) |
| 7564 |
if n > 0 { |
| 7565 |
t.Errorf("MapIter.Reset allocated %d times", n) |
| 7566 |
} |
| 7567 |
} |
| 7568 |
|
| 7569 |
func TestMapIterSafety(t *testing.T) { |
| 7570 |
// Using a zero MapIter causes a panic, but not a crash. |
| 7571 |
func() { |
| 7572 |
defer func() { recover() }() |
| 7573 |
new(MapIter).Key() |
| 7574 |
t.Fatal("Key did not panic") |
| 7575 |
}() |
| 7576 |
func() { |
| 7577 |
defer func() { recover() }() |
| 7578 |
new(MapIter).Value() |
| 7579 |
t.Fatal("Value did not panic") |
| 7580 |
}() |
| 7581 |
func() { |
| 7582 |
defer func() { recover() }() |
| 7583 |
new(MapIter).Next() |
| 7584 |
t.Fatal("Next did not panic") |
| 7585 |
}() |
| 7586 |
|
| 7587 |
// Calling Key/Value on a MapIter before Next |
| 7588 |
// causes a panic, but not a crash. |
| 7589 |
var m map[string]int |
| 7590 |
iter := ValueOf(m).MapRange() |
| 7591 |
|
| 7592 |
func() { |
| 7593 |
defer func() { recover() }() |
| 7594 |
iter.Key() |
| 7595 |
t.Fatal("Key did not panic") |
| 7596 |
}() |
| 7597 |
func() { |
| 7598 |
defer func() { recover() }() |
| 7599 |
iter.Value() |
| 7600 |
t.Fatal("Value did not panic") |
| 7601 |
}() |
| 7602 |
|
| 7603 |
// Calling Next, Key, or Value on an exhausted iterator |
| 7604 |
// causes a panic, but not a crash. |
| 7605 |
iter.Next() // -> false |
| 7606 |
func() { |
| 7607 |
defer func() { recover() }() |
| 7608 |
iter.Key() |
| 7609 |
t.Fatal("Key did not panic") |
| 7610 |
}() |
| 7611 |
func() { |
| 7612 |
defer func() { recover() }() |
| 7613 |
iter.Value() |
| 7614 |
t.Fatal("Value did not panic") |
| 7615 |
}() |
| 7616 |
func() { |
| 7617 |
defer func() { recover() }() |
| 7618 |
iter.Next() |
| 7619 |
t.Fatal("Next did not panic") |
| 7620 |
}() |
| 7621 |
} |
| 7622 |
|
| 7623 |
func TestMapIterNext(t *testing.T) { |
| 7624 |
// The first call to Next should reflect any |
| 7625 |
// insertions to the map since the iterator was created. |
| 7626 |
m := map[string]int{} |
| 7627 |
iter := ValueOf(m).MapRange() |
| 7628 |
m["one"] = 1 |
| 7629 |
if got, want := iterateToString(iter), `[one: 1]`; got != want { |
| 7630 |
t.Errorf("iterator returned deleted elements: got %s, want %s", got, want) |
| 7631 |
} |
| 7632 |
} |
| 7633 |
|
| 7634 |
func BenchmarkMapIterNext(b *testing.B) { |
| 7635 |
m := ValueOf(map[string]int{"a": 0, "b": 1, "c": 2, "d": 3}) |
| 7636 |
it := m.MapRange() |
| 7637 |
for i := 0; i < b.N; i++ { |
| 7638 |
for it.Next() { |
| 7639 |
} |
| 7640 |
it.Reset(m) |
| 7641 |
} |
| 7642 |
} |
| 7643 |
|
| 7644 |
func TestMapIterDelete0(t *testing.T) { |
| 7645 |
// Delete all elements before first iteration. |
| 7646 |
m := map[string]int{"one": 1, "two": 2, "three": 3} |
| 7647 |
iter := ValueOf(m).MapRange() |
| 7648 |
delete(m, "one") |
| 7649 |
delete(m, "two") |
| 7650 |
delete(m, "three") |
| 7651 |
if got, want := iterateToString(iter), `[]`; got != want { |
| 7652 |
t.Errorf("iterator returned deleted elements: got %s, want %s", got, want) |
| 7653 |
} |
| 7654 |
} |
| 7655 |
|
| 7656 |
func TestMapIterDelete1(t *testing.T) { |
| 7657 |
// Delete all elements after first iteration. |
| 7658 |
m := map[string]int{"one": 1, "two": 2, "three": 3} |
| 7659 |
iter := ValueOf(m).MapRange() |
| 7660 |
var got []string |
| 7661 |
for iter.Next() { |
| 7662 |
got = append(got, fmt.Sprint(iter.Key(), iter.Value())) |
| 7663 |
delete(m, "one") |
| 7664 |
delete(m, "two") |
| 7665 |
delete(m, "three") |
| 7666 |
} |
| 7667 |
if len(got) != 1 { |
| 7668 |
t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got)) |
| 7669 |
} |
| 7670 |
} |
| 7671 |
|
| 7672 |
// iterateToString returns the set of elements |
| 7673 |
// returned by an iterator in readable form. |
| 7674 |
func iterateToString(it *MapIter) string { |
| 7675 |
var got []string |
| 7676 |
for it.Next() { |
| 7677 |
line := fmt.Sprintf("%v: %v", it.Key(), it.Value()) |
| 7678 |
got = append(got, line) |
| 7679 |
} |
| 7680 |
sort.Strings(got) |
| 7681 |
return "[" + strings.Join(got, ", ") + "]" |
| 7682 |
} |
| 7683 |
|
| 7684 |
func TestConvertibleTo(t *testing.T) { |
| 7685 |
t1 := ValueOf(example1.MyStruct{}).Type() |
| 7686 |
t2 := ValueOf(example2.MyStruct{}).Type() |
| 7687 |
|
| 7688 |
// Shouldn't raise stack overflow |
| 7689 |
if t1.ConvertibleTo(t2) { |
| 7690 |
t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2) |
| 7691 |
} |
| 7692 |
|
| 7693 |
t3 := ValueOf([]example1.MyStruct{}).Type() |
| 7694 |
t4 := ValueOf([]example2.MyStruct{}).Type() |
| 7695 |
|
| 7696 |
if t3.ConvertibleTo(t4) { |
| 7697 |
t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4) |
| 7698 |
} |
| 7699 |
} |
| 7700 |
|
| 7701 |
func TestSetIter(t *testing.T) { |
| 7702 |
data := map[string]int{ |
| 7703 |
"foo": 1, |
| 7704 |
"bar": 2, |
| 7705 |
"baz": 3, |
| 7706 |
} |
| 7707 |
|
| 7708 |
m := ValueOf(data) |
| 7709 |
i := m.MapRange() |
| 7710 |
k := New(TypeOf("")).Elem() |
| 7711 |
v := New(TypeOf(0)).Elem() |
| 7712 |
shouldPanic("Value.SetIterKey called before Next", func() { |
| 7713 |
k.SetIterKey(i) |
| 7714 |
}) |
| 7715 |
shouldPanic("Value.SetIterValue called before Next", func() { |
| 7716 |
v.SetIterValue(i) |
| 7717 |
}) |
| 7718 |
data2 := map[string]int{} |
| 7719 |
for i.Next() { |
| 7720 |
k.SetIterKey(i) |
| 7721 |
v.SetIterValue(i) |
| 7722 |
data2[k.Interface().(string)] = v.Interface().(int) |
| 7723 |
} |
| 7724 |
if !DeepEqual(data, data2) { |
| 7725 |
t.Errorf("maps not equal, got %v want %v", data2, data) |
| 7726 |
} |
| 7727 |
shouldPanic("Value.SetIterKey called on exhausted iterator", func() { |
| 7728 |
k.SetIterKey(i) |
| 7729 |
}) |
| 7730 |
shouldPanic("Value.SetIterValue called on exhausted iterator", func() { |
| 7731 |
v.SetIterValue(i) |
| 7732 |
}) |
| 7733 |
|
| 7734 |
i.Reset(m) |
| 7735 |
i.Next() |
| 7736 |
shouldPanic("Value.SetIterKey using unaddressable value", func() { |
| 7737 |
ValueOf("").SetIterKey(i) |
| 7738 |
}) |
| 7739 |
shouldPanic("Value.SetIterValue using unaddressable value", func() { |
| 7740 |
ValueOf(0).SetIterValue(i) |
| 7741 |
}) |
| 7742 |
shouldPanic("value of type string is not assignable to type int", func() { |
| 7743 |
New(TypeOf(0)).Elem().SetIterKey(i) |
| 7744 |
}) |
| 7745 |
shouldPanic("value of type int is not assignable to type string", func() { |
| 7746 |
New(TypeOf("")).Elem().SetIterValue(i) |
| 7747 |
}) |
| 7748 |
|
| 7749 |
// Make sure assignment conversion works. |
| 7750 |
var x any |
| 7751 |
y := ValueOf(&x).Elem() |
| 7752 |
y.SetIterKey(i) |
| 7753 |
if _, ok := data[x.(string)]; !ok { |
| 7754 |
t.Errorf("got key %s which is not in map", x) |
| 7755 |
} |
| 7756 |
y.SetIterValue(i) |
| 7757 |
if x.(int) < 1 || x.(int) > 3 { |
| 7758 |
t.Errorf("got value %d which is not in map", x) |
| 7759 |
} |
| 7760 |
|
| 7761 |
// Try some key/value types which are direct interfaces. |
| 7762 |
a := 88 |
| 7763 |
b := 99 |
| 7764 |
pp := map[*int]*int{ |
| 7765 |
&a: &b, |
| 7766 |
} |
| 7767 |
i = ValueOf(pp).MapRange() |
| 7768 |
i.Next() |
| 7769 |
y.SetIterKey(i) |
| 7770 |
if got := *y.Interface().(*int); got != a { |
| 7771 |
t.Errorf("pointer incorrect: got %d want %d", got, a) |
| 7772 |
} |
| 7773 |
y.SetIterValue(i) |
| 7774 |
if got := *y.Interface().(*int); got != b { |
| 7775 |
t.Errorf("pointer incorrect: got %d want %d", got, b) |
| 7776 |
} |
| 7777 |
} |
| 7778 |
|
| 7779 |
//go:notinheap |
| 7780 |
type nih struct{ x int } |
| 7781 |
|
| 7782 |
var global_nih = nih{x: 7} |
| 7783 |
|
| 7784 |
func TestNotInHeapDeref(t *testing.T) { |
| 7785 |
// See issue 48399. |
| 7786 |
v := ValueOf((*nih)(nil)) |
| 7787 |
v.Elem() |
| 7788 |
shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) }) |
| 7789 |
|
| 7790 |
v = ValueOf(&global_nih) |
| 7791 |
if got := v.Elem().Field(0).Int(); got != 7 { |
| 7792 |
t.Fatalf("got %d, want 7", got) |
| 7793 |
} |
| 7794 |
|
| 7795 |
v = ValueOf((*nih)(unsafe.Pointer(new(int)))) |
| 7796 |
shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() }) |
| 7797 |
shouldPanic("reflect: reflect.Value.Pointer on an invalid notinheap pointer", func() { v.Pointer() }) |
| 7798 |
shouldPanic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer", func() { v.UnsafePointer() }) |
| 7799 |
} |
| 7800 |
|
| 7801 |
func TestMethodCallValueCodePtr(t *testing.T) { |
| 7802 |
m := ValueOf(Point{}).Method(1) |
| 7803 |
want := MethodValueCallCodePtr() |
| 7804 |
if got := uintptr(m.UnsafePointer()); got != want { |
| 7805 |
t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got) |
| 7806 |
} |
| 7807 |
if got := m.Pointer(); got != want { |
| 7808 |
t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got) |
| 7809 |
} |
| 7810 |
} |
| 7811 |
|
| 7812 |
/* FIXME: comment out for generics |
| 7813 |
|
| 7814 |
type A struct{} |
| 7815 |
type B[T any] struct{} |
| 7816 |
|
| 7817 |
func TestIssue50208(t *testing.T) { |
| 7818 |
want1 := "B[reflect_test.A]" |
| 7819 |
if got := TypeOf(new(B[A])).Elem().Name(); got != want1 { |
| 7820 |
t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got) |
| 7821 |
} |
| 7822 |
want2 := "B[reflect_test.B[reflect_test.A]]" |
| 7823 |
if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 { |
| 7824 |
t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got) |
| 7825 |
} |
| 7826 |
} |
| 7827 |
|
| 7828 |
*/ |