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