github.com/sbinet/go@v0.0.0-20160827155028-54d7de7dd62b/src/reflect/value.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package reflect 6 7 import ( 8 "math" 9 "runtime" 10 "unsafe" 11 ) 12 13 const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const 14 15 // Value is the reflection interface to a Go value. 16 // 17 // Not all methods apply to all kinds of values. Restrictions, 18 // if any, are noted in the documentation for each method. 19 // Use the Kind method to find out the kind of value before 20 // calling kind-specific methods. Calling a method 21 // inappropriate to the kind of type causes a run time panic. 22 // 23 // The zero Value represents no value. 24 // Its IsValid method returns false, its Kind method returns Invalid, 25 // its String method returns "<invalid Value>", and all other methods panic. 26 // Most functions and methods never return an invalid value. 27 // If one does, its documentation states the conditions explicitly. 28 // 29 // A Value can be used concurrently by multiple goroutines provided that 30 // the underlying Go value can be used concurrently for the equivalent 31 // direct operations. 32 // 33 // Using == on two Values does not compare the underlying values 34 // they represent, but rather the contents of the Value structs. 35 // To compare two Values, compare the results of the Interface method. 36 type Value struct { 37 // typ holds the type of the value represented by a Value. 38 typ *rtype 39 40 // Pointer-valued data or, if flagIndir is set, pointer to data. 41 // Valid when either flagIndir is set or typ.pointers() is true. 42 ptr unsafe.Pointer 43 44 // flag holds metadata about the value. 45 // The lowest bits are flag bits: 46 // - flagStickyRO: obtained via unexported not embedded field, so read-only 47 // - flagEmbedRO: obtained via unexported embedded field, so read-only 48 // - flagIndir: val holds a pointer to the data 49 // - flagAddr: v.CanAddr is true (implies flagIndir) 50 // - flagMethod: v is a method value. 51 // The next five bits give the Kind of the value. 52 // This repeats typ.Kind() except for method values. 53 // The remaining 23+ bits give a method number for method values. 54 // If flag.kind() != Func, code can assume that flagMethod is unset. 55 // If ifaceIndir(typ), code can assume that flagIndir is set. 56 flag 57 58 // A method value represents a curried method invocation 59 // like r.Read for some receiver r. The typ+val+flag bits describe 60 // the receiver r, but the flag's Kind bits say Func (methods are 61 // functions), and the top bits of the flag give the method number 62 // in r's type's method table. 63 } 64 65 type flag uintptr 66 67 const ( 68 flagKindWidth = 5 // there are 27 kinds 69 flagKindMask flag = 1<<flagKindWidth - 1 70 flagStickyRO flag = 1 << 5 71 flagEmbedRO flag = 1 << 6 72 flagIndir flag = 1 << 7 73 flagAddr flag = 1 << 8 74 flagMethod flag = 1 << 9 75 flagMethodShift = 10 76 flagRO flag = flagStickyRO | flagEmbedRO 77 ) 78 79 func (f flag) kind() Kind { 80 return Kind(f & flagKindMask) 81 } 82 83 // pointer returns the underlying pointer represented by v. 84 // v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer 85 func (v Value) pointer() unsafe.Pointer { 86 if v.typ.size != ptrSize || !v.typ.pointers() { 87 panic("can't call pointer on a non-pointer Value") 88 } 89 if v.flag&flagIndir != 0 { 90 return *(*unsafe.Pointer)(v.ptr) 91 } 92 return v.ptr 93 } 94 95 // packEface converts v to the empty interface. 96 func packEface(v Value) interface{} { 97 t := v.typ 98 var i interface{} 99 e := (*emptyInterface)(unsafe.Pointer(&i)) 100 // First, fill in the data portion of the interface. 101 switch { 102 case ifaceIndir(t): 103 if v.flag&flagIndir == 0 { 104 panic("bad indir") 105 } 106 // Value is indirect, and so is the interface we're making. 107 ptr := v.ptr 108 if v.flag&flagAddr != 0 { 109 // TODO: pass safe boolean from valueInterface so 110 // we don't need to copy if safe==true? 111 c := unsafe_New(t) 112 typedmemmove(t, c, ptr) 113 ptr = c 114 } 115 e.word = ptr 116 case v.flag&flagIndir != 0: 117 // Value is indirect, but interface is direct. We need 118 // to load the data at v.ptr into the interface data word. 119 e.word = *(*unsafe.Pointer)(v.ptr) 120 default: 121 // Value is direct, and so is the interface. 122 e.word = v.ptr 123 } 124 // Now, fill in the type portion. We're very careful here not 125 // to have any operation between the e.word and e.typ assignments 126 // that would let the garbage collector observe the partially-built 127 // interface value. 128 e.typ = t 129 return i 130 } 131 132 // unpackEface converts the empty interface i to a Value. 133 func unpackEface(i interface{}) Value { 134 e := (*emptyInterface)(unsafe.Pointer(&i)) 135 // NOTE: don't read e.word until we know whether it is really a pointer or not. 136 t := e.typ 137 if t == nil { 138 return Value{} 139 } 140 f := flag(t.Kind()) 141 if ifaceIndir(t) { 142 f |= flagIndir 143 } 144 return Value{t, e.word, f} 145 } 146 147 // A ValueError occurs when a Value method is invoked on 148 // a Value that does not support it. Such cases are documented 149 // in the description of each method. 150 type ValueError struct { 151 Method string 152 Kind Kind 153 } 154 155 func (e *ValueError) Error() string { 156 if e.Kind == 0 { 157 return "reflect: call of " + e.Method + " on zero Value" 158 } 159 return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value" 160 } 161 162 // methodName returns the name of the calling method, 163 // assumed to be two stack frames above. 164 func methodName() string { 165 pc, _, _, _ := runtime.Caller(2) 166 f := runtime.FuncForPC(pc) 167 if f == nil { 168 return "unknown method" 169 } 170 return f.Name() 171 } 172 173 // emptyInterface is the header for an interface{} value. 174 type emptyInterface struct { 175 typ *rtype 176 word unsafe.Pointer 177 } 178 179 // nonEmptyInterface is the header for a interface value with methods. 180 type nonEmptyInterface struct { 181 // see ../runtime/iface.go:/Itab 182 itab *struct { 183 ityp *rtype // static interface type 184 typ *rtype // dynamic concrete type 185 link unsafe.Pointer 186 bad int32 187 unused int32 188 fun [100000]unsafe.Pointer // method table 189 } 190 word unsafe.Pointer 191 } 192 193 // mustBe panics if f's kind is not expected. 194 // Making this a method on flag instead of on Value 195 // (and embedding flag in Value) means that we can write 196 // the very clear v.mustBe(Bool) and have it compile into 197 // v.flag.mustBe(Bool), which will only bother to copy the 198 // single important word for the receiver. 199 func (f flag) mustBe(expected Kind) { 200 if f.kind() != expected { 201 panic(&ValueError{methodName(), f.kind()}) 202 } 203 } 204 205 // mustBeExported panics if f records that the value was obtained using 206 // an unexported field. 207 func (f flag) mustBeExported() { 208 if f == 0 { 209 panic(&ValueError{methodName(), 0}) 210 } 211 if f&flagRO != 0 { 212 panic("reflect: " + methodName() + " using value obtained using unexported field") 213 } 214 } 215 216 // mustBeAssignable panics if f records that the value is not assignable, 217 // which is to say that either it was obtained using an unexported field 218 // or it is not addressable. 219 func (f flag) mustBeAssignable() { 220 if f == 0 { 221 panic(&ValueError{methodName(), Invalid}) 222 } 223 // Assignable if addressable and not read-only. 224 if f&flagRO != 0 { 225 panic("reflect: " + methodName() + " using value obtained using unexported field") 226 } 227 if f&flagAddr == 0 { 228 panic("reflect: " + methodName() + " using unaddressable value") 229 } 230 } 231 232 // Addr returns a pointer value representing the address of v. 233 // It panics if CanAddr() returns false. 234 // Addr is typically used to obtain a pointer to a struct field 235 // or slice element in order to call a method that requires a 236 // pointer receiver. 237 func (v Value) Addr() Value { 238 if v.flag&flagAddr == 0 { 239 panic("reflect.Value.Addr of unaddressable value") 240 } 241 return Value{v.typ.ptrTo(), v.ptr, (v.flag & flagRO) | flag(Ptr)} 242 } 243 244 // Bool returns v's underlying value. 245 // It panics if v's kind is not Bool. 246 func (v Value) Bool() bool { 247 v.mustBe(Bool) 248 return *(*bool)(v.ptr) 249 } 250 251 // Bytes returns v's underlying value. 252 // It panics if v's underlying value is not a slice of bytes. 253 func (v Value) Bytes() []byte { 254 v.mustBe(Slice) 255 if v.typ.Elem().Kind() != Uint8 { 256 panic("reflect.Value.Bytes of non-byte slice") 257 } 258 // Slice is always bigger than a word; assume flagIndir. 259 return *(*[]byte)(v.ptr) 260 } 261 262 // runes returns v's underlying value. 263 // It panics if v's underlying value is not a slice of runes (int32s). 264 func (v Value) runes() []rune { 265 v.mustBe(Slice) 266 if v.typ.Elem().Kind() != Int32 { 267 panic("reflect.Value.Bytes of non-rune slice") 268 } 269 // Slice is always bigger than a word; assume flagIndir. 270 return *(*[]rune)(v.ptr) 271 } 272 273 // CanAddr reports whether the value's address can be obtained with Addr. 274 // Such values are called addressable. A value is addressable if it is 275 // an element of a slice, an element of an addressable array, 276 // a field of an addressable struct, or the result of dereferencing a pointer. 277 // If CanAddr returns false, calling Addr will panic. 278 func (v Value) CanAddr() bool { 279 return v.flag&flagAddr != 0 280 } 281 282 // CanSet reports whether the value of v can be changed. 283 // A Value can be changed only if it is addressable and was not 284 // obtained by the use of unexported struct fields. 285 // If CanSet returns false, calling Set or any type-specific 286 // setter (e.g., SetBool, SetInt) will panic. 287 func (v Value) CanSet() bool { 288 return v.flag&(flagAddr|flagRO) == flagAddr 289 } 290 291 // Call calls the function v with the input arguments in. 292 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]). 293 // Call panics if v's Kind is not Func. 294 // It returns the output results as Values. 295 // As in Go, each input argument must be assignable to the 296 // type of the function's corresponding input parameter. 297 // If v is a variadic function, Call creates the variadic slice parameter 298 // itself, copying in the corresponding values. 299 func (v Value) Call(in []Value) []Value { 300 v.mustBe(Func) 301 v.mustBeExported() 302 return v.call("Call", in) 303 } 304 305 // CallSlice calls the variadic function v with the input arguments in, 306 // assigning the slice in[len(in)-1] to v's final variadic argument. 307 // For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...). 308 // CallSlice panics if v's Kind is not Func or if v is not variadic. 309 // It returns the output results as Values. 310 // As in Go, each input argument must be assignable to the 311 // type of the function's corresponding input parameter. 312 func (v Value) CallSlice(in []Value) []Value { 313 v.mustBe(Func) 314 v.mustBeExported() 315 return v.call("CallSlice", in) 316 } 317 318 var callGC bool // for testing; see TestCallMethodJump 319 320 func (v Value) call(op string, in []Value) []Value { 321 // Get function pointer, type. 322 t := v.typ 323 var ( 324 fn unsafe.Pointer 325 rcvr Value 326 rcvrtype *rtype 327 ) 328 if v.flag&flagMethod != 0 { 329 rcvr = v 330 rcvrtype, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift) 331 } else if v.flag&flagIndir != 0 { 332 fn = *(*unsafe.Pointer)(v.ptr) 333 } else { 334 fn = v.ptr 335 } 336 337 if fn == nil { 338 panic("reflect.Value.Call: call of nil function") 339 } 340 341 isSlice := op == "CallSlice" 342 n := t.NumIn() 343 if isSlice { 344 if !t.IsVariadic() { 345 panic("reflect: CallSlice of non-variadic function") 346 } 347 if len(in) < n { 348 panic("reflect: CallSlice with too few input arguments") 349 } 350 if len(in) > n { 351 panic("reflect: CallSlice with too many input arguments") 352 } 353 } else { 354 if t.IsVariadic() { 355 n-- 356 } 357 if len(in) < n { 358 panic("reflect: Call with too few input arguments") 359 } 360 if !t.IsVariadic() && len(in) > n { 361 panic("reflect: Call with too many input arguments") 362 } 363 } 364 for _, x := range in { 365 if x.Kind() == Invalid { 366 panic("reflect: " + op + " using zero Value argument") 367 } 368 } 369 for i := 0; i < n; i++ { 370 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) { 371 panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String()) 372 } 373 } 374 if !isSlice && t.IsVariadic() { 375 // prepare slice for remaining values 376 m := len(in) - n 377 slice := MakeSlice(t.In(n), m, m) 378 elem := t.In(n).Elem() 379 for i := 0; i < m; i++ { 380 x := in[n+i] 381 if xt := x.Type(); !xt.AssignableTo(elem) { 382 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op) 383 } 384 slice.Index(i).Set(x) 385 } 386 origIn := in 387 in = make([]Value, n+1) 388 copy(in[:n], origIn) 389 in[n] = slice 390 } 391 392 nin := len(in) 393 if nin != t.NumIn() { 394 panic("reflect.Value.Call: wrong argument count") 395 } 396 nout := t.NumOut() 397 398 // Compute frame type. 399 frametype, _, retOffset, _, framePool := funcLayout(t, rcvrtype) 400 401 // Allocate a chunk of memory for frame. 402 var args unsafe.Pointer 403 if nout == 0 { 404 args = framePool.Get().(unsafe.Pointer) 405 } else { 406 // Can't use pool if the function has return values. 407 // We will leak pointer to args in ret, so its lifetime is not scoped. 408 args = unsafe_New(frametype) 409 } 410 off := uintptr(0) 411 412 // Copy inputs into args. 413 if rcvrtype != nil { 414 storeRcvr(rcvr, args) 415 off = ptrSize 416 } 417 for i, v := range in { 418 v.mustBeExported() 419 targ := t.In(i).(*rtype) 420 a := uintptr(targ.align) 421 off = (off + a - 1) &^ (a - 1) 422 n := targ.size 423 addr := unsafe.Pointer(uintptr(args) + off) 424 v = v.assignTo("reflect.Value.Call", targ, addr) 425 if v.flag&flagIndir != 0 { 426 typedmemmove(targ, addr, v.ptr) 427 } else { 428 *(*unsafe.Pointer)(addr) = v.ptr 429 } 430 off += n 431 } 432 433 // Call. 434 call(frametype, fn, args, uint32(frametype.size), uint32(retOffset)) 435 436 // For testing; see TestCallMethodJump. 437 if callGC { 438 runtime.GC() 439 } 440 441 var ret []Value 442 if nout == 0 { 443 memclr(args, frametype.size) 444 framePool.Put(args) 445 } else { 446 // Zero the now unused input area of args, 447 // because the Values returned by this function contain pointers to the args object, 448 // and will thus keep the args object alive indefinitely. 449 memclr(args, retOffset) 450 // Copy return values out of args. 451 ret = make([]Value, nout) 452 off = retOffset 453 for i := 0; i < nout; i++ { 454 tv := t.Out(i) 455 a := uintptr(tv.Align()) 456 off = (off + a - 1) &^ (a - 1) 457 fl := flagIndir | flag(tv.Kind()) 458 ret[i] = Value{tv.common(), unsafe.Pointer(uintptr(args) + off), fl} 459 off += tv.Size() 460 } 461 } 462 463 return ret 464 } 465 466 // callReflect is the call implementation used by a function 467 // returned by MakeFunc. In many ways it is the opposite of the 468 // method Value.call above. The method above converts a call using Values 469 // into a call of a function with a concrete argument frame, while 470 // callReflect converts a call of a function with a concrete argument 471 // frame into a call using Values. 472 // It is in this file so that it can be next to the call method above. 473 // The remainder of the MakeFunc implementation is in makefunc.go. 474 // 475 // NOTE: This function must be marked as a "wrapper" in the generated code, 476 // so that the linker can make it work correctly for panic and recover. 477 // The gc compilers know to do that for the name "reflect.callReflect". 478 func callReflect(ctxt *makeFuncImpl, frame unsafe.Pointer) { 479 ftyp := ctxt.typ 480 f := ctxt.fn 481 482 // Copy argument frame into Values. 483 ptr := frame 484 off := uintptr(0) 485 in := make([]Value, 0, int(ftyp.inCount)) 486 for _, typ := range ftyp.in() { 487 off += -off & uintptr(typ.align-1) 488 addr := unsafe.Pointer(uintptr(ptr) + off) 489 v := Value{typ, nil, flag(typ.Kind())} 490 if ifaceIndir(typ) { 491 // value cannot be inlined in interface data. 492 // Must make a copy, because f might keep a reference to it, 493 // and we cannot let f keep a reference to the stack frame 494 // after this function returns, not even a read-only reference. 495 v.ptr = unsafe_New(typ) 496 typedmemmove(typ, v.ptr, addr) 497 v.flag |= flagIndir 498 } else { 499 v.ptr = *(*unsafe.Pointer)(addr) 500 } 501 in = append(in, v) 502 off += typ.size 503 } 504 505 // Call underlying function. 506 out := f(in) 507 numOut := ftyp.NumOut() 508 if len(out) != numOut { 509 panic("reflect: wrong return count from function created by MakeFunc") 510 } 511 512 // Copy results back into argument frame. 513 if numOut > 0 { 514 off += -off & (ptrSize - 1) 515 if runtime.GOARCH == "amd64p32" { 516 off = align(off, 8) 517 } 518 for i, typ := range ftyp.out() { 519 v := out[i] 520 if v.typ != typ { 521 panic("reflect: function created by MakeFunc using " + funcName(f) + 522 " returned wrong type: have " + 523 out[i].typ.String() + " for " + typ.String()) 524 } 525 if v.flag&flagRO != 0 { 526 panic("reflect: function created by MakeFunc using " + funcName(f) + 527 " returned value obtained from unexported field") 528 } 529 off += -off & uintptr(typ.align-1) 530 addr := unsafe.Pointer(uintptr(ptr) + off) 531 if v.flag&flagIndir != 0 { 532 typedmemmove(typ, addr, v.ptr) 533 } else { 534 *(*unsafe.Pointer)(addr) = v.ptr 535 } 536 off += typ.size 537 } 538 } 539 } 540 541 // methodReceiver returns information about the receiver 542 // described by v. The Value v may or may not have the 543 // flagMethod bit set, so the kind cached in v.flag should 544 // not be used. 545 // The return value rcvrtype gives the method's actual receiver type. 546 // The return value t gives the method type signature (without the receiver). 547 // The return value fn is a pointer to the method code. 548 func methodReceiver(op string, v Value, methodIndex int) (rcvrtype, t *rtype, fn unsafe.Pointer) { 549 i := methodIndex 550 if v.typ.Kind() == Interface { 551 tt := (*interfaceType)(unsafe.Pointer(v.typ)) 552 if uint(i) >= uint(len(tt.methods)) { 553 panic("reflect: internal error: invalid method index") 554 } 555 m := &tt.methods[i] 556 if !tt.nameOff(m.name).isExported() { 557 panic("reflect: " + op + " of unexported method") 558 } 559 iface := (*nonEmptyInterface)(v.ptr) 560 if iface.itab == nil { 561 panic("reflect: " + op + " of method on nil interface value") 562 } 563 rcvrtype = iface.itab.typ 564 fn = unsafe.Pointer(&iface.itab.fun[i]) 565 t = tt.typeOff(m.typ) 566 } else { 567 rcvrtype = v.typ 568 ut := v.typ.uncommon() 569 if ut == nil || uint(i) >= uint(ut.mcount) { 570 panic("reflect: internal error: invalid method index") 571 } 572 m := ut.methods()[i] 573 if !v.typ.nameOff(m.name).isExported() { 574 panic("reflect: " + op + " of unexported method") 575 } 576 ifn := v.typ.textOff(m.ifn) 577 fn = unsafe.Pointer(&ifn) 578 t = v.typ.typeOff(m.mtyp) 579 } 580 return 581 } 582 583 // v is a method receiver. Store at p the word which is used to 584 // encode that receiver at the start of the argument list. 585 // Reflect uses the "interface" calling convention for 586 // methods, which always uses one word to record the receiver. 587 func storeRcvr(v Value, p unsafe.Pointer) { 588 t := v.typ 589 if t.Kind() == Interface { 590 // the interface data word becomes the receiver word 591 iface := (*nonEmptyInterface)(v.ptr) 592 *(*unsafe.Pointer)(p) = iface.word 593 } else if v.flag&flagIndir != 0 && !ifaceIndir(t) { 594 *(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr) 595 } else { 596 *(*unsafe.Pointer)(p) = v.ptr 597 } 598 } 599 600 // align returns the result of rounding x up to a multiple of n. 601 // n must be a power of two. 602 func align(x, n uintptr) uintptr { 603 return (x + n - 1) &^ (n - 1) 604 } 605 606 // callMethod is the call implementation used by a function returned 607 // by makeMethodValue (used by v.Method(i).Interface()). 608 // It is a streamlined version of the usual reflect call: the caller has 609 // already laid out the argument frame for us, so we don't have 610 // to deal with individual Values for each argument. 611 // It is in this file so that it can be next to the two similar functions above. 612 // The remainder of the makeMethodValue implementation is in makefunc.go. 613 // 614 // NOTE: This function must be marked as a "wrapper" in the generated code, 615 // so that the linker can make it work correctly for panic and recover. 616 // The gc compilers know to do that for the name "reflect.callMethod". 617 func callMethod(ctxt *methodValue, frame unsafe.Pointer) { 618 rcvr := ctxt.rcvr 619 rcvrtype, t, fn := methodReceiver("call", rcvr, ctxt.method) 620 frametype, argSize, retOffset, _, framePool := funcLayout(t, rcvrtype) 621 622 // Make a new frame that is one word bigger so we can store the receiver. 623 args := framePool.Get().(unsafe.Pointer) 624 625 // Copy in receiver and rest of args. 626 storeRcvr(rcvr, args) 627 typedmemmovepartial(frametype, unsafe.Pointer(uintptr(args)+ptrSize), frame, ptrSize, argSize-ptrSize) 628 629 // Call. 630 call(frametype, fn, args, uint32(frametype.size), uint32(retOffset)) 631 632 // Copy return values. On amd64p32, the beginning of return values 633 // is 64-bit aligned, so the caller's frame layout (which doesn't have 634 // a receiver) is different from the layout of the fn call, which has 635 // a receiver. 636 // Ignore any changes to args and just copy return values. 637 callerRetOffset := retOffset - ptrSize 638 if runtime.GOARCH == "amd64p32" { 639 callerRetOffset = align(argSize-ptrSize, 8) 640 } 641 typedmemmovepartial(frametype, 642 unsafe.Pointer(uintptr(frame)+callerRetOffset), 643 unsafe.Pointer(uintptr(args)+retOffset), 644 retOffset, 645 frametype.size-retOffset) 646 647 memclr(args, frametype.size) 648 framePool.Put(args) 649 } 650 651 // funcName returns the name of f, for use in error messages. 652 func funcName(f func([]Value) []Value) string { 653 pc := *(*uintptr)(unsafe.Pointer(&f)) 654 rf := runtime.FuncForPC(pc) 655 if rf != nil { 656 return rf.Name() 657 } 658 return "closure" 659 } 660 661 // Cap returns v's capacity. 662 // It panics if v's Kind is not Array, Chan, or Slice. 663 func (v Value) Cap() int { 664 k := v.kind() 665 switch k { 666 case Array: 667 return v.typ.Len() 668 case Chan: 669 return chancap(v.pointer()) 670 case Slice: 671 // Slice is always bigger than a word; assume flagIndir. 672 return (*sliceHeader)(v.ptr).Cap 673 } 674 panic(&ValueError{"reflect.Value.Cap", v.kind()}) 675 } 676 677 // Close closes the channel v. 678 // It panics if v's Kind is not Chan. 679 func (v Value) Close() { 680 v.mustBe(Chan) 681 v.mustBeExported() 682 chanclose(v.pointer()) 683 } 684 685 // Complex returns v's underlying value, as a complex128. 686 // It panics if v's Kind is not Complex64 or Complex128 687 func (v Value) Complex() complex128 { 688 k := v.kind() 689 switch k { 690 case Complex64: 691 return complex128(*(*complex64)(v.ptr)) 692 case Complex128: 693 return *(*complex128)(v.ptr) 694 } 695 panic(&ValueError{"reflect.Value.Complex", v.kind()}) 696 } 697 698 // Elem returns the value that the interface v contains 699 // or that the pointer v points to. 700 // It panics if v's Kind is not Interface or Ptr. 701 // It returns the zero Value if v is nil. 702 func (v Value) Elem() Value { 703 k := v.kind() 704 switch k { 705 case Interface: 706 var eface interface{} 707 if v.typ.NumMethod() == 0 { 708 eface = *(*interface{})(v.ptr) 709 } else { 710 eface = (interface{})(*(*interface { 711 M() 712 })(v.ptr)) 713 } 714 x := unpackEface(eface) 715 if x.flag != 0 { 716 x.flag |= v.flag & flagRO 717 } 718 return x 719 case Ptr: 720 ptr := v.ptr 721 if v.flag&flagIndir != 0 { 722 ptr = *(*unsafe.Pointer)(ptr) 723 } 724 // The returned value's address is v's value. 725 if ptr == nil { 726 return Value{} 727 } 728 tt := (*ptrType)(unsafe.Pointer(v.typ)) 729 typ := tt.elem 730 fl := v.flag&flagRO | flagIndir | flagAddr 731 fl |= flag(typ.Kind()) 732 return Value{typ, ptr, fl} 733 } 734 panic(&ValueError{"reflect.Value.Elem", v.kind()}) 735 } 736 737 // Field returns the i'th field of the struct v. 738 // It panics if v's Kind is not Struct or i is out of range. 739 func (v Value) Field(i int) Value { 740 if v.kind() != Struct { 741 panic(&ValueError{"reflect.Value.Field", v.kind()}) 742 } 743 tt := (*structType)(unsafe.Pointer(v.typ)) 744 if uint(i) >= uint(len(tt.fields)) { 745 panic("reflect: Field index out of range") 746 } 747 field := &tt.fields[i] 748 typ := field.typ 749 750 // Inherit permission bits from v, but clear flagEmbedRO. 751 fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind()) 752 // Using an unexported field forces flagRO. 753 if !field.name.isExported() { 754 if field.name.name() == "" { 755 fl |= flagEmbedRO 756 } else { 757 fl |= flagStickyRO 758 } 759 } 760 // Either flagIndir is set and v.ptr points at struct, 761 // or flagIndir is not set and v.ptr is the actual struct data. 762 // In the former case, we want v.ptr + offset. 763 // In the latter case, we must have field.offset = 0, 764 // so v.ptr + field.offset is still okay. 765 ptr := unsafe.Pointer(uintptr(v.ptr) + field.offset) 766 return Value{typ, ptr, fl} 767 } 768 769 // FieldByIndex returns the nested field corresponding to index. 770 // It panics if v's Kind is not struct. 771 func (v Value) FieldByIndex(index []int) Value { 772 if len(index) == 1 { 773 return v.Field(index[0]) 774 } 775 v.mustBe(Struct) 776 for i, x := range index { 777 if i > 0 { 778 if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct { 779 if v.IsNil() { 780 panic("reflect: indirection through nil pointer to embedded struct") 781 } 782 v = v.Elem() 783 } 784 } 785 v = v.Field(x) 786 } 787 return v 788 } 789 790 // FieldByName returns the struct field with the given name. 791 // It returns the zero Value if no field was found. 792 // It panics if v's Kind is not struct. 793 func (v Value) FieldByName(name string) Value { 794 v.mustBe(Struct) 795 if f, ok := v.typ.FieldByName(name); ok { 796 return v.FieldByIndex(f.Index) 797 } 798 return Value{} 799 } 800 801 // FieldByNameFunc returns the struct field with a name 802 // that satisfies the match function. 803 // It panics if v's Kind is not struct. 804 // It returns the zero Value if no field was found. 805 func (v Value) FieldByNameFunc(match func(string) bool) Value { 806 if f, ok := v.typ.FieldByNameFunc(match); ok { 807 return v.FieldByIndex(f.Index) 808 } 809 return Value{} 810 } 811 812 // Float returns v's underlying value, as a float64. 813 // It panics if v's Kind is not Float32 or Float64 814 func (v Value) Float() float64 { 815 k := v.kind() 816 switch k { 817 case Float32: 818 return float64(*(*float32)(v.ptr)) 819 case Float64: 820 return *(*float64)(v.ptr) 821 } 822 panic(&ValueError{"reflect.Value.Float", v.kind()}) 823 } 824 825 var uint8Type = TypeOf(uint8(0)).(*rtype) 826 827 // Index returns v's i'th element. 828 // It panics if v's Kind is not Array, Slice, or String or i is out of range. 829 func (v Value) Index(i int) Value { 830 switch v.kind() { 831 case Array: 832 tt := (*arrayType)(unsafe.Pointer(v.typ)) 833 if uint(i) >= uint(tt.len) { 834 panic("reflect: array index out of range") 835 } 836 typ := tt.elem 837 offset := uintptr(i) * typ.size 838 839 // Either flagIndir is set and v.ptr points at array, 840 // or flagIndir is not set and v.ptr is the actual array data. 841 // In the former case, we want v.ptr + offset. 842 // In the latter case, we must be doing Index(0), so offset = 0, 843 // so v.ptr + offset is still okay. 844 val := unsafe.Pointer(uintptr(v.ptr) + offset) 845 fl := v.flag&(flagRO|flagIndir|flagAddr) | flag(typ.Kind()) // bits same as overall array 846 return Value{typ, val, fl} 847 848 case Slice: 849 // Element flag same as Elem of Ptr. 850 // Addressable, indirect, possibly read-only. 851 s := (*sliceHeader)(v.ptr) 852 if uint(i) >= uint(s.Len) { 853 panic("reflect: slice index out of range") 854 } 855 tt := (*sliceType)(unsafe.Pointer(v.typ)) 856 typ := tt.elem 857 val := arrayAt(s.Data, i, typ.size) 858 fl := flagAddr | flagIndir | v.flag&flagRO | flag(typ.Kind()) 859 return Value{typ, val, fl} 860 861 case String: 862 s := (*stringHeader)(v.ptr) 863 if uint(i) >= uint(s.Len) { 864 panic("reflect: string index out of range") 865 } 866 p := arrayAt(s.Data, i, 1) 867 fl := v.flag&flagRO | flag(Uint8) | flagIndir 868 return Value{uint8Type, p, fl} 869 } 870 panic(&ValueError{"reflect.Value.Index", v.kind()}) 871 } 872 873 // Int returns v's underlying value, as an int64. 874 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64. 875 func (v Value) Int() int64 { 876 k := v.kind() 877 p := v.ptr 878 switch k { 879 case Int: 880 return int64(*(*int)(p)) 881 case Int8: 882 return int64(*(*int8)(p)) 883 case Int16: 884 return int64(*(*int16)(p)) 885 case Int32: 886 return int64(*(*int32)(p)) 887 case Int64: 888 return *(*int64)(p) 889 } 890 panic(&ValueError{"reflect.Value.Int", v.kind()}) 891 } 892 893 // CanInterface reports whether Interface can be used without panicking. 894 func (v Value) CanInterface() bool { 895 if v.flag == 0 { 896 panic(&ValueError{"reflect.Value.CanInterface", Invalid}) 897 } 898 return v.flag&flagRO == 0 899 } 900 901 // Interface returns v's current value as an interface{}. 902 // It is equivalent to: 903 // var i interface{} = (v's underlying value) 904 // It panics if the Value was obtained by accessing 905 // unexported struct fields. 906 func (v Value) Interface() (i interface{}) { 907 return valueInterface(v, true) 908 } 909 910 func valueInterface(v Value, safe bool) interface{} { 911 if v.flag == 0 { 912 panic(&ValueError{"reflect.Value.Interface", 0}) 913 } 914 if safe && v.flag&flagRO != 0 { 915 // Do not allow access to unexported values via Interface, 916 // because they might be pointers that should not be 917 // writable or methods or function that should not be callable. 918 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method") 919 } 920 if v.flag&flagMethod != 0 { 921 v = makeMethodValue("Interface", v) 922 } 923 924 if v.kind() == Interface { 925 // Special case: return the element inside the interface. 926 // Empty interface has one layout, all interfaces with 927 // methods have a second layout. 928 if v.NumMethod() == 0 { 929 return *(*interface{})(v.ptr) 930 } 931 return *(*interface { 932 M() 933 })(v.ptr) 934 } 935 936 // TODO: pass safe to packEface so we don't need to copy if safe==true? 937 return packEface(v) 938 } 939 940 // InterfaceData returns the interface v's value as a uintptr pair. 941 // It panics if v's Kind is not Interface. 942 func (v Value) InterfaceData() [2]uintptr { 943 // TODO: deprecate this 944 v.mustBe(Interface) 945 // We treat this as a read operation, so we allow 946 // it even for unexported data, because the caller 947 // has to import "unsafe" to turn it into something 948 // that can be abused. 949 // Interface value is always bigger than a word; assume flagIndir. 950 return *(*[2]uintptr)(v.ptr) 951 } 952 953 // IsNil reports whether its argument v is nil. The argument must be 954 // a chan, func, interface, map, pointer, or slice value; if it is 955 // not, IsNil panics. Note that IsNil is not always equivalent to a 956 // regular comparison with nil in Go. For example, if v was created 957 // by calling ValueOf with an uninitialized interface variable i, 958 // i==nil will be true but v.IsNil will panic as v will be the zero 959 // Value. 960 func (v Value) IsNil() bool { 961 k := v.kind() 962 switch k { 963 case Chan, Func, Map, Ptr: 964 if v.flag&flagMethod != 0 { 965 return false 966 } 967 ptr := v.ptr 968 if v.flag&flagIndir != 0 { 969 ptr = *(*unsafe.Pointer)(ptr) 970 } 971 return ptr == nil 972 case Interface, Slice: 973 // Both interface and slice are nil if first word is 0. 974 // Both are always bigger than a word; assume flagIndir. 975 return *(*unsafe.Pointer)(v.ptr) == nil 976 } 977 panic(&ValueError{"reflect.Value.IsNil", v.kind()}) 978 } 979 980 // IsValid reports whether v represents a value. 981 // It returns false if v is the zero Value. 982 // If IsValid returns false, all other methods except String panic. 983 // Most functions and methods never return an invalid value. 984 // If one does, its documentation states the conditions explicitly. 985 func (v Value) IsValid() bool { 986 return v.flag != 0 987 } 988 989 // Kind returns v's Kind. 990 // If v is the zero Value (IsValid returns false), Kind returns Invalid. 991 func (v Value) Kind() Kind { 992 return v.kind() 993 } 994 995 // Len returns v's length. 996 // It panics if v's Kind is not Array, Chan, Map, Slice, or String. 997 func (v Value) Len() int { 998 k := v.kind() 999 switch k { 1000 case Array: 1001 tt := (*arrayType)(unsafe.Pointer(v.typ)) 1002 return int(tt.len) 1003 case Chan: 1004 return chanlen(v.pointer()) 1005 case Map: 1006 return maplen(v.pointer()) 1007 case Slice: 1008 // Slice is bigger than a word; assume flagIndir. 1009 return (*sliceHeader)(v.ptr).Len 1010 case String: 1011 // String is bigger than a word; assume flagIndir. 1012 return (*stringHeader)(v.ptr).Len 1013 } 1014 panic(&ValueError{"reflect.Value.Len", v.kind()}) 1015 } 1016 1017 // MapIndex returns the value associated with key in the map v. 1018 // It panics if v's Kind is not Map. 1019 // It returns the zero Value if key is not found in the map or if v represents a nil map. 1020 // As in Go, the key's value must be assignable to the map's key type. 1021 func (v Value) MapIndex(key Value) Value { 1022 v.mustBe(Map) 1023 tt := (*mapType)(unsafe.Pointer(v.typ)) 1024 1025 // Do not require key to be exported, so that DeepEqual 1026 // and other programs can use all the keys returned by 1027 // MapKeys as arguments to MapIndex. If either the map 1028 // or the key is unexported, though, the result will be 1029 // considered unexported. This is consistent with the 1030 // behavior for structs, which allow read but not write 1031 // of unexported fields. 1032 key = key.assignTo("reflect.Value.MapIndex", tt.key, nil) 1033 1034 var k unsafe.Pointer 1035 if key.flag&flagIndir != 0 { 1036 k = key.ptr 1037 } else { 1038 k = unsafe.Pointer(&key.ptr) 1039 } 1040 e := mapaccess(v.typ, v.pointer(), k) 1041 if e == nil { 1042 return Value{} 1043 } 1044 typ := tt.elem 1045 fl := (v.flag | key.flag) & flagRO 1046 fl |= flag(typ.Kind()) 1047 if ifaceIndir(typ) { 1048 // Copy result so future changes to the map 1049 // won't change the underlying value. 1050 c := unsafe_New(typ) 1051 typedmemmove(typ, c, e) 1052 return Value{typ, c, fl | flagIndir} 1053 } else { 1054 return Value{typ, *(*unsafe.Pointer)(e), fl} 1055 } 1056 } 1057 1058 // MapKeys returns a slice containing all the keys present in the map, 1059 // in unspecified order. 1060 // It panics if v's Kind is not Map. 1061 // It returns an empty slice if v represents a nil map. 1062 func (v Value) MapKeys() []Value { 1063 v.mustBe(Map) 1064 tt := (*mapType)(unsafe.Pointer(v.typ)) 1065 keyType := tt.key 1066 1067 fl := v.flag&flagRO | flag(keyType.Kind()) 1068 1069 m := v.pointer() 1070 mlen := int(0) 1071 if m != nil { 1072 mlen = maplen(m) 1073 } 1074 it := mapiterinit(v.typ, m) 1075 a := make([]Value, mlen) 1076 var i int 1077 for i = 0; i < len(a); i++ { 1078 key := mapiterkey(it) 1079 if key == nil { 1080 // Someone deleted an entry from the map since we 1081 // called maplen above. It's a data race, but nothing 1082 // we can do about it. 1083 break 1084 } 1085 if ifaceIndir(keyType) { 1086 // Copy result so future changes to the map 1087 // won't change the underlying value. 1088 c := unsafe_New(keyType) 1089 typedmemmove(keyType, c, key) 1090 a[i] = Value{keyType, c, fl | flagIndir} 1091 } else { 1092 a[i] = Value{keyType, *(*unsafe.Pointer)(key), fl} 1093 } 1094 mapiternext(it) 1095 } 1096 return a[:i] 1097 } 1098 1099 // Method returns a function value corresponding to v's i'th method. 1100 // The arguments to a Call on the returned function should not include 1101 // a receiver; the returned function will always use v as the receiver. 1102 // Method panics if i is out of range or if v is a nil interface value. 1103 func (v Value) Method(i int) Value { 1104 if v.typ == nil { 1105 panic(&ValueError{"reflect.Value.Method", Invalid}) 1106 } 1107 if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) { 1108 panic("reflect: Method index out of range") 1109 } 1110 if v.typ.Kind() == Interface && v.IsNil() { 1111 panic("reflect: Method on nil interface value") 1112 } 1113 fl := v.flag & (flagStickyRO | flagIndir) // Clear flagEmbedRO 1114 fl |= flag(Func) 1115 fl |= flag(i)<<flagMethodShift | flagMethod 1116 return Value{v.typ, v.ptr, fl} 1117 } 1118 1119 // NumMethod returns the number of methods in the value's method set. 1120 func (v Value) NumMethod() int { 1121 if v.typ == nil { 1122 panic(&ValueError{"reflect.Value.NumMethod", Invalid}) 1123 } 1124 if v.flag&flagMethod != 0 { 1125 return 0 1126 } 1127 return v.typ.NumMethod() 1128 } 1129 1130 // MethodByName returns a function value corresponding to the method 1131 // of v with the given name. 1132 // The arguments to a Call on the returned function should not include 1133 // a receiver; the returned function will always use v as the receiver. 1134 // It returns the zero Value if no method was found. 1135 func (v Value) MethodByName(name string) Value { 1136 if v.typ == nil { 1137 panic(&ValueError{"reflect.Value.MethodByName", Invalid}) 1138 } 1139 if v.flag&flagMethod != 0 { 1140 return Value{} 1141 } 1142 m, ok := v.typ.MethodByName(name) 1143 if !ok { 1144 return Value{} 1145 } 1146 return v.Method(m.Index) 1147 } 1148 1149 // NumField returns the number of fields in the struct v. 1150 // It panics if v's Kind is not Struct. 1151 func (v Value) NumField() int { 1152 v.mustBe(Struct) 1153 tt := (*structType)(unsafe.Pointer(v.typ)) 1154 return len(tt.fields) 1155 } 1156 1157 // OverflowComplex reports whether the complex128 x cannot be represented by v's type. 1158 // It panics if v's Kind is not Complex64 or Complex128. 1159 func (v Value) OverflowComplex(x complex128) bool { 1160 k := v.kind() 1161 switch k { 1162 case Complex64: 1163 return overflowFloat32(real(x)) || overflowFloat32(imag(x)) 1164 case Complex128: 1165 return false 1166 } 1167 panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()}) 1168 } 1169 1170 // OverflowFloat reports whether the float64 x cannot be represented by v's type. 1171 // It panics if v's Kind is not Float32 or Float64. 1172 func (v Value) OverflowFloat(x float64) bool { 1173 k := v.kind() 1174 switch k { 1175 case Float32: 1176 return overflowFloat32(x) 1177 case Float64: 1178 return false 1179 } 1180 panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()}) 1181 } 1182 1183 func overflowFloat32(x float64) bool { 1184 if x < 0 { 1185 x = -x 1186 } 1187 return math.MaxFloat32 < x && x <= math.MaxFloat64 1188 } 1189 1190 // OverflowInt reports whether the int64 x cannot be represented by v's type. 1191 // It panics if v's Kind is not Int, Int8, int16, Int32, or Int64. 1192 func (v Value) OverflowInt(x int64) bool { 1193 k := v.kind() 1194 switch k { 1195 case Int, Int8, Int16, Int32, Int64: 1196 bitSize := v.typ.size * 8 1197 trunc := (x << (64 - bitSize)) >> (64 - bitSize) 1198 return x != trunc 1199 } 1200 panic(&ValueError{"reflect.Value.OverflowInt", v.kind()}) 1201 } 1202 1203 // OverflowUint reports whether the uint64 x cannot be represented by v's type. 1204 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. 1205 func (v Value) OverflowUint(x uint64) bool { 1206 k := v.kind() 1207 switch k { 1208 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64: 1209 bitSize := v.typ.size * 8 1210 trunc := (x << (64 - bitSize)) >> (64 - bitSize) 1211 return x != trunc 1212 } 1213 panic(&ValueError{"reflect.Value.OverflowUint", v.kind()}) 1214 } 1215 1216 // Pointer returns v's value as a uintptr. 1217 // It returns uintptr instead of unsafe.Pointer so that 1218 // code using reflect cannot obtain unsafe.Pointers 1219 // without importing the unsafe package explicitly. 1220 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer. 1221 // 1222 // If v's Kind is Func, the returned pointer is an underlying 1223 // code pointer, but not necessarily enough to identify a 1224 // single function uniquely. The only guarantee is that the 1225 // result is zero if and only if v is a nil func Value. 1226 // 1227 // If v's Kind is Slice, the returned pointer is to the first 1228 // element of the slice. If the slice is nil the returned value 1229 // is 0. If the slice is empty but non-nil the return value is non-zero. 1230 func (v Value) Pointer() uintptr { 1231 // TODO: deprecate 1232 k := v.kind() 1233 switch k { 1234 case Chan, Map, Ptr, UnsafePointer: 1235 return uintptr(v.pointer()) 1236 case Func: 1237 if v.flag&flagMethod != 0 { 1238 // As the doc comment says, the returned pointer is an 1239 // underlying code pointer but not necessarily enough to 1240 // identify a single function uniquely. All method expressions 1241 // created via reflect have the same underlying code pointer, 1242 // so their Pointers are equal. The function used here must 1243 // match the one used in makeMethodValue. 1244 f := methodValueCall 1245 return **(**uintptr)(unsafe.Pointer(&f)) 1246 } 1247 p := v.pointer() 1248 // Non-nil func value points at data block. 1249 // First word of data block is actual code. 1250 if p != nil { 1251 p = *(*unsafe.Pointer)(p) 1252 } 1253 return uintptr(p) 1254 1255 case Slice: 1256 return (*SliceHeader)(v.ptr).Data 1257 } 1258 panic(&ValueError{"reflect.Value.Pointer", v.kind()}) 1259 } 1260 1261 // Recv receives and returns a value from the channel v. 1262 // It panics if v's Kind is not Chan. 1263 // The receive blocks until a value is ready. 1264 // The boolean value ok is true if the value x corresponds to a send 1265 // on the channel, false if it is a zero value received because the channel is closed. 1266 func (v Value) Recv() (x Value, ok bool) { 1267 v.mustBe(Chan) 1268 v.mustBeExported() 1269 return v.recv(false) 1270 } 1271 1272 // internal recv, possibly non-blocking (nb). 1273 // v is known to be a channel. 1274 func (v Value) recv(nb bool) (val Value, ok bool) { 1275 tt := (*chanType)(unsafe.Pointer(v.typ)) 1276 if ChanDir(tt.dir)&RecvDir == 0 { 1277 panic("reflect: recv on send-only channel") 1278 } 1279 t := tt.elem 1280 val = Value{t, nil, flag(t.Kind())} 1281 var p unsafe.Pointer 1282 if ifaceIndir(t) { 1283 p = unsafe_New(t) 1284 val.ptr = p 1285 val.flag |= flagIndir 1286 } else { 1287 p = unsafe.Pointer(&val.ptr) 1288 } 1289 selected, ok := chanrecv(v.typ, v.pointer(), nb, p) 1290 if !selected { 1291 val = Value{} 1292 } 1293 return 1294 } 1295 1296 // Send sends x on the channel v. 1297 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type. 1298 // As in Go, x's value must be assignable to the channel's element type. 1299 func (v Value) Send(x Value) { 1300 v.mustBe(Chan) 1301 v.mustBeExported() 1302 v.send(x, false) 1303 } 1304 1305 // internal send, possibly non-blocking. 1306 // v is known to be a channel. 1307 func (v Value) send(x Value, nb bool) (selected bool) { 1308 tt := (*chanType)(unsafe.Pointer(v.typ)) 1309 if ChanDir(tt.dir)&SendDir == 0 { 1310 panic("reflect: send on recv-only channel") 1311 } 1312 x.mustBeExported() 1313 x = x.assignTo("reflect.Value.Send", tt.elem, nil) 1314 var p unsafe.Pointer 1315 if x.flag&flagIndir != 0 { 1316 p = x.ptr 1317 } else { 1318 p = unsafe.Pointer(&x.ptr) 1319 } 1320 return chansend(v.typ, v.pointer(), p, nb) 1321 } 1322 1323 // Set assigns x to the value v. 1324 // It panics if CanSet returns false. 1325 // As in Go, x's value must be assignable to v's type. 1326 func (v Value) Set(x Value) { 1327 v.mustBeAssignable() 1328 x.mustBeExported() // do not let unexported x leak 1329 var target unsafe.Pointer 1330 if v.kind() == Interface { 1331 target = v.ptr 1332 } 1333 x = x.assignTo("reflect.Set", v.typ, target) 1334 if x.flag&flagIndir != 0 { 1335 typedmemmove(v.typ, v.ptr, x.ptr) 1336 } else { 1337 *(*unsafe.Pointer)(v.ptr) = x.ptr 1338 } 1339 } 1340 1341 // SetBool sets v's underlying value. 1342 // It panics if v's Kind is not Bool or if CanSet() is false. 1343 func (v Value) SetBool(x bool) { 1344 v.mustBeAssignable() 1345 v.mustBe(Bool) 1346 *(*bool)(v.ptr) = x 1347 } 1348 1349 // SetBytes sets v's underlying value. 1350 // It panics if v's underlying value is not a slice of bytes. 1351 func (v Value) SetBytes(x []byte) { 1352 v.mustBeAssignable() 1353 v.mustBe(Slice) 1354 if v.typ.Elem().Kind() != Uint8 { 1355 panic("reflect.Value.SetBytes of non-byte slice") 1356 } 1357 *(*[]byte)(v.ptr) = x 1358 } 1359 1360 // setRunes sets v's underlying value. 1361 // It panics if v's underlying value is not a slice of runes (int32s). 1362 func (v Value) setRunes(x []rune) { 1363 v.mustBeAssignable() 1364 v.mustBe(Slice) 1365 if v.typ.Elem().Kind() != Int32 { 1366 panic("reflect.Value.setRunes of non-rune slice") 1367 } 1368 *(*[]rune)(v.ptr) = x 1369 } 1370 1371 // SetComplex sets v's underlying value to x. 1372 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false. 1373 func (v Value) SetComplex(x complex128) { 1374 v.mustBeAssignable() 1375 switch k := v.kind(); k { 1376 default: 1377 panic(&ValueError{"reflect.Value.SetComplex", v.kind()}) 1378 case Complex64: 1379 *(*complex64)(v.ptr) = complex64(x) 1380 case Complex128: 1381 *(*complex128)(v.ptr) = x 1382 } 1383 } 1384 1385 // SetFloat sets v's underlying value to x. 1386 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false. 1387 func (v Value) SetFloat(x float64) { 1388 v.mustBeAssignable() 1389 switch k := v.kind(); k { 1390 default: 1391 panic(&ValueError{"reflect.Value.SetFloat", v.kind()}) 1392 case Float32: 1393 *(*float32)(v.ptr) = float32(x) 1394 case Float64: 1395 *(*float64)(v.ptr) = x 1396 } 1397 } 1398 1399 // SetInt sets v's underlying value to x. 1400 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false. 1401 func (v Value) SetInt(x int64) { 1402 v.mustBeAssignable() 1403 switch k := v.kind(); k { 1404 default: 1405 panic(&ValueError{"reflect.Value.SetInt", v.kind()}) 1406 case Int: 1407 *(*int)(v.ptr) = int(x) 1408 case Int8: 1409 *(*int8)(v.ptr) = int8(x) 1410 case Int16: 1411 *(*int16)(v.ptr) = int16(x) 1412 case Int32: 1413 *(*int32)(v.ptr) = int32(x) 1414 case Int64: 1415 *(*int64)(v.ptr) = x 1416 } 1417 } 1418 1419 // SetLen sets v's length to n. 1420 // It panics if v's Kind is not Slice or if n is negative or 1421 // greater than the capacity of the slice. 1422 func (v Value) SetLen(n int) { 1423 v.mustBeAssignable() 1424 v.mustBe(Slice) 1425 s := (*sliceHeader)(v.ptr) 1426 if uint(n) > uint(s.Cap) { 1427 panic("reflect: slice length out of range in SetLen") 1428 } 1429 s.Len = n 1430 } 1431 1432 // SetCap sets v's capacity to n. 1433 // It panics if v's Kind is not Slice or if n is smaller than the length or 1434 // greater than the capacity of the slice. 1435 func (v Value) SetCap(n int) { 1436 v.mustBeAssignable() 1437 v.mustBe(Slice) 1438 s := (*sliceHeader)(v.ptr) 1439 if n < s.Len || n > s.Cap { 1440 panic("reflect: slice capacity out of range in SetCap") 1441 } 1442 s.Cap = n 1443 } 1444 1445 // SetMapIndex sets the value associated with key in the map v to val. 1446 // It panics if v's Kind is not Map. 1447 // If val is the zero Value, SetMapIndex deletes the key from the map. 1448 // Otherwise if v holds a nil map, SetMapIndex will panic. 1449 // As in Go, key's value must be assignable to the map's key type, 1450 // and val's value must be assignable to the map's value type. 1451 func (v Value) SetMapIndex(key, val Value) { 1452 v.mustBe(Map) 1453 v.mustBeExported() 1454 key.mustBeExported() 1455 tt := (*mapType)(unsafe.Pointer(v.typ)) 1456 key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil) 1457 var k unsafe.Pointer 1458 if key.flag&flagIndir != 0 { 1459 k = key.ptr 1460 } else { 1461 k = unsafe.Pointer(&key.ptr) 1462 } 1463 if val.typ == nil { 1464 mapdelete(v.typ, v.pointer(), k) 1465 return 1466 } 1467 val.mustBeExported() 1468 val = val.assignTo("reflect.Value.SetMapIndex", tt.elem, nil) 1469 var e unsafe.Pointer 1470 if val.flag&flagIndir != 0 { 1471 e = val.ptr 1472 } else { 1473 e = unsafe.Pointer(&val.ptr) 1474 } 1475 mapassign(v.typ, v.pointer(), k, e) 1476 } 1477 1478 // SetUint sets v's underlying value to x. 1479 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false. 1480 func (v Value) SetUint(x uint64) { 1481 v.mustBeAssignable() 1482 switch k := v.kind(); k { 1483 default: 1484 panic(&ValueError{"reflect.Value.SetUint", v.kind()}) 1485 case Uint: 1486 *(*uint)(v.ptr) = uint(x) 1487 case Uint8: 1488 *(*uint8)(v.ptr) = uint8(x) 1489 case Uint16: 1490 *(*uint16)(v.ptr) = uint16(x) 1491 case Uint32: 1492 *(*uint32)(v.ptr) = uint32(x) 1493 case Uint64: 1494 *(*uint64)(v.ptr) = x 1495 case Uintptr: 1496 *(*uintptr)(v.ptr) = uintptr(x) 1497 } 1498 } 1499 1500 // SetPointer sets the unsafe.Pointer value v to x. 1501 // It panics if v's Kind is not UnsafePointer. 1502 func (v Value) SetPointer(x unsafe.Pointer) { 1503 v.mustBeAssignable() 1504 v.mustBe(UnsafePointer) 1505 *(*unsafe.Pointer)(v.ptr) = x 1506 } 1507 1508 // SetString sets v's underlying value to x. 1509 // It panics if v's Kind is not String or if CanSet() is false. 1510 func (v Value) SetString(x string) { 1511 v.mustBeAssignable() 1512 v.mustBe(String) 1513 *(*string)(v.ptr) = x 1514 } 1515 1516 // Slice returns v[i:j]. 1517 // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array, 1518 // or if the indexes are out of bounds. 1519 func (v Value) Slice(i, j int) Value { 1520 var ( 1521 cap int 1522 typ *sliceType 1523 base unsafe.Pointer 1524 ) 1525 switch kind := v.kind(); kind { 1526 default: 1527 panic(&ValueError{"reflect.Value.Slice", v.kind()}) 1528 1529 case Array: 1530 if v.flag&flagAddr == 0 { 1531 panic("reflect.Value.Slice: slice of unaddressable array") 1532 } 1533 tt := (*arrayType)(unsafe.Pointer(v.typ)) 1534 cap = int(tt.len) 1535 typ = (*sliceType)(unsafe.Pointer(tt.slice)) 1536 base = v.ptr 1537 1538 case Slice: 1539 typ = (*sliceType)(unsafe.Pointer(v.typ)) 1540 s := (*sliceHeader)(v.ptr) 1541 base = s.Data 1542 cap = s.Cap 1543 1544 case String: 1545 s := (*stringHeader)(v.ptr) 1546 if i < 0 || j < i || j > s.Len { 1547 panic("reflect.Value.Slice: string slice index out of bounds") 1548 } 1549 t := stringHeader{arrayAt(s.Data, i, 1), j - i} 1550 return Value{v.typ, unsafe.Pointer(&t), v.flag} 1551 } 1552 1553 if i < 0 || j < i || j > cap { 1554 panic("reflect.Value.Slice: slice index out of bounds") 1555 } 1556 1557 // Declare slice so that gc can see the base pointer in it. 1558 var x []unsafe.Pointer 1559 1560 // Reinterpret as *sliceHeader to edit. 1561 s := (*sliceHeader)(unsafe.Pointer(&x)) 1562 s.Len = j - i 1563 s.Cap = cap - i 1564 if cap-i > 0 { 1565 s.Data = arrayAt(base, i, typ.elem.Size()) 1566 } else { 1567 // do not advance pointer, to avoid pointing beyond end of slice 1568 s.Data = base 1569 } 1570 1571 fl := v.flag&flagRO | flagIndir | flag(Slice) 1572 return Value{typ.common(), unsafe.Pointer(&x), fl} 1573 } 1574 1575 // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k]. 1576 // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array, 1577 // or if the indexes are out of bounds. 1578 func (v Value) Slice3(i, j, k int) Value { 1579 var ( 1580 cap int 1581 typ *sliceType 1582 base unsafe.Pointer 1583 ) 1584 switch kind := v.kind(); kind { 1585 default: 1586 panic(&ValueError{"reflect.Value.Slice3", v.kind()}) 1587 1588 case Array: 1589 if v.flag&flagAddr == 0 { 1590 panic("reflect.Value.Slice3: slice of unaddressable array") 1591 } 1592 tt := (*arrayType)(unsafe.Pointer(v.typ)) 1593 cap = int(tt.len) 1594 typ = (*sliceType)(unsafe.Pointer(tt.slice)) 1595 base = v.ptr 1596 1597 case Slice: 1598 typ = (*sliceType)(unsafe.Pointer(v.typ)) 1599 s := (*sliceHeader)(v.ptr) 1600 base = s.Data 1601 cap = s.Cap 1602 } 1603 1604 if i < 0 || j < i || k < j || k > cap { 1605 panic("reflect.Value.Slice3: slice index out of bounds") 1606 } 1607 1608 // Declare slice so that the garbage collector 1609 // can see the base pointer in it. 1610 var x []unsafe.Pointer 1611 1612 // Reinterpret as *sliceHeader to edit. 1613 s := (*sliceHeader)(unsafe.Pointer(&x)) 1614 s.Len = j - i 1615 s.Cap = k - i 1616 if k-i > 0 { 1617 s.Data = arrayAt(base, i, typ.elem.Size()) 1618 } else { 1619 // do not advance pointer, to avoid pointing beyond end of slice 1620 s.Data = base 1621 } 1622 1623 fl := v.flag&flagRO | flagIndir | flag(Slice) 1624 return Value{typ.common(), unsafe.Pointer(&x), fl} 1625 } 1626 1627 // String returns the string v's underlying value, as a string. 1628 // String is a special case because of Go's String method convention. 1629 // Unlike the other getters, it does not panic if v's Kind is not String. 1630 // Instead, it returns a string of the form "<T value>" where T is v's type. 1631 // The fmt package treats Values specially. It does not call their String 1632 // method implicitly but instead prints the concrete values they hold. 1633 func (v Value) String() string { 1634 switch k := v.kind(); k { 1635 case Invalid: 1636 return "<invalid Value>" 1637 case String: 1638 return *(*string)(v.ptr) 1639 } 1640 // If you call String on a reflect.Value of other type, it's better to 1641 // print something than to panic. Useful in debugging. 1642 return "<" + v.Type().String() + " Value>" 1643 } 1644 1645 // TryRecv attempts to receive a value from the channel v but will not block. 1646 // It panics if v's Kind is not Chan. 1647 // If the receive delivers a value, x is the transferred value and ok is true. 1648 // If the receive cannot finish without blocking, x is the zero Value and ok is false. 1649 // If the channel is closed, x is the zero value for the channel's element type and ok is false. 1650 func (v Value) TryRecv() (x Value, ok bool) { 1651 v.mustBe(Chan) 1652 v.mustBeExported() 1653 return v.recv(true) 1654 } 1655 1656 // TrySend attempts to send x on the channel v but will not block. 1657 // It panics if v's Kind is not Chan. 1658 // It reports whether the value was sent. 1659 // As in Go, x's value must be assignable to the channel's element type. 1660 func (v Value) TrySend(x Value) bool { 1661 v.mustBe(Chan) 1662 v.mustBeExported() 1663 return v.send(x, true) 1664 } 1665 1666 // Type returns v's type. 1667 func (v Value) Type() Type { 1668 f := v.flag 1669 if f == 0 { 1670 panic(&ValueError{"reflect.Value.Type", Invalid}) 1671 } 1672 if f&flagMethod == 0 { 1673 // Easy case 1674 return v.typ 1675 } 1676 1677 // Method value. 1678 // v.typ describes the receiver, not the method type. 1679 i := int(v.flag) >> flagMethodShift 1680 if v.typ.Kind() == Interface { 1681 // Method on interface. 1682 tt := (*interfaceType)(unsafe.Pointer(v.typ)) 1683 if uint(i) >= uint(len(tt.methods)) { 1684 panic("reflect: internal error: invalid method index") 1685 } 1686 m := &tt.methods[i] 1687 return v.typ.typeOff(m.typ) 1688 } 1689 // Method on concrete type. 1690 ut := v.typ.uncommon() 1691 if ut == nil || uint(i) >= uint(ut.mcount) { 1692 panic("reflect: internal error: invalid method index") 1693 } 1694 m := ut.methods()[i] 1695 return v.typ.typeOff(m.mtyp) 1696 } 1697 1698 // Uint returns v's underlying value, as a uint64. 1699 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. 1700 func (v Value) Uint() uint64 { 1701 k := v.kind() 1702 p := v.ptr 1703 switch k { 1704 case Uint: 1705 return uint64(*(*uint)(p)) 1706 case Uint8: 1707 return uint64(*(*uint8)(p)) 1708 case Uint16: 1709 return uint64(*(*uint16)(p)) 1710 case Uint32: 1711 return uint64(*(*uint32)(p)) 1712 case Uint64: 1713 return *(*uint64)(p) 1714 case Uintptr: 1715 return uint64(*(*uintptr)(p)) 1716 } 1717 panic(&ValueError{"reflect.Value.Uint", v.kind()}) 1718 } 1719 1720 // UnsafeAddr returns a pointer to v's data. 1721 // It is for advanced clients that also import the "unsafe" package. 1722 // It panics if v is not addressable. 1723 func (v Value) UnsafeAddr() uintptr { 1724 // TODO: deprecate 1725 if v.typ == nil { 1726 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid}) 1727 } 1728 if v.flag&flagAddr == 0 { 1729 panic("reflect.Value.UnsafeAddr of unaddressable value") 1730 } 1731 return uintptr(v.ptr) 1732 } 1733 1734 // StringHeader is the runtime representation of a string. 1735 // It cannot be used safely or portably and its representation may 1736 // change in a later release. 1737 // Moreover, the Data field is not sufficient to guarantee the data 1738 // it references will not be garbage collected, so programs must keep 1739 // a separate, correctly typed pointer to the underlying data. 1740 type StringHeader struct { 1741 Data uintptr 1742 Len int 1743 } 1744 1745 // stringHeader is a safe version of StringHeader used within this package. 1746 type stringHeader struct { 1747 Data unsafe.Pointer 1748 Len int 1749 } 1750 1751 // SliceHeader is the runtime representation of a slice. 1752 // It cannot be used safely or portably and its representation may 1753 // change in a later release. 1754 // Moreover, the Data field is not sufficient to guarantee the data 1755 // it references will not be garbage collected, so programs must keep 1756 // a separate, correctly typed pointer to the underlying data. 1757 type SliceHeader struct { 1758 Data uintptr 1759 Len int 1760 Cap int 1761 } 1762 1763 // sliceHeader is a safe version of SliceHeader used within this package. 1764 type sliceHeader struct { 1765 Data unsafe.Pointer 1766 Len int 1767 Cap int 1768 } 1769 1770 func typesMustMatch(what string, t1, t2 Type) { 1771 if t1 != t2 { 1772 panic(what + ": " + t1.String() + " != " + t2.String()) 1773 } 1774 } 1775 1776 // arrayAt returns the i-th element of p, a C-array whose elements are 1777 // eltSize wide (in bytes). 1778 func arrayAt(p unsafe.Pointer, i int, eltSize uintptr) unsafe.Pointer { 1779 return unsafe.Pointer(uintptr(p) + uintptr(i)*eltSize) 1780 } 1781 1782 // grow grows the slice s so that it can hold extra more values, allocating 1783 // more capacity if needed. It also returns the old and new slice lengths. 1784 func grow(s Value, extra int) (Value, int, int) { 1785 i0 := s.Len() 1786 i1 := i0 + extra 1787 if i1 < i0 { 1788 panic("reflect.Append: slice overflow") 1789 } 1790 m := s.Cap() 1791 if i1 <= m { 1792 return s.Slice(0, i1), i0, i1 1793 } 1794 if m == 0 { 1795 m = extra 1796 } else { 1797 for m < i1 { 1798 if i0 < 1024 { 1799 m += m 1800 } else { 1801 m += m / 4 1802 } 1803 } 1804 } 1805 t := MakeSlice(s.Type(), i1, m) 1806 Copy(t, s) 1807 return t, i0, i1 1808 } 1809 1810 // Append appends the values x to a slice s and returns the resulting slice. 1811 // As in Go, each x's value must be assignable to the slice's element type. 1812 func Append(s Value, x ...Value) Value { 1813 s.mustBe(Slice) 1814 s, i0, i1 := grow(s, len(x)) 1815 for i, j := i0, 0; i < i1; i, j = i+1, j+1 { 1816 s.Index(i).Set(x[j]) 1817 } 1818 return s 1819 } 1820 1821 // AppendSlice appends a slice t to a slice s and returns the resulting slice. 1822 // The slices s and t must have the same element type. 1823 func AppendSlice(s, t Value) Value { 1824 s.mustBe(Slice) 1825 t.mustBe(Slice) 1826 typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem()) 1827 s, i0, i1 := grow(s, t.Len()) 1828 Copy(s.Slice(i0, i1), t) 1829 return s 1830 } 1831 1832 // Copy copies the contents of src into dst until either 1833 // dst has been filled or src has been exhausted. 1834 // It returns the number of elements copied. 1835 // Dst and src each must have kind Slice or Array, and 1836 // dst and src must have the same element type. 1837 func Copy(dst, src Value) int { 1838 dk := dst.kind() 1839 if dk != Array && dk != Slice { 1840 panic(&ValueError{"reflect.Copy", dk}) 1841 } 1842 if dk == Array { 1843 dst.mustBeAssignable() 1844 } 1845 dst.mustBeExported() 1846 1847 sk := src.kind() 1848 if sk != Array && sk != Slice { 1849 panic(&ValueError{"reflect.Copy", sk}) 1850 } 1851 src.mustBeExported() 1852 1853 de := dst.typ.Elem() 1854 se := src.typ.Elem() 1855 typesMustMatch("reflect.Copy", de, se) 1856 1857 var ds, ss sliceHeader 1858 if dk == Array { 1859 ds.Data = dst.ptr 1860 ds.Len = dst.Len() 1861 ds.Cap = ds.Len 1862 } else { 1863 ds = *(*sliceHeader)(dst.ptr) 1864 } 1865 if sk == Array { 1866 ss.Data = src.ptr 1867 ss.Len = src.Len() 1868 ss.Cap = ss.Len 1869 } else { 1870 ss = *(*sliceHeader)(src.ptr) 1871 } 1872 1873 return typedslicecopy(de.common(), ds, ss) 1874 } 1875 1876 // A runtimeSelect is a single case passed to rselect. 1877 // This must match ../runtime/select.go:/runtimeSelect 1878 type runtimeSelect struct { 1879 dir SelectDir // SelectSend, SelectRecv or SelectDefault 1880 typ *rtype // channel type 1881 ch unsafe.Pointer // channel 1882 val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir) 1883 } 1884 1885 // rselect runs a select. It returns the index of the chosen case. 1886 // If the case was a receive, val is filled in with the received value. 1887 // The conventional OK bool indicates whether the receive corresponds 1888 // to a sent value. 1889 //go:noescape 1890 func rselect([]runtimeSelect) (chosen int, recvOK bool) 1891 1892 // A SelectDir describes the communication direction of a select case. 1893 type SelectDir int 1894 1895 // NOTE: These values must match ../runtime/select.go:/selectDir. 1896 1897 const ( 1898 _ SelectDir = iota 1899 SelectSend // case Chan <- Send 1900 SelectRecv // case <-Chan: 1901 SelectDefault // default 1902 ) 1903 1904 // A SelectCase describes a single case in a select operation. 1905 // The kind of case depends on Dir, the communication direction. 1906 // 1907 // If Dir is SelectDefault, the case represents a default case. 1908 // Chan and Send must be zero Values. 1909 // 1910 // If Dir is SelectSend, the case represents a send operation. 1911 // Normally Chan's underlying value must be a channel, and Send's underlying value must be 1912 // assignable to the channel's element type. As a special case, if Chan is a zero Value, 1913 // then the case is ignored, and the field Send will also be ignored and may be either zero 1914 // or non-zero. 1915 // 1916 // If Dir is SelectRecv, the case represents a receive operation. 1917 // Normally Chan's underlying value must be a channel and Send must be a zero Value. 1918 // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value. 1919 // When a receive operation is selected, the received Value is returned by Select. 1920 // 1921 type SelectCase struct { 1922 Dir SelectDir // direction of case 1923 Chan Value // channel to use (for send or receive) 1924 Send Value // value to send (for send) 1925 } 1926 1927 // Select executes a select operation described by the list of cases. 1928 // Like the Go select statement, it blocks until at least one of the cases 1929 // can proceed, makes a uniform pseudo-random choice, 1930 // and then executes that case. It returns the index of the chosen case 1931 // and, if that case was a receive operation, the value received and a 1932 // boolean indicating whether the value corresponds to a send on the channel 1933 // (as opposed to a zero value received because the channel is closed). 1934 func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) { 1935 // NOTE: Do not trust that caller is not modifying cases data underfoot. 1936 // The range is safe because the caller cannot modify our copy of the len 1937 // and each iteration makes its own copy of the value c. 1938 runcases := make([]runtimeSelect, len(cases)) 1939 haveDefault := false 1940 for i, c := range cases { 1941 rc := &runcases[i] 1942 rc.dir = c.Dir 1943 switch c.Dir { 1944 default: 1945 panic("reflect.Select: invalid Dir") 1946 1947 case SelectDefault: // default 1948 if haveDefault { 1949 panic("reflect.Select: multiple default cases") 1950 } 1951 haveDefault = true 1952 if c.Chan.IsValid() { 1953 panic("reflect.Select: default case has Chan value") 1954 } 1955 if c.Send.IsValid() { 1956 panic("reflect.Select: default case has Send value") 1957 } 1958 1959 case SelectSend: 1960 ch := c.Chan 1961 if !ch.IsValid() { 1962 break 1963 } 1964 ch.mustBe(Chan) 1965 ch.mustBeExported() 1966 tt := (*chanType)(unsafe.Pointer(ch.typ)) 1967 if ChanDir(tt.dir)&SendDir == 0 { 1968 panic("reflect.Select: SendDir case using recv-only channel") 1969 } 1970 rc.ch = ch.pointer() 1971 rc.typ = &tt.rtype 1972 v := c.Send 1973 if !v.IsValid() { 1974 panic("reflect.Select: SendDir case missing Send value") 1975 } 1976 v.mustBeExported() 1977 v = v.assignTo("reflect.Select", tt.elem, nil) 1978 if v.flag&flagIndir != 0 { 1979 rc.val = v.ptr 1980 } else { 1981 rc.val = unsafe.Pointer(&v.ptr) 1982 } 1983 1984 case SelectRecv: 1985 if c.Send.IsValid() { 1986 panic("reflect.Select: RecvDir case has Send value") 1987 } 1988 ch := c.Chan 1989 if !ch.IsValid() { 1990 break 1991 } 1992 ch.mustBe(Chan) 1993 ch.mustBeExported() 1994 tt := (*chanType)(unsafe.Pointer(ch.typ)) 1995 if ChanDir(tt.dir)&RecvDir == 0 { 1996 panic("reflect.Select: RecvDir case using send-only channel") 1997 } 1998 rc.ch = ch.pointer() 1999 rc.typ = &tt.rtype 2000 rc.val = unsafe_New(tt.elem) 2001 } 2002 } 2003 2004 chosen, recvOK = rselect(runcases) 2005 if runcases[chosen].dir == SelectRecv { 2006 tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ)) 2007 t := tt.elem 2008 p := runcases[chosen].val 2009 fl := flag(t.Kind()) 2010 if ifaceIndir(t) { 2011 recv = Value{t, p, fl | flagIndir} 2012 } else { 2013 recv = Value{t, *(*unsafe.Pointer)(p), fl} 2014 } 2015 } 2016 return chosen, recv, recvOK 2017 } 2018 2019 /* 2020 * constructors 2021 */ 2022 2023 // implemented in package runtime 2024 func unsafe_New(*rtype) unsafe.Pointer 2025 func unsafe_NewArray(*rtype, int) unsafe.Pointer 2026 2027 // MakeSlice creates a new zero-initialized slice value 2028 // for the specified slice type, length, and capacity. 2029 func MakeSlice(typ Type, len, cap int) Value { 2030 if typ.Kind() != Slice { 2031 panic("reflect.MakeSlice of non-slice type") 2032 } 2033 if len < 0 { 2034 panic("reflect.MakeSlice: negative len") 2035 } 2036 if cap < 0 { 2037 panic("reflect.MakeSlice: negative cap") 2038 } 2039 if len > cap { 2040 panic("reflect.MakeSlice: len > cap") 2041 } 2042 2043 s := sliceHeader{unsafe_NewArray(typ.Elem().(*rtype), cap), len, cap} 2044 return Value{typ.common(), unsafe.Pointer(&s), flagIndir | flag(Slice)} 2045 } 2046 2047 // MakeChan creates a new channel with the specified type and buffer size. 2048 func MakeChan(typ Type, buffer int) Value { 2049 if typ.Kind() != Chan { 2050 panic("reflect.MakeChan of non-chan type") 2051 } 2052 if buffer < 0 { 2053 panic("reflect.MakeChan: negative buffer size") 2054 } 2055 if typ.ChanDir() != BothDir { 2056 panic("reflect.MakeChan: unidirectional channel type") 2057 } 2058 ch := makechan(typ.(*rtype), uint64(buffer)) 2059 return Value{typ.common(), ch, flag(Chan)} 2060 } 2061 2062 // MakeMap creates a new map of the specified type. 2063 func MakeMap(typ Type) Value { 2064 if typ.Kind() != Map { 2065 panic("reflect.MakeMap of non-map type") 2066 } 2067 m := makemap(typ.(*rtype)) 2068 return Value{typ.common(), m, flag(Map)} 2069 } 2070 2071 // Indirect returns the value that v points to. 2072 // If v is a nil pointer, Indirect returns a zero Value. 2073 // If v is not a pointer, Indirect returns v. 2074 func Indirect(v Value) Value { 2075 if v.Kind() != Ptr { 2076 return v 2077 } 2078 return v.Elem() 2079 } 2080 2081 // ValueOf returns a new Value initialized to the concrete value 2082 // stored in the interface i. ValueOf(nil) returns the zero Value. 2083 func ValueOf(i interface{}) Value { 2084 if i == nil { 2085 return Value{} 2086 } 2087 2088 // TODO: Maybe allow contents of a Value to live on the stack. 2089 // For now we make the contents always escape to the heap. It 2090 // makes life easier in a few places (see chanrecv/mapassign 2091 // comment below). 2092 escapes(i) 2093 2094 return unpackEface(i) 2095 } 2096 2097 // Zero returns a Value representing the zero value for the specified type. 2098 // The result is different from the zero value of the Value struct, 2099 // which represents no value at all. 2100 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. 2101 // The returned value is neither addressable nor settable. 2102 func Zero(typ Type) Value { 2103 if typ == nil { 2104 panic("reflect: Zero(nil)") 2105 } 2106 t := typ.common() 2107 fl := flag(t.Kind()) 2108 if ifaceIndir(t) { 2109 return Value{t, unsafe_New(typ.(*rtype)), fl | flagIndir} 2110 } 2111 return Value{t, nil, fl} 2112 } 2113 2114 // New returns a Value representing a pointer to a new zero value 2115 // for the specified type. That is, the returned Value's Type is PtrTo(typ). 2116 func New(typ Type) Value { 2117 if typ == nil { 2118 panic("reflect: New(nil)") 2119 } 2120 ptr := unsafe_New(typ.(*rtype)) 2121 fl := flag(Ptr) 2122 return Value{typ.common().ptrTo(), ptr, fl} 2123 } 2124 2125 // NewAt returns a Value representing a pointer to a value of the 2126 // specified type, using p as that pointer. 2127 func NewAt(typ Type, p unsafe.Pointer) Value { 2128 fl := flag(Ptr) 2129 return Value{typ.common().ptrTo(), p, fl} 2130 } 2131 2132 // assignTo returns a value v that can be assigned directly to typ. 2133 // It panics if v is not assignable to typ. 2134 // For a conversion to an interface type, target is a suggested scratch space to use. 2135 func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value { 2136 if v.flag&flagMethod != 0 { 2137 v = makeMethodValue(context, v) 2138 } 2139 2140 switch { 2141 case directlyAssignable(dst, v.typ): 2142 // Overwrite type so that they match. 2143 // Same memory layout, so no harm done. 2144 v.typ = dst 2145 fl := v.flag & (flagRO | flagAddr | flagIndir) 2146 fl |= flag(dst.Kind()) 2147 return Value{dst, v.ptr, fl} 2148 2149 case implements(dst, v.typ): 2150 if target == nil { 2151 target = unsafe_New(dst) 2152 } 2153 x := valueInterface(v, false) 2154 if dst.NumMethod() == 0 { 2155 *(*interface{})(target) = x 2156 } else { 2157 ifaceE2I(dst, x, target) 2158 } 2159 return Value{dst, target, flagIndir | flag(Interface)} 2160 } 2161 2162 // Failed. 2163 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String()) 2164 } 2165 2166 // Convert returns the value v converted to type t. 2167 // If the usual Go conversion rules do not allow conversion 2168 // of the value v to type t, Convert panics. 2169 func (v Value) Convert(t Type) Value { 2170 if v.flag&flagMethod != 0 { 2171 v = makeMethodValue("Convert", v) 2172 } 2173 op := convertOp(t.common(), v.typ) 2174 if op == nil { 2175 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String()) 2176 } 2177 return op(v, t) 2178 } 2179 2180 // convertOp returns the function to convert a value of type src 2181 // to a value of type dst. If the conversion is illegal, convertOp returns nil. 2182 func convertOp(dst, src *rtype) func(Value, Type) Value { 2183 switch src.Kind() { 2184 case Int, Int8, Int16, Int32, Int64: 2185 switch dst.Kind() { 2186 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2187 return cvtInt 2188 case Float32, Float64: 2189 return cvtIntFloat 2190 case String: 2191 return cvtIntString 2192 } 2193 2194 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2195 switch dst.Kind() { 2196 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2197 return cvtUint 2198 case Float32, Float64: 2199 return cvtUintFloat 2200 case String: 2201 return cvtUintString 2202 } 2203 2204 case Float32, Float64: 2205 switch dst.Kind() { 2206 case Int, Int8, Int16, Int32, Int64: 2207 return cvtFloatInt 2208 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2209 return cvtFloatUint 2210 case Float32, Float64: 2211 return cvtFloat 2212 } 2213 2214 case Complex64, Complex128: 2215 switch dst.Kind() { 2216 case Complex64, Complex128: 2217 return cvtComplex 2218 } 2219 2220 case String: 2221 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" { 2222 switch dst.Elem().Kind() { 2223 case Uint8: 2224 return cvtStringBytes 2225 case Int32: 2226 return cvtStringRunes 2227 } 2228 } 2229 2230 case Slice: 2231 if dst.Kind() == String && src.Elem().PkgPath() == "" { 2232 switch src.Elem().Kind() { 2233 case Uint8: 2234 return cvtBytesString 2235 case Int32: 2236 return cvtRunesString 2237 } 2238 } 2239 } 2240 2241 // dst and src have same underlying type. 2242 if haveIdenticalUnderlyingType(dst, src) { 2243 return cvtDirect 2244 } 2245 2246 // dst and src are unnamed pointer types with same underlying base type. 2247 if dst.Kind() == Ptr && dst.Name() == "" && 2248 src.Kind() == Ptr && src.Name() == "" && 2249 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common()) { 2250 return cvtDirect 2251 } 2252 2253 if implements(dst, src) { 2254 if src.Kind() == Interface { 2255 return cvtI2I 2256 } 2257 return cvtT2I 2258 } 2259 2260 return nil 2261 } 2262 2263 // makeInt returns a Value of type t equal to bits (possibly truncated), 2264 // where t is a signed or unsigned int type. 2265 func makeInt(f flag, bits uint64, t Type) Value { 2266 typ := t.common() 2267 ptr := unsafe_New(typ) 2268 switch typ.size { 2269 case 1: 2270 *(*uint8)(ptr) = uint8(bits) 2271 case 2: 2272 *(*uint16)(ptr) = uint16(bits) 2273 case 4: 2274 *(*uint32)(ptr) = uint32(bits) 2275 case 8: 2276 *(*uint64)(ptr) = bits 2277 } 2278 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2279 } 2280 2281 // makeFloat returns a Value of type t equal to v (possibly truncated to float32), 2282 // where t is a float32 or float64 type. 2283 func makeFloat(f flag, v float64, t Type) Value { 2284 typ := t.common() 2285 ptr := unsafe_New(typ) 2286 switch typ.size { 2287 case 4: 2288 *(*float32)(ptr) = float32(v) 2289 case 8: 2290 *(*float64)(ptr) = v 2291 } 2292 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2293 } 2294 2295 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64), 2296 // where t is a complex64 or complex128 type. 2297 func makeComplex(f flag, v complex128, t Type) Value { 2298 typ := t.common() 2299 ptr := unsafe_New(typ) 2300 switch typ.size { 2301 case 8: 2302 *(*complex64)(ptr) = complex64(v) 2303 case 16: 2304 *(*complex128)(ptr) = v 2305 } 2306 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2307 } 2308 2309 func makeString(f flag, v string, t Type) Value { 2310 ret := New(t).Elem() 2311 ret.SetString(v) 2312 ret.flag = ret.flag&^flagAddr | f 2313 return ret 2314 } 2315 2316 func makeBytes(f flag, v []byte, t Type) Value { 2317 ret := New(t).Elem() 2318 ret.SetBytes(v) 2319 ret.flag = ret.flag&^flagAddr | f 2320 return ret 2321 } 2322 2323 func makeRunes(f flag, v []rune, t Type) Value { 2324 ret := New(t).Elem() 2325 ret.setRunes(v) 2326 ret.flag = ret.flag&^flagAddr | f 2327 return ret 2328 } 2329 2330 // These conversion functions are returned by convertOp 2331 // for classes of conversions. For example, the first function, cvtInt, 2332 // takes any value v of signed int type and returns the value converted 2333 // to type t, where t is any signed or unsigned int type. 2334 2335 // convertOp: intXX -> [u]intXX 2336 func cvtInt(v Value, t Type) Value { 2337 return makeInt(v.flag&flagRO, uint64(v.Int()), t) 2338 } 2339 2340 // convertOp: uintXX -> [u]intXX 2341 func cvtUint(v Value, t Type) Value { 2342 return makeInt(v.flag&flagRO, v.Uint(), t) 2343 } 2344 2345 // convertOp: floatXX -> intXX 2346 func cvtFloatInt(v Value, t Type) Value { 2347 return makeInt(v.flag&flagRO, uint64(int64(v.Float())), t) 2348 } 2349 2350 // convertOp: floatXX -> uintXX 2351 func cvtFloatUint(v Value, t Type) Value { 2352 return makeInt(v.flag&flagRO, uint64(v.Float()), t) 2353 } 2354 2355 // convertOp: intXX -> floatXX 2356 func cvtIntFloat(v Value, t Type) Value { 2357 return makeFloat(v.flag&flagRO, float64(v.Int()), t) 2358 } 2359 2360 // convertOp: uintXX -> floatXX 2361 func cvtUintFloat(v Value, t Type) Value { 2362 return makeFloat(v.flag&flagRO, float64(v.Uint()), t) 2363 } 2364 2365 // convertOp: floatXX -> floatXX 2366 func cvtFloat(v Value, t Type) Value { 2367 return makeFloat(v.flag&flagRO, v.Float(), t) 2368 } 2369 2370 // convertOp: complexXX -> complexXX 2371 func cvtComplex(v Value, t Type) Value { 2372 return makeComplex(v.flag&flagRO, v.Complex(), t) 2373 } 2374 2375 // convertOp: intXX -> string 2376 func cvtIntString(v Value, t Type) Value { 2377 return makeString(v.flag&flagRO, string(v.Int()), t) 2378 } 2379 2380 // convertOp: uintXX -> string 2381 func cvtUintString(v Value, t Type) Value { 2382 return makeString(v.flag&flagRO, string(v.Uint()), t) 2383 } 2384 2385 // convertOp: []byte -> string 2386 func cvtBytesString(v Value, t Type) Value { 2387 return makeString(v.flag&flagRO, string(v.Bytes()), t) 2388 } 2389 2390 // convertOp: string -> []byte 2391 func cvtStringBytes(v Value, t Type) Value { 2392 return makeBytes(v.flag&flagRO, []byte(v.String()), t) 2393 } 2394 2395 // convertOp: []rune -> string 2396 func cvtRunesString(v Value, t Type) Value { 2397 return makeString(v.flag&flagRO, string(v.runes()), t) 2398 } 2399 2400 // convertOp: string -> []rune 2401 func cvtStringRunes(v Value, t Type) Value { 2402 return makeRunes(v.flag&flagRO, []rune(v.String()), t) 2403 } 2404 2405 // convertOp: direct copy 2406 func cvtDirect(v Value, typ Type) Value { 2407 f := v.flag 2408 t := typ.common() 2409 ptr := v.ptr 2410 if f&flagAddr != 0 { 2411 // indirect, mutable word - make a copy 2412 c := unsafe_New(t) 2413 typedmemmove(t, c, ptr) 2414 ptr = c 2415 f &^= flagAddr 2416 } 2417 return Value{t, ptr, v.flag&flagRO | f} // v.flag&flagRO|f == f? 2418 } 2419 2420 // convertOp: concrete -> interface 2421 func cvtT2I(v Value, typ Type) Value { 2422 target := unsafe_New(typ.common()) 2423 x := valueInterface(v, false) 2424 if typ.NumMethod() == 0 { 2425 *(*interface{})(target) = x 2426 } else { 2427 ifaceE2I(typ.(*rtype), x, target) 2428 } 2429 return Value{typ.common(), target, v.flag&flagRO | flagIndir | flag(Interface)} 2430 } 2431 2432 // convertOp: interface -> interface 2433 func cvtI2I(v Value, typ Type) Value { 2434 if v.IsNil() { 2435 ret := Zero(typ) 2436 ret.flag |= v.flag & flagRO 2437 return ret 2438 } 2439 return cvtT2I(v.Elem(), typ) 2440 } 2441 2442 // implemented in ../runtime 2443 func chancap(ch unsafe.Pointer) int 2444 func chanclose(ch unsafe.Pointer) 2445 func chanlen(ch unsafe.Pointer) int 2446 2447 // Note: some of the noescape annotations below are technically a lie, 2448 // but safe in the context of this package. Functions like chansend 2449 // and mapassign don't escape the referent, but may escape anything 2450 // the referent points to (they do shallow copies of the referent). 2451 // It is safe in this package because the referent may only point 2452 // to something a Value may point to, and that is always in the heap 2453 // (due to the escapes() call in ValueOf). 2454 2455 //go:noescape 2456 func chanrecv(t *rtype, ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool) 2457 2458 //go:noescape 2459 func chansend(t *rtype, ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool 2460 2461 func makechan(typ *rtype, size uint64) (ch unsafe.Pointer) 2462 func makemap(t *rtype) (m unsafe.Pointer) 2463 2464 //go:noescape 2465 func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer) 2466 2467 //go:noescape 2468 func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer) 2469 2470 //go:noescape 2471 func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer) 2472 2473 // m escapes into the return value, but the caller of mapiterinit 2474 // doesn't let the return value escape. 2475 //go:noescape 2476 func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer 2477 2478 //go:noescape 2479 func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer) 2480 2481 //go:noescape 2482 func mapiternext(it unsafe.Pointer) 2483 2484 //go:noescape 2485 func maplen(m unsafe.Pointer) int 2486 2487 // call calls fn with a copy of the n argument bytes pointed at by arg. 2488 // After fn returns, reflectcall copies n-retoffset result bytes 2489 // back into arg+retoffset before returning. If copying result bytes back, 2490 // the caller must pass the argument frame type as argtype, so that 2491 // call can execute appropriate write barriers during the copy. 2492 func call(argtype *rtype, fn, arg unsafe.Pointer, n uint32, retoffset uint32) 2493 2494 func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer) 2495 2496 // typedmemmove copies a value of type t to dst from src. 2497 //go:noescape 2498 func typedmemmove(t *rtype, dst, src unsafe.Pointer) 2499 2500 // typedmemmovepartial is like typedmemmove but assumes that 2501 // dst and src point off bytes into the value and only copies size bytes. 2502 //go:noescape 2503 func typedmemmovepartial(t *rtype, dst, src unsafe.Pointer, off, size uintptr) 2504 2505 // typedslicecopy copies a slice of elemType values from src to dst, 2506 // returning the number of elements copied. 2507 //go:noescape 2508 func typedslicecopy(elemType *rtype, dst, src sliceHeader) int 2509 2510 //go:noescape 2511 func memclr(ptr unsafe.Pointer, n uintptr) 2512 2513 // Dummy annotation marking that the value x escapes, 2514 // for use in cases where the reflect code is so clever that 2515 // the compiler cannot follow. 2516 func escapes(x interface{}) { 2517 if dummy.b { 2518 dummy.x = x 2519 } 2520 } 2521 2522 var dummy struct { 2523 b bool 2524 x interface{} 2525 }