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.
14 const bigEndian = false // can be smarter if we find a big-endian machine
15 const ptrSize = unsafe.Sizeof((*byte)(nil))
16 const cannotSet = "cannot set value obtained from unexported struct field"
18 // TODO: This will have to go away when
19 // the new gc goes in.
20 func memmove(adst, asrc unsafe.Pointer, n uintptr) {
24 case src < dst && src+n > dst:
26 // careful: i is unsigned
29 *(*byte)(unsafe.Pointer(dst + i)) = *(*byte)(unsafe.Pointer(src + i))
31 case (n|src|dst)&(ptrSize-1) != 0:
33 for i := uintptr(0); i < n; i++ {
34 *(*byte)(unsafe.Pointer(dst + i)) = *(*byte)(unsafe.Pointer(src + i))
38 for i := uintptr(0); i < n; i += ptrSize {
39 *(*uintptr)(unsafe.Pointer(dst + i)) = *(*uintptr)(unsafe.Pointer(src + i))
44 // Value is the reflection interface to a Go value.
46 // Not all methods apply to all kinds of values. Restrictions,
47 // if any, are noted in the documentation for each method.
48 // Use the Kind method to find out the kind of value before
49 // calling kind-specific methods. Calling a method
50 // inappropriate to the kind of type causes a run time panic.
52 // The zero Value represents no value.
53 // Its IsValid method returns false, its Kind method returns Invalid,
54 // its String method returns "<invalid Value>", and all other methods panic.
55 // Most functions and methods never return an invalid value.
56 // If one does, its documentation states the conditions explicitly.
58 // A Value can be used concurrently by multiple goroutines provided that
59 // the underlying Go value can be used concurrently for the equivalent
62 // typ holds the type of the value represented by a Value.
65 // val holds the 1-word representation of the value.
66 // If flag's flagIndir bit is set, then val is a pointer to the data.
67 // Otherwise val is a word holding the actual data.
68 // When the data is smaller than a word, it begins at
69 // the first byte (in the memory address sense) of val.
70 // We use unsafe.Pointer so that the garbage collector
71 // knows that val could be a pointer.
74 // flag holds metadata about the value.
75 // The lowest bits are flag bits:
76 // - flagRO: obtained via unexported field, so read-only
77 // - flagIndir: val holds a pointer to the data
78 // - flagAddr: v.CanAddr is true (implies flagIndir)
79 // - flagMethod: v is a method value.
80 // The next five bits give the Kind of the value.
81 // This repeats typ.Kind() except for method values.
82 // The remaining 23+ bits give a method number for method values.
83 // If flag.kind() != Func, code can assume that flagMethod is unset.
84 // If typ.size > ptrSize, code can assume that flagIndir is set.
87 // A method value represents a curried method invocation
88 // like r.Read for some receiver r. The typ+val+flag bits describe
89 // the receiver r, but the flag's Kind bits say Func (methods are
90 // functions), and the top bits of the flag give the method number
91 // in r's type's method table.
97 flagRO flag = 1 << iota
102 flagKindWidth = 5 // there are 27 kinds
103 flagKindMask flag = 1<<flagKindWidth - 1
104 flagMethodShift = flagKindShift + flagKindWidth
107 func (f flag) kind() Kind {
108 return Kind((f >> flagKindShift) & flagKindMask)
111 // A ValueError occurs when a Value method is invoked on
112 // a Value that does not support it. Such cases are documented
113 // in the description of each method.
114 type ValueError struct {
119 func (e *ValueError) Error() string {
121 return "reflect: call of " + e.Method + " on zero Value"
123 return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
126 // methodName returns the name of the calling method,
127 // assumed to be two stack frames above.
128 func methodName() string {
129 pc, _, _, _ := runtime.Caller(2)
130 f := runtime.FuncForPC(pc)
132 return "unknown method"
137 // An iword is the word that would be stored in an
138 // interface to represent a given value v. Specifically, if v is
139 // bigger than a pointer, its word is a pointer to v's data.
140 // Otherwise, its word holds the data stored
141 // in its leading bytes (so is not a pointer).
142 // Because the value sometimes holds a pointer, we use
143 // unsafe.Pointer to represent it, so that if iword appears
144 // in a struct, the garbage collector knows that might be
146 type iword unsafe.Pointer
148 func (v Value) iword() iword {
149 if v.flag&flagIndir != 0 && (v.kind() == Ptr || v.kind() == UnsafePointer) {
150 // Have indirect but want direct word.
151 return loadIword(v.val, v.typ.size)
156 // loadIword loads n bytes at p from memory into an iword.
157 func loadIword(p unsafe.Pointer, n uintptr) iword {
158 // Run the copy ourselves instead of calling memmove
159 // to avoid moving w to the heap.
163 panic("reflect: internal error: loadIword of " + strconv.Itoa(int(n)) + "-byte value")
166 *(*uint8)(unsafe.Pointer(&w)) = *(*uint8)(p)
168 *(*uint16)(unsafe.Pointer(&w)) = *(*uint16)(p)
170 *(*[3]byte)(unsafe.Pointer(&w)) = *(*[3]byte)(p)
172 *(*uint32)(unsafe.Pointer(&w)) = *(*uint32)(p)
174 *(*[5]byte)(unsafe.Pointer(&w)) = *(*[5]byte)(p)
176 *(*[6]byte)(unsafe.Pointer(&w)) = *(*[6]byte)(p)
178 *(*[7]byte)(unsafe.Pointer(&w)) = *(*[7]byte)(p)
180 *(*uint64)(unsafe.Pointer(&w)) = *(*uint64)(p)
185 // storeIword stores n bytes from w into p.
186 func storeIword(p unsafe.Pointer, w iword, n uintptr) {
187 // Run the copy ourselves instead of calling memmove
188 // to avoid moving w to the heap.
191 panic("reflect: internal error: storeIword of " + strconv.Itoa(int(n)) + "-byte value")
194 *(*uint8)(p) = *(*uint8)(unsafe.Pointer(&w))
196 *(*uint16)(p) = *(*uint16)(unsafe.Pointer(&w))
198 *(*[3]byte)(p) = *(*[3]byte)(unsafe.Pointer(&w))
200 *(*uint32)(p) = *(*uint32)(unsafe.Pointer(&w))
202 *(*[5]byte)(p) = *(*[5]byte)(unsafe.Pointer(&w))
204 *(*[6]byte)(p) = *(*[6]byte)(unsafe.Pointer(&w))
206 *(*[7]byte)(p) = *(*[7]byte)(unsafe.Pointer(&w))
208 *(*uint64)(p) = *(*uint64)(unsafe.Pointer(&w))
212 // emptyInterface is the header for an interface{} value.
213 type emptyInterface struct {
218 // nonEmptyInterface is the header for a interface value with methods.
219 type nonEmptyInterface struct {
220 // see ../runtime/iface.c:/Itab
222 typ *runtimeType // dynamic concrete type
223 fun [100000]unsafe.Pointer // method table
228 // mustBe panics if f's kind is not expected.
229 // Making this a method on flag instead of on Value
230 // (and embedding flag in Value) means that we can write
231 // the very clear v.mustBe(Bool) and have it compile into
232 // v.flag.mustBe(Bool), which will only bother to copy the
233 // single important word for the receiver.
234 func (f flag) mustBe(expected Kind) {
237 panic(&ValueError{methodName(), k})
241 // mustBeExported panics if f records that the value was obtained using
242 // an unexported field.
243 func (f flag) mustBeExported() {
245 panic(&ValueError{methodName(), 0})
248 panic(methodName() + " using value obtained using unexported field")
252 // mustBeAssignable panics if f records that the value is not assignable,
253 // which is to say that either it was obtained using an unexported field
254 // or it is not addressable.
255 func (f flag) mustBeAssignable() {
257 panic(&ValueError{methodName(), Invalid})
259 // Assignable if addressable and not read-only.
261 panic(methodName() + " using value obtained using unexported field")
264 panic(methodName() + " using unaddressable value")
268 // Addr returns a pointer value representing the address of v.
269 // It panics if CanAddr() returns false.
270 // Addr is typically used to obtain a pointer to a struct field
271 // or slice element in order to call a method that requires a
273 func (v Value) Addr() Value {
274 if v.flag&flagAddr == 0 {
275 panic("reflect.Value.Addr of unaddressable value")
277 return Value{v.typ.ptrTo(), v.val, (v.flag & flagRO) | flag(Ptr)<<flagKindShift}
280 // Bool returns v's underlying value.
281 // It panics if v's kind is not Bool.
282 func (v Value) Bool() bool {
284 if v.flag&flagIndir != 0 {
285 return *(*bool)(v.val)
287 return *(*bool)(unsafe.Pointer(&v.val))
290 // Bytes returns v's underlying value.
291 // It panics if v's underlying value is not a slice of bytes.
292 func (v Value) Bytes() []byte {
294 if v.typ.Elem().Kind() != Uint8 {
295 panic("reflect.Value.Bytes of non-byte slice")
297 // Slice is always bigger than a word; assume flagIndir.
298 return *(*[]byte)(v.val)
301 // runes returns v's underlying value.
302 // It panics if v's underlying value is not a slice of runes (int32s).
303 func (v Value) runes() []rune {
305 if v.typ.Elem().Kind() != Int32 {
306 panic("reflect.Value.Bytes of non-rune slice")
308 // Slice is always bigger than a word; assume flagIndir.
309 return *(*[]rune)(v.val)
312 // CanAddr returns true if the value's address can be obtained with Addr.
313 // Such values are called addressable. A value is addressable if it is
314 // an element of a slice, an element of an addressable array,
315 // a field of an addressable struct, or the result of dereferencing a pointer.
316 // If CanAddr returns false, calling Addr will panic.
317 func (v Value) CanAddr() bool {
318 return v.flag&flagAddr != 0
321 // CanSet returns true if the value of v can be changed.
322 // A Value can be changed only if it is addressable and was not
323 // obtained by the use of unexported struct fields.
324 // If CanSet returns false, calling Set or any type-specific
325 // setter (e.g., SetBool, SetInt64) will panic.
326 func (v Value) CanSet() bool {
327 return v.flag&(flagAddr|flagRO) == flagAddr
330 // Call calls the function v with the input arguments in.
331 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
332 // Call panics if v's Kind is not Func.
333 // It returns the output results as Values.
334 // As in Go, each input argument must be assignable to the
335 // type of the function's corresponding input parameter.
336 // If v is a variadic function, Call creates the variadic slice parameter
337 // itself, copying in the corresponding values.
338 func (v Value) Call(in []Value) []Value {
341 return v.call("Call", in)
344 // CallSlice calls the variadic function v with the input arguments in,
345 // assigning the slice in[len(in)-1] to v's final variadic argument.
346 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]...).
347 // Call panics if v's Kind is not Func or if v is not variadic.
348 // It returns the output results as Values.
349 // As in Go, each input argument must be assignable to the
350 // type of the function's corresponding input parameter.
351 func (v Value) CallSlice(in []Value) []Value {
354 return v.call("CallSlice", in)
357 func (v Value) call(method string, in []Value) []Value {
358 // Get function pointer, type.
364 if v.flag&flagMethod != 0 {
365 i := int(v.flag) >> flagMethodShift
366 if v.typ.Kind() == Interface {
367 tt := (*interfaceType)(unsafe.Pointer(v.typ))
368 if i < 0 || i >= len(tt.methods) {
369 panic("reflect: broken Value")
372 if m.pkgPath != nil {
373 panic(method + " of unexported method")
375 t = toCommonType(m.typ)
376 iface := (*nonEmptyInterface)(v.val)
377 if iface.itab == nil {
378 panic(method + " of method on nil interface value")
380 fn = iface.itab.fun[i]
383 ut := v.typ.uncommon()
384 if ut == nil || i < 0 || i >= len(ut.methods) {
385 panic("reflect: broken Value")
388 if m.pkgPath != nil {
389 panic(method + " of unexported method")
392 t = toCommonType(m.mtyp)
395 } else if v.flag&flagIndir != 0 {
396 fn = *(*unsafe.Pointer)(v.val)
402 panic("reflect.Value.Call: call of nil function")
405 isSlice := method == "CallSlice"
409 panic("reflect: CallSlice of non-variadic function")
412 panic("reflect: CallSlice with too few input arguments")
415 panic("reflect: CallSlice with too many input arguments")
422 panic("reflect: Call with too few input arguments")
424 if !t.IsVariadic() && len(in) > n {
425 panic("reflect: Call with too many input arguments")
428 for _, x := range in {
429 if x.Kind() == Invalid {
430 panic("reflect: " + method + " using zero Value argument")
433 for i := 0; i < n; i++ {
434 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
435 panic("reflect: " + method + " using " + xt.String() + " as type " + targ.String())
438 if !isSlice && t.IsVariadic() {
439 // prepare slice for remaining values
441 slice := MakeSlice(t.In(n), m, m)
442 elem := t.In(n).Elem()
443 for i := 0; i < m; i++ {
445 if xt := x.Type(); !xt.AssignableTo(elem) {
446 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + method)
448 slice.Index(i).Set(x)
451 in = make([]Value, n+1)
457 if nin != t.NumIn() {
458 panic("reflect.Value.Call: wrong argument count")
462 if v.flag&flagMethod != 0 {
465 params := make([]unsafe.Pointer, nin)
467 if v.flag&flagMethod != 0 {
468 // Hard-wired first argument.
471 params[0] = unsafe.Pointer(p)
474 first_pointer := false
475 for i, pv := range in {
477 targ := t.In(i).(*commonType)
478 pv = pv.assignTo("reflect.Value.Call", targ, nil)
479 if pv.flag&flagIndir == 0 {
480 p := new(unsafe.Pointer)
482 params[off] = unsafe.Pointer(p)
486 if i == 0 && Kind(targ.kind) != Ptr && v.flag&flagMethod == 0 && isMethod(v.typ) {
487 p := new(unsafe.Pointer)
489 params[off] = unsafe.Pointer(p)
495 ret := make([]Value, nout)
496 results := make([]unsafe.Pointer, nout)
497 for i := 0; i < nout; i++ {
499 results[i] = unsafe.Pointer(v.Pointer())
503 var pp *unsafe.Pointer
507 var pr *unsafe.Pointer
508 if len(results) > 0 {
512 call(t, fn, v.flag&flagMethod != 0, first_pointer, pp, pr)
517 // gccgo specific test to see if typ is a method. We can tell by
518 // looking at the string to see if there is a receiver. We need this
519 // because for gccgo all methods take pointer receivers.
520 func isMethod(t *commonType) bool {
521 if Kind(t.kind) != Func {
528 for i, c := range s {
534 } else if parens == 0 && c == ' ' && s[i+1] != '(' && !sawRet {
542 // callReflect is the call implementation used by a function
543 // returned by MakeFunc. In many ways it is the opposite of the
544 // method Value.call above. The method above converts a call using Values
545 // into a call of a function with a concrete argument frame, while
546 // callReflect converts a call of a function with a concrete argument
547 // frame into a call using Values.
548 // It is in this file so that it can be next to the call method above.
549 // The remainder of the MakeFunc implementation is in makefunc.go.
550 func callReflect(ftyp *funcType, f func([]Value) []Value, frame unsafe.Pointer) {
551 // Copy argument frame into Values.
554 in := make([]Value, 0, len(ftyp.in))
555 for _, arg := range ftyp.in {
556 typ := toCommonType(arg)
557 off += -off & uintptr(typ.align-1)
558 v := Value{typ, nil, flag(typ.Kind()) << flagKindShift}
559 if typ.size <= ptrSize {
560 // value fits in word.
561 v.val = unsafe.Pointer(loadIword(unsafe.Pointer(uintptr(ptr)+off), typ.size))
563 // value does not fit in word.
564 // Must make a copy, because f might keep a reference to it,
565 // and we cannot let f keep a reference to the stack frame
566 // after this function returns, not even a read-only reference.
567 v.val = unsafe_New(typ)
568 memmove(v.val, unsafe.Pointer(uintptr(ptr)+off), typ.size)
575 // Call underlying function.
577 if len(out) != len(ftyp.out) {
578 panic("reflect: wrong return count from function created by MakeFunc")
581 // Copy results back into argument frame.
582 if len(ftyp.out) > 0 {
583 off += -off & (ptrSize - 1)
584 for i, arg := range ftyp.out {
585 typ := toCommonType(arg)
588 panic("reflect: function created by MakeFunc using " + funcName(f) +
589 " returned wrong type: have " +
590 out[i].typ.String() + " for " + typ.String())
592 if v.flag&flagRO != 0 {
593 panic("reflect: function created by MakeFunc using " + funcName(f) +
594 " returned value obtained from unexported field")
596 off += -off & uintptr(typ.align-1)
597 addr := unsafe.Pointer(uintptr(ptr) + off)
598 if v.flag&flagIndir == 0 {
599 storeIword(addr, iword(v.val), typ.size)
601 memmove(addr, v.val, typ.size)
608 // funcName returns the name of f, for use in error messages.
609 func funcName(f func([]Value) []Value) string {
610 pc := *(*uintptr)(unsafe.Pointer(&f))
611 rf := runtime.FuncForPC(pc)
618 // Cap returns v's capacity.
619 // It panics if v's Kind is not Array, Chan, or Slice.
620 func (v Value) Cap() int {
626 return int(chancap(*(*iword)(v.iword())))
628 // Slice is always bigger than a word; assume flagIndir.
629 return (*SliceHeader)(v.val).Cap
631 panic(&ValueError{"reflect.Value.Cap", k})
634 // Close closes the channel v.
635 // It panics if v's Kind is not Chan.
636 func (v Value) Close() {
639 chanclose(*(*iword)(v.iword()))
642 // Complex returns v's underlying value, as a complex128.
643 // It panics if v's Kind is not Complex64 or Complex128
644 func (v Value) Complex() complex128 {
648 if v.flag&flagIndir != 0 {
649 return complex128(*(*complex64)(v.val))
651 return complex128(*(*complex64)(unsafe.Pointer(&v.val)))
653 // complex128 is always bigger than a word; assume flagIndir.
654 return *(*complex128)(v.val)
656 panic(&ValueError{"reflect.Value.Complex", k})
659 // Elem returns the value that the interface v contains
660 // or that the pointer v points to.
661 // It panics if v's Kind is not Interface or Ptr.
662 // It returns the zero Value if v is nil.
663 func (v Value) Elem() Value {
671 if v.typ.NumMethod() == 0 {
672 eface := (*emptyInterface)(v.val)
673 if eface.typ == nil {
674 // nil interface value
677 typ = toCommonType(eface.typ)
678 val = unsafe.Pointer(eface.word)
680 iface := (*nonEmptyInterface)(v.val)
681 if iface.itab == nil {
682 // nil interface value
685 typ = toCommonType(iface.itab.typ)
686 val = unsafe.Pointer(iface.word)
688 fl := v.flag & flagRO
689 fl |= flag(typ.Kind()) << flagKindShift
690 if typ.Kind() != Ptr && typ.Kind() != UnsafePointer {
693 return Value{typ, val, fl}
697 if v.flag&flagIndir != 0 {
698 val = *(*unsafe.Pointer)(val)
700 // The returned value's address is v's value.
704 tt := (*ptrType)(unsafe.Pointer(v.typ))
705 typ := toCommonType(tt.elem)
706 fl := v.flag&flagRO | flagIndir | flagAddr
707 fl |= flag(typ.Kind() << flagKindShift)
708 return Value{typ, val, fl}
710 panic(&ValueError{"reflect.Value.Elem", k})
713 // Field returns the i'th field of the struct v.
714 // It panics if v's Kind is not Struct or i is out of range.
715 func (v Value) Field(i int) Value {
717 tt := (*structType)(unsafe.Pointer(v.typ))
718 if i < 0 || i >= len(tt.fields) {
719 panic("reflect: Field index out of range")
721 field := &tt.fields[i]
722 typ := toCommonType(field.typ)
724 // Inherit permission bits from v.
725 fl := v.flag & (flagRO | flagIndir | flagAddr)
726 // Using an unexported field forces flagRO.
727 if field.pkgPath != nil {
730 fl |= flag(typ.Kind()) << flagKindShift
732 var val unsafe.Pointer
734 case fl&flagIndir != 0:
735 // Indirect. Just bump pointer.
736 val = unsafe.Pointer(uintptr(v.val) + field.offset)
738 // Direct. Discard leading bytes.
739 val = unsafe.Pointer(uintptr(v.val) << (field.offset * 8))
741 // Direct. Discard leading bytes.
742 val = unsafe.Pointer(uintptr(v.val) >> (field.offset * 8))
745 return Value{typ, val, fl}
748 // FieldByIndex returns the nested field corresponding to index.
749 // It panics if v's Kind is not struct.
750 func (v Value) FieldByIndex(index []int) Value {
752 for i, x := range index {
754 if v.Kind() == Ptr && v.Elem().Kind() == Struct {
763 // FieldByName returns the struct field with the given name.
764 // It returns the zero Value if no field was found.
765 // It panics if v's Kind is not struct.
766 func (v Value) FieldByName(name string) Value {
768 if f, ok := v.typ.FieldByName(name); ok {
769 return v.FieldByIndex(f.Index)
774 // FieldByNameFunc returns the struct field with a name
775 // that satisfies the match function.
776 // It panics if v's Kind is not struct.
777 // It returns the zero Value if no field was found.
778 func (v Value) FieldByNameFunc(match func(string) bool) Value {
780 if f, ok := v.typ.FieldByNameFunc(match); ok {
781 return v.FieldByIndex(f.Index)
786 // Float returns v's underlying value, as a float64.
787 // It panics if v's Kind is not Float32 or Float64
788 func (v Value) Float() float64 {
792 if v.flag&flagIndir != 0 {
793 return float64(*(*float32)(v.val))
795 return float64(*(*float32)(unsafe.Pointer(&v.val)))
797 if v.flag&flagIndir != 0 {
798 return *(*float64)(v.val)
800 return *(*float64)(unsafe.Pointer(&v.val))
802 panic(&ValueError{"reflect.Value.Float", k})
805 // Index returns v's i'th element.
806 // It panics if v's Kind is not Array or Slice or i is out of range.
807 func (v Value) Index(i int) Value {
811 tt := (*arrayType)(unsafe.Pointer(v.typ))
812 if i < 0 || i > int(tt.len) {
813 panic("reflect: array index out of range")
815 typ := toCommonType(tt.elem)
816 fl := v.flag & (flagRO | flagIndir | flagAddr) // bits same as overall array
817 fl |= flag(typ.Kind()) << flagKindShift
818 offset := uintptr(i) * typ.size
820 var val unsafe.Pointer
822 case fl&flagIndir != 0:
823 // Indirect. Just bump pointer.
824 val = unsafe.Pointer(uintptr(v.val) + offset)
826 // Direct. Discard leading bytes.
827 val = unsafe.Pointer(uintptr(v.val) << (offset * 8))
829 // Direct. Discard leading bytes.
830 val = unsafe.Pointer(uintptr(v.val) >> (offset * 8))
832 return Value{typ, val, fl}
835 // Element flag same as Elem of Ptr.
836 // Addressable, indirect, possibly read-only.
837 fl := flagAddr | flagIndir | v.flag&flagRO
838 s := (*SliceHeader)(v.val)
839 if i < 0 || i >= s.Len {
840 panic("reflect: slice index out of range")
842 tt := (*sliceType)(unsafe.Pointer(v.typ))
843 typ := toCommonType(tt.elem)
844 fl |= flag(typ.Kind()) << flagKindShift
845 val := unsafe.Pointer(s.Data + uintptr(i)*typ.size)
846 return Value{typ, val, fl}
848 panic(&ValueError{"reflect.Value.Index", k})
851 // Int returns v's underlying value, as an int64.
852 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
853 func (v Value) Int() int64 {
856 if v.flag&flagIndir != 0 {
859 // The escape analysis is good enough that &v.val
860 // does not trigger a heap allocation.
861 p = unsafe.Pointer(&v.val)
865 return int64(*(*int)(p))
867 return int64(*(*int8)(p))
869 return int64(*(*int16)(p))
871 return int64(*(*int32)(p))
873 return int64(*(*int64)(p))
875 panic(&ValueError{"reflect.Value.Int", k})
878 // CanInterface returns true if Interface can be used without panicking.
879 func (v Value) CanInterface() bool {
881 panic(&ValueError{"reflect.Value.CanInterface", Invalid})
883 return v.flag&(flagMethod|flagRO) == 0
886 // Interface returns v's current value as an interface{}.
887 // It is equivalent to:
888 // var i interface{} = (v's underlying value)
889 // If v is a method obtained by invoking Value.Method
890 // (as opposed to Type.Method), Interface cannot return an
891 // interface value, so it panics.
892 // It also panics if the Value was obtained by accessing
893 // unexported struct fields.
894 func (v Value) Interface() (i interface{}) {
895 return valueInterface(v, true)
898 func valueInterface(v Value, safe bool) interface{} {
900 panic(&ValueError{"reflect.Value.Interface", 0})
902 if v.flag&flagMethod != 0 {
903 panic("reflect.Value.Interface: cannot create interface value for method with bound receiver")
906 if safe && v.flag&flagRO != 0 {
907 // Do not allow access to unexported values via Interface,
908 // because they might be pointers that should not be
909 // writable or methods or function that should not be callable.
910 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
915 // Special case: return the element inside the interface.
916 // Empty interface has one layout, all interfaces with
917 // methods have a second layout.
918 if v.NumMethod() == 0 {
919 return *(*interface{})(v.val)
921 return *(*interface {
926 // Non-interface value.
927 var eface emptyInterface
928 eface.typ = v.typ.runtimeType()
929 eface.word = v.iword()
931 if v.flag&flagIndir != 0 && v.typ.size > ptrSize {
932 // eface.word is a pointer to the actual data,
933 // which might be changed. We need to return
934 // a pointer to unchanging data, so make a copy.
935 ptr := unsafe_New(v.typ)
936 memmove(ptr, unsafe.Pointer(eface.word), v.typ.size)
937 eface.word = iword(ptr)
940 return *(*interface{})(unsafe.Pointer(&eface))
943 // InterfaceData returns the interface v's value as a uintptr pair.
944 // It panics if v's Kind is not Interface.
945 func (v Value) InterfaceData() [2]uintptr {
947 // We treat this as a read operation, so we allow
948 // it even for unexported data, because the caller
949 // has to import "unsafe" to turn it into something
950 // that can be abused.
951 // Interface value is always bigger than a word; assume flagIndir.
952 return *(*[2]uintptr)(v.val)
955 // IsNil returns true if v is a nil value.
956 // It panics if v's Kind is not Chan, Func, Interface, Map, Ptr, or Slice.
957 func (v Value) IsNil() bool {
960 case Chan, Func, Map, Ptr:
961 if v.flag&flagMethod != 0 {
962 panic("reflect: IsNil of method Value")
965 if v.flag&flagIndir != 0 {
966 ptr = *(*unsafe.Pointer)(ptr)
969 case Interface, Slice:
970 // Both interface and slice are nil if first word is 0.
971 // Both are always bigger than a word; assume flagIndir.
972 return *(*unsafe.Pointer)(v.val) == nil
974 panic(&ValueError{"reflect.Value.IsNil", k})
977 // IsValid returns true if v represents a value.
978 // It returns false if v is the zero Value.
979 // If IsValid returns false, all other methods except String panic.
980 // Most functions and methods never return an invalid value.
981 // If one does, its documentation states the conditions explicitly.
982 func (v Value) IsValid() bool {
986 // Kind returns v's Kind.
987 // If v is the zero Value (IsValid returns false), Kind returns Invalid.
988 func (v Value) Kind() Kind {
992 // Len returns v's length.
993 // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
994 func (v Value) Len() int {
998 tt := (*arrayType)(unsafe.Pointer(v.typ))
1001 return chanlen(*(*iword)(v.iword()))
1003 return maplen(*(*iword)(v.iword()))
1005 // Slice is bigger than a word; assume flagIndir.
1006 return (*SliceHeader)(v.val).Len
1008 // String is bigger than a word; assume flagIndir.
1009 return (*StringHeader)(v.val).Len
1011 panic(&ValueError{"reflect.Value.Len", k})
1014 // MapIndex returns the value associated with key in the map v.
1015 // It panics if v's Kind is not Map.
1016 // It returns the zero Value if key is not found in the map or if v represents a nil map.
1017 // As in Go, the key's value must be assignable to the map's key type.
1018 func (v Value) MapIndex(key Value) Value {
1020 tt := (*mapType)(unsafe.Pointer(v.typ))
1022 // Do not require key to be exported, so that DeepEqual
1023 // and other programs can use all the keys returned by
1024 // MapKeys as arguments to MapIndex. If either the map
1025 // or the key is unexported, though, the result will be
1026 // considered unexported. This is consistent with the
1027 // behavior for structs, which allow read but not write
1028 // of unexported fields.
1029 key = key.assignTo("reflect.Value.MapIndex", toCommonType(tt.key), nil)
1031 word, ok := mapaccess(v.typ.runtimeType(), *(*iword)(v.iword()), key.iword())
1035 typ := toCommonType(tt.elem)
1036 fl := (v.flag | key.flag) & flagRO
1037 if typ.Kind() != Ptr && typ.Kind() != UnsafePointer {
1040 fl |= flag(typ.Kind()) << flagKindShift
1041 return Value{typ, unsafe.Pointer(word), fl}
1044 // MapKeys returns a slice containing all the keys present in the map,
1045 // in unspecified order.
1046 // It panics if v's Kind is not Map.
1047 // It returns an empty slice if v represents a nil map.
1048 func (v Value) MapKeys() []Value {
1050 tt := (*mapType)(unsafe.Pointer(v.typ))
1051 keyType := toCommonType(tt.key)
1053 fl := v.flag & flagRO
1054 fl |= flag(keyType.Kind()) << flagKindShift
1055 if keyType.Kind() != Ptr && keyType.Kind() != UnsafePointer {
1059 m := *(*iword)(v.iword())
1064 it := mapiterinit(v.typ.runtimeType(), m)
1065 a := make([]Value, mlen)
1067 for i = 0; i < len(a); i++ {
1068 keyWord, ok := mapiterkey(it)
1072 a[i] = Value{keyType, unsafe.Pointer(keyWord), fl}
1078 // Method returns a function value corresponding to v's i'th method.
1079 // The arguments to a Call on the returned function should not include
1080 // a receiver; the returned function will always use v as the receiver.
1081 // Method panics if i is out of range.
1082 func (v Value) Method(i int) Value {
1084 panic(&ValueError{"reflect.Value.Method", Invalid})
1086 if v.flag&flagMethod != 0 || i < 0 || i >= v.typ.NumMethod() {
1087 panic("reflect: Method index out of range")
1089 fl := v.flag & (flagRO | flagAddr | flagIndir)
1090 fl |= flag(Func) << flagKindShift
1091 fl |= flag(i)<<flagMethodShift | flagMethod
1092 return Value{v.typ, v.val, fl}
1095 // NumMethod returns the number of methods in the value's method set.
1096 func (v Value) NumMethod() int {
1098 panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1100 if v.flag&flagMethod != 0 {
1103 return v.typ.NumMethod()
1106 // MethodByName returns a function value corresponding to the method
1107 // of v with the given name.
1108 // The arguments to a Call on the returned function should not include
1109 // a receiver; the returned function will always use v as the receiver.
1110 // It returns the zero Value if no method was found.
1111 func (v Value) MethodByName(name string) Value {
1113 panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1115 if v.flag&flagMethod != 0 {
1118 m, ok := v.typ.MethodByName(name)
1122 return v.Method(m.Index)
1125 // NumField returns the number of fields in the struct v.
1126 // It panics if v's Kind is not Struct.
1127 func (v Value) NumField() int {
1129 tt := (*structType)(unsafe.Pointer(v.typ))
1130 return len(tt.fields)
1133 // OverflowComplex returns true if the complex128 x cannot be represented by v's type.
1134 // It panics if v's Kind is not Complex64 or Complex128.
1135 func (v Value) OverflowComplex(x complex128) bool {
1139 return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1143 panic(&ValueError{"reflect.Value.OverflowComplex", k})
1146 // OverflowFloat returns true if the float64 x cannot be represented by v's type.
1147 // It panics if v's Kind is not Float32 or Float64.
1148 func (v Value) OverflowFloat(x float64) bool {
1152 return overflowFloat32(x)
1156 panic(&ValueError{"reflect.Value.OverflowFloat", k})
1159 func overflowFloat32(x float64) bool {
1163 return math.MaxFloat32 <= x && x <= math.MaxFloat64
1166 // OverflowInt returns true if the int64 x cannot be represented by v's type.
1167 // It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
1168 func (v Value) OverflowInt(x int64) bool {
1171 case Int, Int8, Int16, Int32, Int64:
1172 bitSize := v.typ.size * 8
1173 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1176 panic(&ValueError{"reflect.Value.OverflowInt", k})
1179 // OverflowUint returns true if the uint64 x cannot be represented by v's type.
1180 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1181 func (v Value) OverflowUint(x uint64) bool {
1184 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1185 bitSize := v.typ.size * 8
1186 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1189 panic(&ValueError{"reflect.Value.OverflowUint", k})
1192 // Pointer returns v's value as a uintptr.
1193 // It returns uintptr instead of unsafe.Pointer so that
1194 // code using reflect cannot obtain unsafe.Pointers
1195 // without importing the unsafe package explicitly.
1196 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1197 func (v Value) Pointer() uintptr {
1200 case Chan, Func, Map, Ptr, UnsafePointer:
1201 if k == Func && v.flag&flagMethod != 0 {
1202 panic("reflect.Value.Pointer of method Value")
1205 if v.flag&flagIndir != 0 {
1206 p = *(*unsafe.Pointer)(p)
1210 return (*SliceHeader)(v.val).Data
1212 panic(&ValueError{"reflect.Value.Pointer", k})
1215 // Recv receives and returns a value from the channel v.
1216 // It panics if v's Kind is not Chan.
1217 // The receive blocks until a value is ready.
1218 // The boolean value ok is true if the value x corresponds to a send
1219 // on the channel, false if it is a zero value received because the channel is closed.
1220 func (v Value) Recv() (x Value, ok bool) {
1223 return v.recv(false)
1226 // internal recv, possibly non-blocking (nb).
1227 // v is known to be a channel.
1228 func (v Value) recv(nb bool) (val Value, ok bool) {
1229 tt := (*chanType)(unsafe.Pointer(v.typ))
1230 if ChanDir(tt.dir)&RecvDir == 0 {
1231 panic("recv on send-only channel")
1233 word, selected, ok := chanrecv(v.typ.runtimeType(), *(*iword)(v.iword()), nb)
1235 typ := toCommonType(tt.elem)
1236 fl := flag(typ.Kind()) << flagKindShift
1237 if typ.Kind() != Ptr && typ.Kind() != UnsafePointer {
1240 val = Value{typ, unsafe.Pointer(word), fl}
1245 // Send sends x on the channel v.
1246 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1247 // As in Go, x's value must be assignable to the channel's element type.
1248 func (v Value) Send(x Value) {
1254 // internal send, possibly non-blocking.
1255 // v is known to be a channel.
1256 func (v Value) send(x Value, nb bool) (selected bool) {
1257 tt := (*chanType)(unsafe.Pointer(v.typ))
1258 if ChanDir(tt.dir)&SendDir == 0 {
1259 panic("send on recv-only channel")
1262 x = x.assignTo("reflect.Value.Send", toCommonType(tt.elem), nil)
1263 return chansend(v.typ.runtimeType(), *(*iword)(v.iword()), x.iword(), nb)
1266 // Set assigns x to the value v.
1267 // It panics if CanSet returns false.
1268 // As in Go, x's value must be assignable to v's type.
1269 func (v Value) Set(x Value) {
1270 v.mustBeAssignable()
1271 x.mustBeExported() // do not let unexported x leak
1272 var target *interface{}
1273 if v.kind() == Interface {
1274 target = (*interface{})(v.val)
1276 x = x.assignTo("reflect.Set", v.typ, target)
1277 if x.flag&flagIndir != 0 {
1278 memmove(v.val, x.val, v.typ.size)
1280 storeIword(v.val, iword(x.val), v.typ.size)
1284 // SetBool sets v's underlying value.
1285 // It panics if v's Kind is not Bool or if CanSet() is false.
1286 func (v Value) SetBool(x bool) {
1287 v.mustBeAssignable()
1292 // SetBytes sets v's underlying value.
1293 // It panics if v's underlying value is not a slice of bytes.
1294 func (v Value) SetBytes(x []byte) {
1295 v.mustBeAssignable()
1297 if v.typ.Elem().Kind() != Uint8 {
1298 panic("reflect.Value.SetBytes of non-byte slice")
1300 *(*[]byte)(v.val) = x
1303 // setRunes sets v's underlying value.
1304 // It panics if v's underlying value is not a slice of runes (int32s).
1305 func (v Value) setRunes(x []rune) {
1306 v.mustBeAssignable()
1308 if v.typ.Elem().Kind() != Int32 {
1309 panic("reflect.Value.setRunes of non-rune slice")
1311 *(*[]rune)(v.val) = x
1314 // SetComplex sets v's underlying value to x.
1315 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1316 func (v Value) SetComplex(x complex128) {
1317 v.mustBeAssignable()
1318 switch k := v.kind(); k {
1320 panic(&ValueError{"reflect.Value.SetComplex", k})
1322 *(*complex64)(v.val) = complex64(x)
1324 *(*complex128)(v.val) = x
1328 // SetFloat sets v's underlying value to x.
1329 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1330 func (v Value) SetFloat(x float64) {
1331 v.mustBeAssignable()
1332 switch k := v.kind(); k {
1334 panic(&ValueError{"reflect.Value.SetFloat", k})
1336 *(*float32)(v.val) = float32(x)
1338 *(*float64)(v.val) = x
1342 // SetInt sets v's underlying value to x.
1343 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1344 func (v Value) SetInt(x int64) {
1345 v.mustBeAssignable()
1346 switch k := v.kind(); k {
1348 panic(&ValueError{"reflect.Value.SetInt", k})
1350 *(*int)(v.val) = int(x)
1352 *(*int8)(v.val) = int8(x)
1354 *(*int16)(v.val) = int16(x)
1356 *(*int32)(v.val) = int32(x)
1358 *(*int64)(v.val) = x
1362 // SetLen sets v's length to n.
1363 // It panics if v's Kind is not Slice or if n is negative or
1364 // greater than the capacity of the slice.
1365 func (v Value) SetLen(n int) {
1366 v.mustBeAssignable()
1368 s := (*SliceHeader)(v.val)
1369 if n < 0 || n > int(s.Cap) {
1370 panic("reflect: slice length out of range in SetLen")
1375 // SetMapIndex sets the value associated with key in the map v to val.
1376 // It panics if v's Kind is not Map.
1377 // If val is the zero Value, SetMapIndex deletes the key from the map.
1378 // As in Go, key's value must be assignable to the map's key type,
1379 // and val's value must be assignable to the map's value type.
1380 func (v Value) SetMapIndex(key, val Value) {
1383 key.mustBeExported()
1384 tt := (*mapType)(unsafe.Pointer(v.typ))
1385 key = key.assignTo("reflect.Value.SetMapIndex", toCommonType(tt.key), nil)
1387 val.mustBeExported()
1388 val = val.assignTo("reflect.Value.SetMapIndex", toCommonType(tt.elem), nil)
1390 mapassign(v.typ.runtimeType(), *(*iword)(v.iword()), key.iword(), val.iword(), val.typ != nil)
1393 // SetUint sets v's underlying value to x.
1394 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1395 func (v Value) SetUint(x uint64) {
1396 v.mustBeAssignable()
1397 switch k := v.kind(); k {
1399 panic(&ValueError{"reflect.Value.SetUint", k})
1401 *(*uint)(v.val) = uint(x)
1403 *(*uint8)(v.val) = uint8(x)
1405 *(*uint16)(v.val) = uint16(x)
1407 *(*uint32)(v.val) = uint32(x)
1409 *(*uint64)(v.val) = x
1411 *(*uintptr)(v.val) = uintptr(x)
1415 // SetPointer sets the unsafe.Pointer value v to x.
1416 // It panics if v's Kind is not UnsafePointer.
1417 func (v Value) SetPointer(x unsafe.Pointer) {
1418 v.mustBeAssignable()
1419 v.mustBe(UnsafePointer)
1420 *(*unsafe.Pointer)(v.val) = x
1423 // SetString sets v's underlying value to x.
1424 // It panics if v's Kind is not String or if CanSet() is false.
1425 func (v Value) SetString(x string) {
1426 v.mustBeAssignable()
1428 *(*string)(v.val) = x
1431 // Slice returns a slice of v.
1432 // It panics if v's Kind is not Array or Slice.
1433 func (v Value) Slice(beg, end int) Value {
1439 switch k := v.kind(); k {
1441 panic(&ValueError{"reflect.Value.Slice", k})
1443 if v.flag&flagAddr == 0 {
1444 panic("reflect.Value.Slice: slice of unaddressable array")
1446 tt := (*arrayType)(unsafe.Pointer(v.typ))
1448 typ = (*sliceType)(unsafe.Pointer(toCommonType(tt.slice)))
1451 typ = (*sliceType)(unsafe.Pointer(v.typ))
1452 s := (*SliceHeader)(v.val)
1453 base = unsafe.Pointer(s.Data)
1457 if beg < 0 || end < beg || end > cap {
1458 panic("reflect.Value.Slice: slice index out of bounds")
1461 // Declare slice so that gc can see the base pointer in it.
1464 // Reinterpret as *SliceHeader to edit.
1465 s := (*SliceHeader)(unsafe.Pointer(&x))
1466 s.Data = uintptr(base) + uintptr(beg)*toCommonType(typ.elem).Size()
1470 fl := v.flag&flagRO | flagIndir | flag(Slice)<<flagKindShift
1471 return Value{typ.common(), unsafe.Pointer(&x), fl}
1474 // String returns the string v's underlying value, as a string.
1475 // String is a special case because of Go's String method convention.
1476 // Unlike the other getters, it does not panic if v's Kind is not String.
1477 // Instead, it returns a string of the form "<T value>" where T is v's type.
1478 func (v Value) String() string {
1479 switch k := v.kind(); k {
1481 return "<invalid Value>"
1483 return *(*string)(v.val)
1485 // If you call String on a reflect.Value of other type, it's better to
1486 // print something than to panic. Useful in debugging.
1487 return "<" + v.typ.String() + " Value>"
1490 // TryRecv attempts to receive a value from the channel v but will not block.
1491 // It panics if v's Kind is not Chan.
1492 // If the receive cannot finish without blocking, x is the zero Value.
1493 // The boolean ok is true if the value x corresponds to a send
1494 // on the channel, false if it is a zero value received because the channel is closed.
1495 func (v Value) TryRecv() (x Value, ok bool) {
1501 // TrySend attempts to send x on the channel v but will not block.
1502 // It panics if v's Kind is not Chan.
1503 // It returns true if the value was sent, false otherwise.
1504 // As in Go, x's value must be assignable to the channel's element type.
1505 func (v Value) TrySend(x Value) bool {
1508 return v.send(x, true)
1511 // Type returns v's type.
1512 func (v Value) Type() Type {
1515 panic(&ValueError{"reflect.Value.Type", Invalid})
1517 if f&flagMethod == 0 {
1519 return v.typ.toType()
1523 // v.typ describes the receiver, not the method type.
1524 i := int(v.flag) >> flagMethodShift
1525 if v.typ.Kind() == Interface {
1526 // Method on interface.
1527 tt := (*interfaceType)(unsafe.Pointer(v.typ))
1528 if i < 0 || i >= len(tt.methods) {
1529 panic("reflect: broken Value")
1532 return toCommonType(m.typ).toType()
1534 // Method on concrete type.
1535 ut := v.typ.uncommon()
1536 if ut == nil || i < 0 || i >= len(ut.methods) {
1537 panic("reflect: broken Value")
1540 return toCommonType(m.mtyp).toType()
1543 // Uint returns v's underlying value, as a uint64.
1544 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1545 func (v Value) Uint() uint64 {
1547 var p unsafe.Pointer
1548 if v.flag&flagIndir != 0 {
1551 // The escape analysis is good enough that &v.val
1552 // does not trigger a heap allocation.
1553 p = unsafe.Pointer(&v.val)
1557 return uint64(*(*uint)(p))
1559 return uint64(*(*uint8)(p))
1561 return uint64(*(*uint16)(p))
1563 return uint64(*(*uint32)(p))
1565 return uint64(*(*uint64)(p))
1567 return uint64(*(*uintptr)(p))
1569 panic(&ValueError{"reflect.Value.Uint", k})
1572 // UnsafeAddr returns a pointer to v's data.
1573 // It is for advanced clients that also import the "unsafe" package.
1574 // It panics if v is not addressable.
1575 func (v Value) UnsafeAddr() uintptr {
1577 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
1579 if v.flag&flagAddr == 0 {
1580 panic("reflect.Value.UnsafeAddr of unaddressable value")
1582 return uintptr(v.val)
1585 // StringHeader is the runtime representation of a string.
1586 // It cannot be used safely or portably.
1587 type StringHeader struct {
1592 // SliceHeader is the runtime representation of a slice.
1593 // It cannot be used safely or portably.
1594 type SliceHeader struct {
1600 func typesMustMatch(what string, t1, t2 Type) {
1602 panic(what + ": " + t1.String() + " != " + t2.String())
1606 // grow grows the slice s so that it can hold extra more values, allocating
1607 // more capacity if needed. It also returns the old and new slice lengths.
1608 func grow(s Value, extra int) (Value, int, int) {
1612 panic("reflect.Append: slice overflow")
1616 return s.Slice(0, i1), i0, i1
1629 t := MakeSlice(s.Type(), i1, m)
1634 // Append appends the values x to a slice s and returns the resulting slice.
1635 // As in Go, each x's value must be assignable to the slice's element type.
1636 func Append(s Value, x ...Value) Value {
1638 s, i0, i1 := grow(s, len(x))
1639 for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
1640 s.Index(i).Set(x[j])
1645 // AppendSlice appends a slice t to a slice s and returns the resulting slice.
1646 // The slices s and t must have the same element type.
1647 func AppendSlice(s, t Value) Value {
1650 typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
1651 s, i0, i1 := grow(s, t.Len())
1652 Copy(s.Slice(i0, i1), t)
1656 // Copy copies the contents of src into dst until either
1657 // dst has been filled or src has been exhausted.
1658 // It returns the number of elements copied.
1659 // Dst and src each must have kind Slice or Array, and
1660 // dst and src must have the same element type.
1661 func Copy(dst, src Value) int {
1663 if dk != Array && dk != Slice {
1664 panic(&ValueError{"reflect.Copy", dk})
1667 dst.mustBeAssignable()
1669 dst.mustBeExported()
1672 if sk != Array && sk != Slice {
1673 panic(&ValueError{"reflect.Copy", sk})
1675 src.mustBeExported()
1677 de := dst.typ.Elem()
1678 se := src.typ.Elem()
1679 typesMustMatch("reflect.Copy", de, se)
1682 if sn := src.Len(); n > sn {
1686 // If sk is an in-line array, cannot take its address.
1687 // Instead, copy element by element.
1688 if src.flag&flagIndir == 0 {
1689 for i := 0; i < n; i++ {
1690 dst.Index(i).Set(src.Index(i))
1695 // Copy via memmove.
1696 var da, sa unsafe.Pointer
1700 da = unsafe.Pointer((*SliceHeader)(dst.val).Data)
1705 sa = unsafe.Pointer((*SliceHeader)(src.val).Data)
1707 memmove(da, sa, uintptr(n)*de.Size())
1711 // A runtimeSelect is a single case passed to rselect.
1712 // This must match ../runtime/chan.c:/runtimeSelect
1713 type runtimeSelect struct {
1714 dir uintptr // 0, SendDir, or RecvDir
1715 typ *runtimeType // channel type
1716 ch iword // interface word for channel
1717 val iword // interface word for value (for SendDir)
1720 // rselect runs a select. It returns the index of the chosen case,
1721 // and if the case was a receive, the interface word of the received
1722 // value and the conventional OK bool to indicate whether the receive
1723 // corresponds to a sent value.
1724 func rselect([]runtimeSelect) (chosen int, recv iword, recvOK bool)
1726 // A SelectDir describes the communication direction of a select case.
1729 // NOTE: These values must match ../runtime/chan.c:/SelectDir.
1733 SelectSend // case Chan <- Send
1734 SelectRecv // case <-Chan:
1735 SelectDefault // default
1738 // A SelectCase describes a single case in a select operation.
1739 // The kind of case depends on Dir, the communication direction.
1741 // If Dir is SelectDefault, the case represents a default case.
1742 // Chan and Send must be zero Values.
1744 // If Dir is SelectSend, the case represents a send operation.
1745 // Normally Chan's underlying value must be a channel, and Send's underlying value must be
1746 // assignable to the channel's element type. As a special case, if Chan is a zero Value,
1747 // then the case is ignored, and the field Send will also be ignored and may be either zero
1750 // If Dir is SelectRecv, the case represents a receive operation.
1751 // Normally Chan's underlying value must be a channel and Send must be a zero Value.
1752 // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
1753 // When a receive operation is selected, the received Value is returned by Select.
1755 type SelectCase struct {
1756 Dir SelectDir // direction of case
1757 Chan Value // channel to use (for send or receive)
1758 Send Value // value to send (for send)
1761 // Select executes a select operation described by the list of cases.
1762 // Like the Go select statement, it blocks until one of the cases can
1763 // proceed and then executes that case. It returns the index of the chosen case
1764 // and, if that case was a receive operation, the value received and a
1765 // boolean indicating whether the value corresponds to a send on the channel
1766 // (as opposed to a zero value received because the channel is closed).
1767 func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
1768 // NOTE: Do not trust that caller is not modifying cases data underfoot.
1769 // The range is safe because the caller cannot modify our copy of the len
1770 // and each iteration makes its own copy of the value c.
1771 runcases := make([]runtimeSelect, len(cases))
1772 haveDefault := false
1773 for i, c := range cases {
1775 rc.dir = uintptr(c.Dir)
1778 panic("reflect.Select: invalid Dir")
1780 case SelectDefault: // default
1782 panic("reflect.Select: multiple default cases")
1785 if c.Chan.IsValid() {
1786 panic("reflect.Select: default case has Chan value")
1788 if c.Send.IsValid() {
1789 panic("reflect.Select: default case has Send value")
1799 tt := (*chanType)(unsafe.Pointer(ch.typ))
1800 if ChanDir(tt.dir)&SendDir == 0 {
1801 panic("reflect.Select: SendDir case using recv-only channel")
1803 rc.ch = *(*iword)(ch.iword())
1804 rc.typ = tt.runtimeType()
1807 panic("reflect.Select: SendDir case missing Send value")
1810 v = v.assignTo("reflect.Select", toCommonType(tt.elem), nil)
1814 if c.Send.IsValid() {
1815 panic("reflect.Select: RecvDir case has Send value")
1823 tt := (*chanType)(unsafe.Pointer(ch.typ))
1824 rc.typ = tt.runtimeType()
1825 if ChanDir(tt.dir)&RecvDir == 0 {
1826 panic("reflect.Select: RecvDir case using send-only channel")
1828 rc.ch = *(*iword)(ch.iword())
1832 chosen, word, recvOK := rselect(runcases)
1833 if runcases[chosen].dir == uintptr(SelectRecv) {
1834 tt := (*chanType)(unsafe.Pointer(toCommonType(runcases[chosen].typ)))
1835 typ := toCommonType(tt.elem)
1836 fl := flag(typ.Kind()) << flagKindShift
1837 if typ.Kind() != Ptr && typ.Kind() != UnsafePointer {
1840 recv = Value{typ, unsafe.Pointer(word), fl}
1842 return chosen, recv, recvOK
1849 // implemented in package runtime
1850 func unsafe_New(Type) unsafe.Pointer
1851 func unsafe_NewArray(Type, int) unsafe.Pointer
1853 // MakeSlice creates a new zero-initialized slice value
1854 // for the specified slice type, length, and capacity.
1855 func MakeSlice(typ Type, len, cap int) Value {
1856 if typ.Kind() != Slice {
1857 panic("reflect.MakeSlice of non-slice type")
1860 panic("reflect.MakeSlice: negative len")
1863 panic("reflect.MakeSlice: negative cap")
1866 panic("reflect.MakeSlice: len > cap")
1869 // Declare slice so that gc can see the base pointer in it.
1872 // Reinterpret as *SliceHeader to edit.
1873 s := (*SliceHeader)(unsafe.Pointer(&x))
1874 s.Data = uintptr(unsafe_NewArray(typ.Elem(), cap))
1878 return Value{typ.common(), unsafe.Pointer(&x), flagIndir | flag(Slice)<<flagKindShift}
1881 // MakeChan creates a new channel with the specified type and buffer size.
1882 func MakeChan(typ Type, buffer int) Value {
1883 if typ.Kind() != Chan {
1884 panic("reflect.MakeChan of non-chan type")
1887 panic("reflect.MakeChan: negative buffer size")
1889 if typ.ChanDir() != BothDir {
1890 panic("reflect.MakeChan: unidirectional channel type")
1892 ch := makechan(typ.runtimeType(), uint64(buffer))
1893 return Value{typ.common(), unsafe.Pointer(ch), flagIndir | (flag(Chan) << flagKindShift)}
1896 // MakeMap creates a new map of the specified type.
1897 func MakeMap(typ Type) Value {
1898 if typ.Kind() != Map {
1899 panic("reflect.MakeMap of non-map type")
1901 m := makemap(typ.runtimeType())
1902 return Value{typ.common(), unsafe.Pointer(m), flagIndir | (flag(Map) << flagKindShift)}
1905 // Indirect returns the value that v points to.
1906 // If v is a nil pointer, Indirect returns a zero Value.
1907 // If v is not a pointer, Indirect returns v.
1908 func Indirect(v Value) Value {
1909 if v.Kind() != Ptr {
1915 // ValueOf returns a new Value initialized to the concrete value
1916 // stored in the interface i. ValueOf(nil) returns the zero Value.
1917 func ValueOf(i interface{}) Value {
1922 // TODO(rsc): Eliminate this terrible hack.
1923 // In the call to packValue, eface.typ doesn't escape,
1924 // and eface.word is an integer. So it looks like
1925 // i (= eface) doesn't escape. But really it does,
1926 // because eface.word is actually a pointer.
1929 // For an interface value with the noAddr bit set,
1930 // the representation is identical to an empty interface.
1931 eface := *(*emptyInterface)(unsafe.Pointer(&i))
1932 typ := toCommonType(eface.typ)
1933 fl := flag(typ.Kind()) << flagKindShift
1934 if typ.Kind() != Ptr && typ.Kind() != UnsafePointer {
1937 return Value{typ, unsafe.Pointer(eface.word), fl}
1940 // Zero returns a Value representing the zero value for the specified type.
1941 // The result is different from the zero value of the Value struct,
1942 // which represents no value at all.
1943 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
1944 // The returned value is neither addressable nor settable.
1945 func Zero(typ Type) Value {
1947 panic("reflect: Zero(nil)")
1950 fl := flag(t.Kind()) << flagKindShift
1951 if t.Kind() == Ptr || t.Kind() == UnsafePointer {
1952 return Value{t, nil, fl}
1954 return Value{t, unsafe_New(typ), fl | flagIndir}
1957 // New returns a Value representing a pointer to a new zero value
1958 // for the specified type. That is, the returned Value's Type is PtrTo(t).
1959 func New(typ Type) Value {
1961 panic("reflect: New(nil)")
1963 ptr := unsafe_New(typ)
1964 fl := flag(Ptr) << flagKindShift
1965 return Value{typ.common().ptrTo(), ptr, fl}
1968 // NewAt returns a Value representing a pointer to a value of the
1969 // specified type, using p as that pointer.
1970 func NewAt(typ Type, p unsafe.Pointer) Value {
1971 fl := flag(Ptr) << flagKindShift
1972 return Value{typ.common().ptrTo(), p, fl}
1975 // assignTo returns a value v that can be assigned directly to typ.
1976 // It panics if v is not assignable to typ.
1977 // For a conversion to an interface type, target is a suggested scratch space to use.
1978 func (v Value) assignTo(context string, dst *commonType, target *interface{}) Value {
1979 if v.flag&flagMethod != 0 {
1980 panic(context + ": cannot assign method value to type " + dst.String())
1984 case directlyAssignable(dst, v.typ):
1985 // Overwrite type so that they match.
1986 // Same memory layout, so no harm done.
1988 fl := v.flag & (flagRO | flagAddr | flagIndir)
1989 fl |= flag(dst.Kind()) << flagKindShift
1990 return Value{dst, v.val, fl}
1992 case implements(dst, v.typ):
1994 target = new(interface{})
1996 x := valueInterface(v, false)
1997 if dst.NumMethod() == 0 {
2000 ifaceE2I(dst.runtimeType(), x, unsafe.Pointer(target))
2002 return Value{dst, unsafe.Pointer(target), flagIndir | flag(Interface)<<flagKindShift}
2006 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
2009 // Convert returns the value v converted to type t.
2010 // If the usual Go conversion rules do not allow conversion
2011 // of the value v to type t, Convert panics.
2012 func (v Value) Convert(t Type) Value {
2013 if v.flag&flagMethod != 0 {
2014 panic("reflect.Value.Convert: cannot convert method values")
2016 op := convertOp(t.common(), v.typ)
2018 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
2023 // convertOp returns the function to convert a value of type src
2024 // to a value of type dst. If the conversion is illegal, convertOp returns nil.
2025 func convertOp(dst, src *commonType) func(Value, Type) Value {
2027 case Int, Int8, Int16, Int32, Int64:
2029 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2031 case Float32, Float64:
2037 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2039 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2041 case Float32, Float64:
2044 return cvtUintString
2047 case Float32, Float64:
2049 case Int, Int8, Int16, Int32, Int64:
2051 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2053 case Float32, Float64:
2057 case Complex64, Complex128:
2059 case Complex64, Complex128:
2064 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
2065 switch dst.Elem().Kind() {
2067 return cvtStringBytes
2069 return cvtStringRunes
2074 if dst.Kind() == String && src.Elem().PkgPath() == "" {
2075 switch src.Elem().Kind() {
2077 return cvtBytesString
2079 return cvtRunesString
2084 // dst and src have same underlying type.
2085 if haveIdenticalUnderlyingType(dst, src) {
2089 // dst and src are unnamed pointer types with same underlying base type.
2090 if dst.Kind() == Ptr && dst.Name() == "" &&
2091 src.Kind() == Ptr && src.Name() == "" &&
2092 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common()) {
2096 if implements(dst, src) {
2097 if src.Kind() == Interface {
2106 // makeInt returns a Value of type t equal to bits (possibly truncated),
2107 // where t is a signed or unsigned int type.
2108 func makeInt(f flag, bits uint64, t Type) Value {
2110 if typ.size > ptrSize {
2111 // Assume ptrSize >= 4, so this must be uint64.
2112 ptr := unsafe_New(t)
2113 *(*uint64)(unsafe.Pointer(ptr)) = bits
2114 return Value{typ, ptr, f | flag(typ.Kind())<<flagKindShift}
2119 *(*uint8)(unsafe.Pointer(&w)) = uint8(bits)
2121 *(*uint16)(unsafe.Pointer(&w)) = uint16(bits)
2123 *(*uint32)(unsafe.Pointer(&w)) = uint32(bits)
2125 *(*uint64)(unsafe.Pointer(&w)) = uint64(bits)
2127 return Value{typ, unsafe.Pointer(&w), f | flag(typ.Kind())<<flagKindShift | flagIndir}
2130 // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2131 // where t is a float32 or float64 type.
2132 func makeFloat(f flag, v float64, t Type) Value {
2134 if typ.size > ptrSize {
2135 // Assume ptrSize >= 4, so this must be float64.
2136 ptr := unsafe_New(t)
2137 *(*float64)(unsafe.Pointer(ptr)) = v
2138 return Value{typ, ptr, f | flag(typ.Kind())<<flagKindShift}
2144 *(*float32)(unsafe.Pointer(&w)) = float32(v)
2146 *(*float64)(unsafe.Pointer(&w)) = v
2148 return Value{typ, unsafe.Pointer(&w), f | flag(typ.Kind())<<flagKindShift | flagIndir}
2151 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2152 // where t is a complex64 or complex128 type.
2153 func makeComplex(f flag, v complex128, t Type) Value {
2155 if typ.size > ptrSize {
2156 ptr := unsafe_New(t)
2159 *(*complex64)(unsafe.Pointer(ptr)) = complex64(v)
2161 *(*complex128)(unsafe.Pointer(ptr)) = v
2163 return Value{typ, ptr, f | flag(typ.Kind())<<flagKindShift}
2166 // Assume ptrSize <= 8 so this must be complex64.
2168 *(*complex64)(unsafe.Pointer(&w)) = complex64(v)
2169 return Value{typ, unsafe.Pointer(&w), f | flag(typ.Kind())<<flagKindShift | flagIndir}
2172 func makeString(f flag, v string, t Type) Value {
2173 ret := New(t).Elem()
2175 ret.flag = ret.flag&^flagAddr | f
2179 func makeBytes(f flag, v []byte, t Type) Value {
2180 ret := New(t).Elem()
2182 ret.flag = ret.flag&^flagAddr | f
2186 func makeRunes(f flag, v []rune, t Type) Value {
2187 ret := New(t).Elem()
2189 ret.flag = ret.flag&^flagAddr | f
2193 // These conversion functions are returned by convertOp
2194 // for classes of conversions. For example, the first function, cvtInt,
2195 // takes any value v of signed int type and returns the value converted
2196 // to type t, where t is any signed or unsigned int type.
2198 // convertOp: intXX -> [u]intXX
2199 func cvtInt(v Value, t Type) Value {
2200 return makeInt(v.flag&flagRO, uint64(v.Int()), t)
2203 // convertOp: uintXX -> [u]intXX
2204 func cvtUint(v Value, t Type) Value {
2205 return makeInt(v.flag&flagRO, v.Uint(), t)
2208 // convertOp: floatXX -> intXX
2209 func cvtFloatInt(v Value, t Type) Value {
2210 return makeInt(v.flag&flagRO, uint64(int64(v.Float())), t)
2213 // convertOp: floatXX -> uintXX
2214 func cvtFloatUint(v Value, t Type) Value {
2215 return makeInt(v.flag&flagRO, uint64(v.Float()), t)
2218 // convertOp: intXX -> floatXX
2219 func cvtIntFloat(v Value, t Type) Value {
2220 return makeFloat(v.flag&flagRO, float64(v.Int()), t)
2223 // convertOp: uintXX -> floatXX
2224 func cvtUintFloat(v Value, t Type) Value {
2225 return makeFloat(v.flag&flagRO, float64(v.Uint()), t)
2228 // convertOp: floatXX -> floatXX
2229 func cvtFloat(v Value, t Type) Value {
2230 return makeFloat(v.flag&flagRO, v.Float(), t)
2233 // convertOp: complexXX -> complexXX
2234 func cvtComplex(v Value, t Type) Value {
2235 return makeComplex(v.flag&flagRO, v.Complex(), t)
2238 // convertOp: intXX -> string
2239 func cvtIntString(v Value, t Type) Value {
2240 return makeString(v.flag&flagRO, string(v.Int()), t)
2243 // convertOp: uintXX -> string
2244 func cvtUintString(v Value, t Type) Value {
2245 return makeString(v.flag&flagRO, string(v.Uint()), t)
2248 // convertOp: []byte -> string
2249 func cvtBytesString(v Value, t Type) Value {
2250 return makeString(v.flag&flagRO, string(v.Bytes()), t)
2253 // convertOp: string -> []byte
2254 func cvtStringBytes(v Value, t Type) Value {
2255 return makeBytes(v.flag&flagRO, []byte(v.String()), t)
2258 // convertOp: []rune -> string
2259 func cvtRunesString(v Value, t Type) Value {
2260 return makeString(v.flag&flagRO, string(v.runes()), t)
2263 // convertOp: string -> []rune
2264 func cvtStringRunes(v Value, t Type) Value {
2265 return makeRunes(v.flag&flagRO, []rune(v.String()), t)
2268 // convertOp: direct copy
2269 func cvtDirect(v Value, typ Type) Value {
2273 if f&flagAddr != 0 {
2274 // indirect, mutable word - make a copy
2275 ptr := unsafe_New(t)
2276 memmove(ptr, val, t.size)
2280 return Value{t, val, v.flag&flagRO | f}
2283 // convertOp: concrete -> interface
2284 func cvtT2I(v Value, typ Type) Value {
2285 target := new(interface{})
2286 x := valueInterface(v, false)
2287 if typ.NumMethod() == 0 {
2290 ifaceE2I(typ.runtimeType(), x, unsafe.Pointer(target))
2292 return Value{typ.common(), unsafe.Pointer(target), v.flag&flagRO | flagIndir | flag(Interface)<<flagKindShift}
2295 // convertOp: interface -> interface
2296 func cvtI2I(v Value, typ Type) Value {
2299 ret.flag |= v.flag & flagRO
2302 return cvtT2I(v.Elem(), typ)
2305 // implemented in ../pkg/runtime
2306 func chancap(ch iword) int
2307 func chanclose(ch iword)
2308 func chanlen(ch iword) int
2309 func chanrecv(t *runtimeType, ch iword, nb bool) (val iword, selected, received bool)
2310 func chansend(t *runtimeType, ch iword, val iword, nb bool) bool
2312 func makechan(typ *runtimeType, size uint64) (ch iword)
2313 func makemap(t *runtimeType) (m iword)
2314 func mapaccess(t *runtimeType, m iword, key iword) (val iword, ok bool)
2315 func mapassign(t *runtimeType, m iword, key, val iword, ok bool)
2316 func mapiterinit(t *runtimeType, m iword) *byte
2317 func mapiterkey(it *byte) (key iword, ok bool)
2318 func mapiternext(it *byte)
2319 func maplen(m iword) int
2321 func call(typ *commonType, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer)
2322 func ifaceE2I(t *runtimeType, src interface{}, dst unsafe.Pointer)
2324 // Dummy annotation marking that the value x escapes,
2325 // for use in cases where the reflect code is so clever that
2326 // the compiler cannot follow.
2327 func escapes(x interface{}) {