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