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