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