testuite: fix libtdc++ libatomic flags
[official-gcc.git] / libgo / go / reflect / value.go
blob0b4f094f1b757e2c8e9958ed7fe66b55f3c61d40
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.
5 package reflect
7 import (
8 "internal/unsafeheader"
9 "math"
10 "runtime"
11 "unsafe"
14 const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const
16 // Value is the reflection interface to a Go value.
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.
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.
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.
34 // To compare two Values, compare the results of the Interface method.
35 // Using == on two Values does not compare the underlying values
36 // they represent.
37 type Value struct {
38 // typ holds the type of the value represented by a Value.
39 typ *rtype
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
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
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.
66 type flag uintptr
68 const (
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
81 func (f flag) kind() Kind {
82 return Kind(f & flagKindMask)
85 func (f flag) ro() flag {
86 if f&flagRO != 0 {
87 return flagStickyRO
89 return 0
92 // pointer returns the underlying pointer represented by v.
93 // v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer
94 // if v.Kind() == Ptr, the base type must not be go:notinheap.
95 func (v Value) pointer() unsafe.Pointer {
96 if v.typ.size != ptrSize || !v.typ.pointers() {
97 panic("can't call pointer on a non-pointer Value")
99 if v.flag&flagIndir != 0 {
100 return *(*unsafe.Pointer)(v.ptr)
102 return v.ptr
105 // packEface converts v to the empty interface.
106 func packEface(v Value) interface{} {
107 t := v.typ
108 var i interface{}
109 e := (*emptyInterface)(unsafe.Pointer(&i))
110 // First, fill in the data portion of the interface.
111 switch {
112 case ifaceIndir(t):
113 if v.flag&flagIndir == 0 {
114 panic("bad indir")
116 // Value is indirect, and so is the interface we're making.
117 ptr := v.ptr
118 if v.flag&flagAddr != 0 {
119 // TODO: pass safe boolean from valueInterface so
120 // we don't need to copy if safe==true?
121 c := unsafe_New(t)
122 typedmemmove(t, c, ptr)
123 ptr = c
125 e.word = ptr
126 case v.flag&flagIndir != 0:
127 // Value is indirect, but interface is direct. We need
128 // to load the data at v.ptr into the interface data word.
129 e.word = *(*unsafe.Pointer)(v.ptr)
130 default:
131 // Value is direct, and so is the interface.
132 e.word = v.ptr
134 // Now, fill in the type portion. We're very careful here not
135 // to have any operation between the e.word and e.typ assignments
136 // that would let the garbage collector observe the partially-built
137 // interface value.
138 e.typ = t
139 return i
142 // unpackEface converts the empty interface i to a Value.
143 func unpackEface(i interface{}) Value {
144 e := (*emptyInterface)(unsafe.Pointer(&i))
145 // NOTE: don't read e.word until we know whether it is really a pointer or not.
146 t := e.typ
147 if t == nil {
148 return Value{}
150 f := flag(t.Kind())
151 if ifaceIndir(t) {
152 f |= flagIndir
154 return Value{t, e.word, f}
157 // A ValueError occurs when a Value method is invoked on
158 // a Value that does not support it. Such cases are documented
159 // in the description of each method.
160 type ValueError struct {
161 Method string
162 Kind Kind
165 func (e *ValueError) Error() string {
166 if e.Kind == 0 {
167 return "reflect: call of " + e.Method + " on zero Value"
169 return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
172 // methodName returns the name of the calling method,
173 // assumed to be two stack frames above.
174 func methodName() string {
175 pc, _, _, _ := runtime.Caller(2)
176 f := runtime.FuncForPC(pc)
177 if f == nil {
178 return "unknown method"
180 return f.Name()
183 // methodNameSkip is like methodName, but skips another stack frame.
184 // This is a separate function so that reflect.flag.mustBe will be inlined.
185 func methodNameSkip() string {
186 pc, _, _, _ := runtime.Caller(3)
187 f := runtime.FuncForPC(pc)
188 if f == nil {
189 return "unknown method"
191 return f.Name()
194 // emptyInterface is the header for an interface{} value.
195 type emptyInterface struct {
196 typ *rtype
197 word unsafe.Pointer
200 // nonEmptyInterface is the header for an interface value with methods.
201 type nonEmptyInterface struct {
202 // see ../runtime/iface.go:/Itab
203 itab *struct {
204 typ *rtype // dynamic concrete type
205 fun [100000]unsafe.Pointer // method table
207 word unsafe.Pointer
210 // mustBe panics if f's kind is not expected.
211 // Making this a method on flag instead of on Value
212 // (and embedding flag in Value) means that we can write
213 // the very clear v.mustBe(Bool) and have it compile into
214 // v.flag.mustBe(Bool), which will only bother to copy the
215 // single important word for the receiver.
216 func (f flag) mustBe(expected Kind) {
217 // TODO(mvdan): use f.kind() again once mid-stack inlining gets better
218 if Kind(f&flagKindMask) != expected {
219 panic(&ValueError{methodName(), f.kind()})
223 // mustBeExported panics if f records that the value was obtained using
224 // an unexported field.
225 func (f flag) mustBeExported() {
226 if f == 0 || f&flagRO != 0 {
227 f.mustBeExportedSlow()
231 func (f flag) mustBeExportedSlow() {
232 if f == 0 {
233 panic(&ValueError{methodNameSkip(), Invalid})
235 if f&flagRO != 0 {
236 panic("reflect: " + methodNameSkip() + " using value obtained using unexported field")
240 // mustBeAssignable panics if f records that the value is not assignable,
241 // which is to say that either it was obtained using an unexported field
242 // or it is not addressable.
243 func (f flag) mustBeAssignable() {
244 if f&flagRO != 0 || f&flagAddr == 0 {
245 f.mustBeAssignableSlow()
249 func (f flag) mustBeAssignableSlow() {
250 if f == 0 {
251 panic(&ValueError{methodNameSkip(), Invalid})
253 // Assignable if addressable and not read-only.
254 if f&flagRO != 0 {
255 panic("reflect: " + methodNameSkip() + " using value obtained using unexported field")
257 if f&flagAddr == 0 {
258 panic("reflect: " + methodNameSkip() + " using unaddressable value")
262 // Addr returns a pointer value representing the address of v.
263 // It panics if CanAddr() returns false.
264 // Addr is typically used to obtain a pointer to a struct field
265 // or slice element in order to call a method that requires a
266 // pointer receiver.
267 func (v Value) Addr() Value {
268 if v.flag&flagAddr == 0 {
269 panic("reflect.Value.Addr of unaddressable value")
271 // Preserve flagRO instead of using v.flag.ro() so that
272 // v.Addr().Elem() is equivalent to v (#32772)
273 fl := v.flag & flagRO
274 return Value{v.typ.ptrTo(), v.ptr, fl | flag(Ptr)}
277 // Bool returns v's underlying value.
278 // It panics if v's kind is not Bool.
279 func (v Value) Bool() bool {
280 v.mustBe(Bool)
281 return *(*bool)(v.ptr)
284 // Bytes returns v's underlying value.
285 // It panics if v's underlying value is not a slice of bytes.
286 func (v Value) Bytes() []byte {
287 v.mustBe(Slice)
288 if v.typ.Elem().Kind() != Uint8 {
289 panic("reflect.Value.Bytes of non-byte slice")
291 // Slice is always bigger than a word; assume flagIndir.
292 return *(*[]byte)(v.ptr)
295 // runes returns v's underlying value.
296 // It panics if v's underlying value is not a slice of runes (int32s).
297 func (v Value) runes() []rune {
298 v.mustBe(Slice)
299 if v.typ.Elem().Kind() != Int32 {
300 panic("reflect.Value.Bytes of non-rune slice")
302 // Slice is always bigger than a word; assume flagIndir.
303 return *(*[]rune)(v.ptr)
306 // CanAddr reports whether the value's address can be obtained with Addr.
307 // Such values are called addressable. A value is addressable if it is
308 // an element of a slice, an element of an addressable array,
309 // a field of an addressable struct, or the result of dereferencing a pointer.
310 // If CanAddr returns false, calling Addr will panic.
311 func (v Value) CanAddr() bool {
312 return v.flag&flagAddr != 0
315 // CanSet reports whether the value of v can be changed.
316 // A Value can be changed only if it is addressable and was not
317 // obtained by the use of unexported struct fields.
318 // If CanSet returns false, calling Set or any type-specific
319 // setter (e.g., SetBool, SetInt) will panic.
320 func (v Value) CanSet() bool {
321 return v.flag&(flagAddr|flagRO) == flagAddr
324 // Call calls the function v with the input arguments in.
325 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
326 // Call panics if v's Kind is not Func.
327 // It returns the output results as Values.
328 // As in Go, each input argument must be assignable to the
329 // type of the function's corresponding input parameter.
330 // If v is a variadic function, Call creates the variadic slice parameter
331 // itself, copying in the corresponding values.
332 func (v Value) Call(in []Value) []Value {
333 v.mustBe(Func)
334 v.mustBeExported()
335 return v.call("Call", in)
338 // CallSlice calls the variadic function v with the input arguments in,
339 // assigning the slice in[len(in)-1] to v's final variadic argument.
340 // For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).
341 // CallSlice panics if v's Kind is not Func or if v is not variadic.
342 // It returns the output results as Values.
343 // As in Go, each input argument must be assignable to the
344 // type of the function's corresponding input parameter.
345 func (v Value) CallSlice(in []Value) []Value {
346 v.mustBe(Func)
347 v.mustBeExported()
348 return v.call("CallSlice", in)
351 var callGC bool // for testing; see TestCallMethodJump
353 func (v Value) call(op string, in []Value) []Value {
354 // Get function pointer, type.
355 t := (*funcType)(unsafe.Pointer(v.typ))
356 var (
357 fn unsafe.Pointer
358 rcvr Value
360 if v.flag&flagMethod != 0 {
361 rcvr = v
362 _, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
363 } else if v.flag&flagIndir != 0 {
364 fn = *(*unsafe.Pointer)(v.ptr)
365 } else {
366 fn = v.ptr
369 if fn == nil {
370 panic("reflect.Value.Call: call of nil function")
373 isSlice := op == "CallSlice"
374 n := t.NumIn()
375 if isSlice {
376 if !t.IsVariadic() {
377 panic("reflect: CallSlice of non-variadic function")
379 if len(in) < n {
380 panic("reflect: CallSlice with too few input arguments")
382 if len(in) > n {
383 panic("reflect: CallSlice with too many input arguments")
385 } else {
386 if t.IsVariadic() {
389 if len(in) < n {
390 panic("reflect: Call with too few input arguments")
392 if !t.IsVariadic() && len(in) > n {
393 panic("reflect: Call with too many input arguments")
396 for _, x := range in {
397 if x.Kind() == Invalid {
398 panic("reflect: " + op + " using zero Value argument")
401 for i := 0; i < n; i++ {
402 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
403 panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String())
406 if !isSlice && t.IsVariadic() {
407 // prepare slice for remaining values
408 m := len(in) - n
409 slice := MakeSlice(t.In(n), m, m)
410 elem := t.In(n).Elem()
411 for i := 0; i < m; i++ {
412 x := in[n+i]
413 if xt := x.Type(); !xt.AssignableTo(elem) {
414 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
416 slice.Index(i).Set(x)
418 origIn := in
419 in = make([]Value, n+1)
420 copy(in[:n], origIn)
421 in[n] = slice
424 nin := len(in)
425 if nin != t.NumIn() {
426 panic("reflect.Value.Call: wrong argument count")
428 nout := t.NumOut()
430 if v.flag&flagMethod != 0 {
431 nin++
433 firstPointer := len(in) > 0 && ifaceIndir(t.In(0).common()) && v.flag&flagMethodFn != 0
434 params := make([]unsafe.Pointer, nin)
435 off := 0
436 if v.flag&flagMethod != 0 {
437 // Hard-wired first argument.
438 p := new(unsafe.Pointer)
439 if rcvr.typ.Kind() == Interface {
440 *p = unsafe.Pointer((*nonEmptyInterface)(v.ptr).word)
441 } else if rcvr.typ.Kind() == Ptr || rcvr.typ.Kind() == UnsafePointer {
442 *p = rcvr.pointer()
443 } else {
444 *p = rcvr.ptr
446 params[0] = unsafe.Pointer(p)
447 off = 1
449 for i, pv := range in {
450 pv.mustBeExported()
451 targ := t.In(i).(*rtype)
452 pv = pv.assignTo("reflect.Value.Call", targ, nil)
453 if pv.flag&flagIndir == 0 {
454 p := new(unsafe.Pointer)
455 *p = pv.ptr
456 params[off] = unsafe.Pointer(p)
457 } else {
458 params[off] = pv.ptr
460 if i == 0 && firstPointer {
461 p := new(unsafe.Pointer)
462 *p = params[off]
463 params[off] = unsafe.Pointer(p)
465 off++
468 ret := make([]Value, nout)
469 results := make([]unsafe.Pointer, nout)
470 for i := 0; i < nout; i++ {
471 tv := t.Out(i)
472 v := New(tv)
473 results[i] = v.pointer()
474 fl := flagIndir | flag(tv.Kind())
475 ret[i] = Value{tv.common(), v.pointer(), fl}
478 var pp *unsafe.Pointer
479 if len(params) > 0 {
480 pp = &params[0]
482 var pr *unsafe.Pointer
483 if len(results) > 0 {
484 pr = &results[0]
487 call(t, fn, v.flag&flagMethod != 0, firstPointer, pp, pr)
489 // For testing; see TestCallMethodJump.
490 if callGC {
491 runtime.GC()
494 return ret
497 // methodReceiver returns information about the receiver
498 // described by v. The Value v may or may not have the
499 // flagMethod bit set, so the kind cached in v.flag should
500 // not be used.
501 // The return value rcvrtype gives the method's actual receiver type.
502 // The return value t gives the method type signature (without the receiver).
503 // The return value fn is a pointer to the method code.
504 func methodReceiver(op string, v Value, methodIndex int) (rcvrtype *rtype, t *funcType, fn unsafe.Pointer) {
505 i := methodIndex
506 if v.typ.Kind() == Interface {
507 tt := (*interfaceType)(unsafe.Pointer(v.typ))
508 if uint(i) >= uint(len(tt.methods)) {
509 panic("reflect: internal error: invalid method index")
511 m := &tt.methods[i]
512 if m.pkgPath != nil {
513 panic("reflect: " + op + " of unexported method")
515 iface := (*nonEmptyInterface)(v.ptr)
516 if iface.itab == nil {
517 panic("reflect: " + op + " of method on nil interface value")
519 rcvrtype = iface.itab.typ
520 fn = unsafe.Pointer(&iface.itab.fun[i])
521 t = (*funcType)(unsafe.Pointer(m.typ))
522 } else {
523 rcvrtype = v.typ
524 ms := v.typ.exportedMethods()
525 if uint(i) >= uint(len(ms)) {
526 panic("reflect: internal error: invalid method index")
528 m := ms[i]
529 if m.pkgPath != nil {
530 panic("reflect: " + op + " of unexported method")
532 fn = unsafe.Pointer(&m.tfn)
533 t = (*funcType)(unsafe.Pointer(m.mtyp))
535 return
538 // v is a method receiver. Store at p the word which is used to
539 // encode that receiver at the start of the argument list.
540 // Reflect uses the "interface" calling convention for
541 // methods, which always uses one word to record the receiver.
542 func storeRcvr(v Value, p unsafe.Pointer) {
543 t := v.typ
544 if t.Kind() == Interface {
545 // the interface data word becomes the receiver word
546 iface := (*nonEmptyInterface)(v.ptr)
547 *(*unsafe.Pointer)(p) = iface.word
548 } else if v.flag&flagIndir != 0 && !ifaceIndir(t) {
549 *(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
550 } else {
551 *(*unsafe.Pointer)(p) = v.ptr
555 // align returns the result of rounding x up to a multiple of n.
556 // n must be a power of two.
557 func align(x, n uintptr) uintptr {
558 return (x + n - 1) &^ (n - 1)
561 // funcName returns the name of f, for use in error messages.
562 func funcName(f func([]Value) []Value) string {
563 pc := *(*uintptr)(unsafe.Pointer(&f))
564 rf := runtime.FuncForPC(pc)
565 if rf != nil {
566 return rf.Name()
568 return "closure"
571 // Cap returns v's capacity.
572 // It panics if v's Kind is not Array, Chan, or Slice.
573 func (v Value) Cap() int {
574 k := v.kind()
575 switch k {
576 case Array:
577 return v.typ.Len()
578 case Chan:
579 return chancap(v.pointer())
580 case Slice:
581 // Slice is always bigger than a word; assume flagIndir.
582 return (*unsafeheader.Slice)(v.ptr).Cap
584 panic(&ValueError{"reflect.Value.Cap", v.kind()})
587 // Close closes the channel v.
588 // It panics if v's Kind is not Chan.
589 func (v Value) Close() {
590 v.mustBe(Chan)
591 v.mustBeExported()
592 chanclose(v.pointer())
595 // Complex returns v's underlying value, as a complex128.
596 // It panics if v's Kind is not Complex64 or Complex128
597 func (v Value) Complex() complex128 {
598 k := v.kind()
599 switch k {
600 case Complex64:
601 return complex128(*(*complex64)(v.ptr))
602 case Complex128:
603 return *(*complex128)(v.ptr)
605 panic(&ValueError{"reflect.Value.Complex", v.kind()})
608 // Elem returns the value that the interface v contains
609 // or that the pointer v points to.
610 // It panics if v's Kind is not Interface or Ptr.
611 // It returns the zero Value if v is nil.
612 func (v Value) Elem() Value {
613 k := v.kind()
614 switch k {
615 case Interface:
616 var eface interface{}
617 if v.typ.NumMethod() == 0 {
618 eface = *(*interface{})(v.ptr)
619 } else {
620 eface = (interface{})(*(*interface {
622 })(v.ptr))
624 x := unpackEface(eface)
625 if x.flag != 0 {
626 x.flag |= v.flag.ro()
628 return x
629 case Ptr:
630 ptr := v.ptr
631 if v.flag&flagIndir != 0 {
632 ptr = *(*unsafe.Pointer)(ptr)
634 // The returned value's address is v's value.
635 if ptr == nil {
636 return Value{}
638 tt := (*ptrType)(unsafe.Pointer(v.typ))
639 typ := tt.elem
640 fl := v.flag&flagRO | flagIndir | flagAddr
641 fl |= flag(typ.Kind())
642 return Value{typ, ptr, fl}
644 panic(&ValueError{"reflect.Value.Elem", v.kind()})
647 // Field returns the i'th field of the struct v.
648 // It panics if v's Kind is not Struct or i is out of range.
649 func (v Value) Field(i int) Value {
650 if v.kind() != Struct {
651 panic(&ValueError{"reflect.Value.Field", v.kind()})
653 tt := (*structType)(unsafe.Pointer(v.typ))
654 if uint(i) >= uint(len(tt.fields)) {
655 panic("reflect: Field index out of range")
657 field := &tt.fields[i]
658 typ := field.typ
660 // Inherit permission bits from v, but clear flagEmbedRO.
661 fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind())
662 // Using an unexported field forces flagRO.
663 if field.pkgPath != nil {
664 if field.embedded() {
665 fl |= flagEmbedRO
666 } else {
667 fl |= flagStickyRO
670 // Either flagIndir is set and v.ptr points at struct,
671 // or flagIndir is not set and v.ptr is the actual struct data.
672 // In the former case, we want v.ptr + offset.
673 // In the latter case, we must have field.offset = 0,
674 // so v.ptr + field.offset is still the correct address.
675 ptr := add(v.ptr, field.offset(), "same as non-reflect &v.field")
676 return Value{typ, ptr, fl}
679 // FieldByIndex returns the nested field corresponding to index.
680 // It panics if v's Kind is not struct.
681 func (v Value) FieldByIndex(index []int) Value {
682 if len(index) == 1 {
683 return v.Field(index[0])
685 v.mustBe(Struct)
686 for i, x := range index {
687 if i > 0 {
688 if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct {
689 if v.IsNil() {
690 panic("reflect: indirection through nil pointer to embedded struct")
692 v = v.Elem()
695 v = v.Field(x)
697 return v
700 // FieldByName returns the struct field with the given name.
701 // It returns the zero Value if no field was found.
702 // It panics if v's Kind is not struct.
703 func (v Value) FieldByName(name string) Value {
704 v.mustBe(Struct)
705 if f, ok := v.typ.FieldByName(name); ok {
706 return v.FieldByIndex(f.Index)
708 return Value{}
711 // FieldByNameFunc returns the struct field with a name
712 // that satisfies the match function.
713 // It panics if v's Kind is not struct.
714 // It returns the zero Value if no field was found.
715 func (v Value) FieldByNameFunc(match func(string) bool) Value {
716 if f, ok := v.typ.FieldByNameFunc(match); ok {
717 return v.FieldByIndex(f.Index)
719 return Value{}
722 // Float returns v's underlying value, as a float64.
723 // It panics if v's Kind is not Float32 or Float64
724 func (v Value) Float() float64 {
725 k := v.kind()
726 switch k {
727 case Float32:
728 return float64(*(*float32)(v.ptr))
729 case Float64:
730 return *(*float64)(v.ptr)
732 panic(&ValueError{"reflect.Value.Float", v.kind()})
735 var uint8Type = TypeOf(uint8(0)).(*rtype)
737 // Index returns v's i'th element.
738 // It panics if v's Kind is not Array, Slice, or String or i is out of range.
739 func (v Value) Index(i int) Value {
740 switch v.kind() {
741 case Array:
742 tt := (*arrayType)(unsafe.Pointer(v.typ))
743 if uint(i) >= uint(tt.len) {
744 panic("reflect: array index out of range")
746 typ := tt.elem
747 offset := uintptr(i) * typ.size
749 // Either flagIndir is set and v.ptr points at array,
750 // or flagIndir is not set and v.ptr is the actual array data.
751 // In the former case, we want v.ptr + offset.
752 // In the latter case, we must be doing Index(0), so offset = 0,
753 // so v.ptr + offset is still the correct address.
754 val := add(v.ptr, offset, "same as &v[i], i < tt.len")
755 fl := v.flag&(flagIndir|flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array
756 return Value{typ, val, fl}
758 case Slice:
759 // Element flag same as Elem of Ptr.
760 // Addressable, indirect, possibly read-only.
761 s := (*unsafeheader.Slice)(v.ptr)
762 if uint(i) >= uint(s.Len) {
763 panic("reflect: slice index out of range")
765 tt := (*sliceType)(unsafe.Pointer(v.typ))
766 typ := tt.elem
767 val := arrayAt(s.Data, i, typ.size, "i < s.Len")
768 fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind())
769 return Value{typ, val, fl}
771 case String:
772 s := (*unsafeheader.String)(v.ptr)
773 if uint(i) >= uint(s.Len) {
774 panic("reflect: string index out of range")
776 p := arrayAt(s.Data, i, 1, "i < s.Len")
777 fl := v.flag.ro() | flag(Uint8) | flagIndir
778 return Value{uint8Type, p, fl}
780 panic(&ValueError{"reflect.Value.Index", v.kind()})
783 // Int returns v's underlying value, as an int64.
784 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
785 func (v Value) Int() int64 {
786 k := v.kind()
787 p := v.ptr
788 switch k {
789 case Int:
790 return int64(*(*int)(p))
791 case Int8:
792 return int64(*(*int8)(p))
793 case Int16:
794 return int64(*(*int16)(p))
795 case Int32:
796 return int64(*(*int32)(p))
797 case Int64:
798 return *(*int64)(p)
800 panic(&ValueError{"reflect.Value.Int", v.kind()})
803 // CanInterface reports whether Interface can be used without panicking.
804 func (v Value) CanInterface() bool {
805 if v.flag == 0 {
806 panic(&ValueError{"reflect.Value.CanInterface", Invalid})
808 return v.flag&flagRO == 0
811 // Interface returns v's current value as an interface{}.
812 // It is equivalent to:
813 // var i interface{} = (v's underlying value)
814 // It panics if the Value was obtained by accessing
815 // unexported struct fields.
816 func (v Value) Interface() (i interface{}) {
817 return valueInterface(v, true)
820 func valueInterface(v Value, safe bool) interface{} {
821 if v.flag == 0 {
822 panic(&ValueError{"reflect.Value.Interface", Invalid})
824 if safe && v.flag&flagRO != 0 {
825 // Do not allow access to unexported values via Interface,
826 // because they might be pointers that should not be
827 // writable or methods or function that should not be callable.
828 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
830 if v.flag&flagMethod != 0 {
831 v = makeMethodValue("Interface", v)
834 if v.flag&flagMethodFn != 0 {
835 if v.typ.Kind() != Func {
836 panic("reflect: MethodFn of non-Func")
838 ft := (*funcType)(unsafe.Pointer(v.typ))
839 if ft.in[0].Kind() != Ptr {
840 v = makeValueMethod(v)
844 if v.kind() == Interface {
845 // Special case: return the element inside the interface.
846 // Empty interface has one layout, all interfaces with
847 // methods have a second layout.
848 if v.NumMethod() == 0 {
849 return *(*interface{})(v.ptr)
851 return *(*interface {
853 })(v.ptr)
856 // TODO: pass safe to packEface so we don't need to copy if safe==true?
857 return packEface(v)
860 // InterfaceData returns the interface v's value as a uintptr pair.
861 // It panics if v's Kind is not Interface.
862 func (v Value) InterfaceData() [2]uintptr {
863 // TODO: deprecate this
864 v.mustBe(Interface)
865 // We treat this as a read operation, so we allow
866 // it even for unexported data, because the caller
867 // has to import "unsafe" to turn it into something
868 // that can be abused.
869 // Interface value is always bigger than a word; assume flagIndir.
870 return *(*[2]uintptr)(v.ptr)
873 // IsNil reports whether its argument v is nil. The argument must be
874 // a chan, func, interface, map, pointer, or slice value; if it is
875 // not, IsNil panics. Note that IsNil is not always equivalent to a
876 // regular comparison with nil in Go. For example, if v was created
877 // by calling ValueOf with an uninitialized interface variable i,
878 // i==nil will be true but v.IsNil will panic as v will be the zero
879 // Value.
880 func (v Value) IsNil() bool {
881 k := v.kind()
882 switch k {
883 case Chan, Func, Map, Ptr, UnsafePointer:
884 if v.flag&flagMethod != 0 {
885 return false
887 ptr := v.ptr
888 if v.flag&flagIndir != 0 {
889 ptr = *(*unsafe.Pointer)(ptr)
891 return ptr == nil
892 case Interface, Slice:
893 // Both interface and slice are nil if first word is 0.
894 // Both are always bigger than a word; assume flagIndir.
895 return *(*unsafe.Pointer)(v.ptr) == nil
897 panic(&ValueError{"reflect.Value.IsNil", v.kind()})
900 // IsValid reports whether v represents a value.
901 // It returns false if v is the zero Value.
902 // If IsValid returns false, all other methods except String panic.
903 // Most functions and methods never return an invalid Value.
904 // If one does, its documentation states the conditions explicitly.
905 func (v Value) IsValid() bool {
906 return v.flag != 0
909 // IsZero reports whether v is the zero value for its type.
910 // It panics if the argument is invalid.
911 func (v Value) IsZero() bool {
912 switch v.kind() {
913 case Bool:
914 return !v.Bool()
915 case Int, Int8, Int16, Int32, Int64:
916 return v.Int() == 0
917 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
918 return v.Uint() == 0
919 case Float32, Float64:
920 return math.Float64bits(v.Float()) == 0
921 case Complex64, Complex128:
922 c := v.Complex()
923 return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0
924 case Array:
925 for i := 0; i < v.Len(); i++ {
926 if !v.Index(i).IsZero() {
927 return false
930 return true
931 case Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer:
932 return v.IsNil()
933 case String:
934 return v.Len() == 0
935 case Struct:
936 for i := 0; i < v.NumField(); i++ {
937 if !v.Field(i).IsZero() {
938 return false
941 return true
942 default:
943 // This should never happens, but will act as a safeguard for
944 // later, as a default value doesn't makes sense here.
945 panic(&ValueError{"reflect.Value.IsZero", v.Kind()})
949 // Kind returns v's Kind.
950 // If v is the zero Value (IsValid returns false), Kind returns Invalid.
951 func (v Value) Kind() Kind {
952 return v.kind()
955 // Len returns v's length.
956 // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
957 func (v Value) Len() int {
958 k := v.kind()
959 switch k {
960 case Array:
961 tt := (*arrayType)(unsafe.Pointer(v.typ))
962 return int(tt.len)
963 case Chan:
964 return chanlen(v.pointer())
965 case Map:
966 return maplen(v.pointer())
967 case Slice:
968 // Slice is bigger than a word; assume flagIndir.
969 return (*unsafeheader.Slice)(v.ptr).Len
970 case String:
971 // String is bigger than a word; assume flagIndir.
972 return (*unsafeheader.String)(v.ptr).Len
974 panic(&ValueError{"reflect.Value.Len", v.kind()})
977 // MapIndex returns the value associated with key in the map v.
978 // It panics if v's Kind is not Map.
979 // It returns the zero Value if key is not found in the map or if v represents a nil map.
980 // As in Go, the key's value must be assignable to the map's key type.
981 func (v Value) MapIndex(key Value) Value {
982 v.mustBe(Map)
983 tt := (*mapType)(unsafe.Pointer(v.typ))
985 // Do not require key to be exported, so that DeepEqual
986 // and other programs can use all the keys returned by
987 // MapKeys as arguments to MapIndex. If either the map
988 // or the key is unexported, though, the result will be
989 // considered unexported. This is consistent with the
990 // behavior for structs, which allow read but not write
991 // of unexported fields.
992 key = key.assignTo("reflect.Value.MapIndex", tt.key, nil)
994 var k unsafe.Pointer
995 if key.flag&flagIndir != 0 {
996 k = key.ptr
997 } else {
998 k = unsafe.Pointer(&key.ptr)
1000 e := mapaccess(v.typ, v.pointer(), k)
1001 if e == nil {
1002 return Value{}
1004 typ := tt.elem
1005 fl := (v.flag | key.flag).ro()
1006 fl |= flag(typ.Kind())
1007 return copyVal(typ, fl, e)
1010 // MapKeys returns a slice containing all the keys present in the map,
1011 // in unspecified order.
1012 // It panics if v's Kind is not Map.
1013 // It returns an empty slice if v represents a nil map.
1014 func (v Value) MapKeys() []Value {
1015 v.mustBe(Map)
1016 tt := (*mapType)(unsafe.Pointer(v.typ))
1017 keyType := tt.key
1019 fl := v.flag.ro() | flag(keyType.Kind())
1021 m := v.pointer()
1022 mlen := int(0)
1023 if m != nil {
1024 mlen = maplen(m)
1026 it := mapiterinit(v.typ, m)
1027 a := make([]Value, mlen)
1028 var i int
1029 for i = 0; i < len(a); i++ {
1030 key := mapiterkey(it)
1031 if key == nil {
1032 // Someone deleted an entry from the map since we
1033 // called maplen above. It's a data race, but nothing
1034 // we can do about it.
1035 break
1037 a[i] = copyVal(keyType, fl, key)
1038 mapiternext(it)
1040 return a[:i]
1043 // A MapIter is an iterator for ranging over a map.
1044 // See Value.MapRange.
1045 type MapIter struct {
1046 m Value
1047 it unsafe.Pointer
1050 // Key returns the key of the iterator's current map entry.
1051 func (it *MapIter) Key() Value {
1052 if it.it == nil {
1053 panic("MapIter.Key called before Next")
1055 if mapiterkey(it.it) == nil {
1056 panic("MapIter.Key called on exhausted iterator")
1059 t := (*mapType)(unsafe.Pointer(it.m.typ))
1060 ktype := t.key
1061 return copyVal(ktype, it.m.flag.ro()|flag(ktype.Kind()), mapiterkey(it.it))
1064 // Value returns the value of the iterator's current map entry.
1065 func (it *MapIter) Value() Value {
1066 if it.it == nil {
1067 panic("MapIter.Value called before Next")
1069 if mapiterkey(it.it) == nil {
1070 panic("MapIter.Value called on exhausted iterator")
1073 t := (*mapType)(unsafe.Pointer(it.m.typ))
1074 vtype := t.elem
1075 return copyVal(vtype, it.m.flag.ro()|flag(vtype.Kind()), mapiterelem(it.it))
1078 // Next advances the map iterator and reports whether there is another
1079 // entry. It returns false when the iterator is exhausted; subsequent
1080 // calls to Key, Value, or Next will panic.
1081 func (it *MapIter) Next() bool {
1082 if it.it == nil {
1083 it.it = mapiterinit(it.m.typ, it.m.pointer())
1084 } else {
1085 if mapiterkey(it.it) == nil {
1086 panic("MapIter.Next called on exhausted iterator")
1088 mapiternext(it.it)
1090 return mapiterkey(it.it) != nil
1093 // MapRange returns a range iterator for a map.
1094 // It panics if v's Kind is not Map.
1096 // Call Next to advance the iterator, and Key/Value to access each entry.
1097 // Next returns false when the iterator is exhausted.
1098 // MapRange follows the same iteration semantics as a range statement.
1100 // Example:
1102 // iter := reflect.ValueOf(m).MapRange()
1103 // for iter.Next() {
1104 // k := iter.Key()
1105 // v := iter.Value()
1106 // ...
1107 // }
1109 func (v Value) MapRange() *MapIter {
1110 v.mustBe(Map)
1111 return &MapIter{m: v}
1114 // copyVal returns a Value containing the map key or value at ptr,
1115 // allocating a new variable as needed.
1116 func copyVal(typ *rtype, fl flag, ptr unsafe.Pointer) Value {
1117 if ifaceIndir(typ) {
1118 // Copy result so future changes to the map
1119 // won't change the underlying value.
1120 c := unsafe_New(typ)
1121 typedmemmove(typ, c, ptr)
1122 return Value{typ, c, fl | flagIndir}
1124 return Value{typ, *(*unsafe.Pointer)(ptr), fl}
1127 // Method returns a function value corresponding to v's i'th method.
1128 // The arguments to a Call on the returned function should not include
1129 // a receiver; the returned function will always use v as the receiver.
1130 // Method panics if i is out of range or if v is a nil interface value.
1131 func (v Value) Method(i int) Value {
1132 if v.typ == nil {
1133 panic(&ValueError{"reflect.Value.Method", Invalid})
1135 if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) {
1136 panic("reflect: Method index out of range")
1138 if v.typ.Kind() == Interface && v.IsNil() {
1139 panic("reflect: Method on nil interface value")
1141 fl := v.flag.ro() | (v.flag & flagIndir)
1142 fl |= flag(Func)
1143 fl |= flag(i)<<flagMethodShift | flagMethod
1144 return Value{v.typ, v.ptr, fl}
1147 // NumMethod returns the number of exported methods in the value's method set.
1148 func (v Value) NumMethod() int {
1149 if v.typ == nil {
1150 panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1152 if v.flag&flagMethod != 0 {
1153 return 0
1155 return v.typ.NumMethod()
1158 // MethodByName returns a function value corresponding to the method
1159 // of v with the given name.
1160 // The arguments to a Call on the returned function should not include
1161 // a receiver; the returned function will always use v as the receiver.
1162 // It returns the zero Value if no method was found.
1163 func (v Value) MethodByName(name string) Value {
1164 if v.typ == nil {
1165 panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1167 if v.flag&flagMethod != 0 {
1168 return Value{}
1170 m, ok := v.typ.MethodByName(name)
1171 if !ok {
1172 return Value{}
1174 return v.Method(m.Index)
1177 // NumField returns the number of fields in the struct v.
1178 // It panics if v's Kind is not Struct.
1179 func (v Value) NumField() int {
1180 v.mustBe(Struct)
1181 tt := (*structType)(unsafe.Pointer(v.typ))
1182 return len(tt.fields)
1185 // OverflowComplex reports whether the complex128 x cannot be represented by v's type.
1186 // It panics if v's Kind is not Complex64 or Complex128.
1187 func (v Value) OverflowComplex(x complex128) bool {
1188 k := v.kind()
1189 switch k {
1190 case Complex64:
1191 return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1192 case Complex128:
1193 return false
1195 panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
1198 // OverflowFloat reports whether the float64 x cannot be represented by v's type.
1199 // It panics if v's Kind is not Float32 or Float64.
1200 func (v Value) OverflowFloat(x float64) bool {
1201 k := v.kind()
1202 switch k {
1203 case Float32:
1204 return overflowFloat32(x)
1205 case Float64:
1206 return false
1208 panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
1211 func overflowFloat32(x float64) bool {
1212 if x < 0 {
1213 x = -x
1215 return math.MaxFloat32 < x && x <= math.MaxFloat64
1218 // OverflowInt reports whether the int64 x cannot be represented by v's type.
1219 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
1220 func (v Value) OverflowInt(x int64) bool {
1221 k := v.kind()
1222 switch k {
1223 case Int, Int8, Int16, Int32, Int64:
1224 bitSize := v.typ.size * 8
1225 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1226 return x != trunc
1228 panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
1231 // OverflowUint reports whether the uint64 x cannot be represented by v's type.
1232 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1233 func (v Value) OverflowUint(x uint64) bool {
1234 k := v.kind()
1235 switch k {
1236 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1237 bitSize := v.typ.size * 8
1238 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1239 return x != trunc
1241 panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
1244 //go:nocheckptr
1245 // This prevents inlining Value.Pointer when -d=checkptr is enabled,
1246 // which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer())
1247 // and make an exception.
1249 // Pointer returns v's value as a uintptr.
1250 // It returns uintptr instead of unsafe.Pointer so that
1251 // code using reflect cannot obtain unsafe.Pointers
1252 // without importing the unsafe package explicitly.
1253 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1255 // If v's Kind is Func, the returned pointer is an underlying
1256 // code pointer, but not necessarily enough to identify a
1257 // single function uniquely. The only guarantee is that the
1258 // result is zero if and only if v is a nil func Value.
1260 // If v's Kind is Slice, the returned pointer is to the first
1261 // element of the slice. If the slice is nil the returned value
1262 // is 0. If the slice is empty but non-nil the return value is non-zero.
1263 func (v Value) Pointer() uintptr {
1264 // TODO: deprecate
1265 k := v.kind()
1266 switch k {
1267 case Ptr:
1268 if v.typ.ptrdata == 0 {
1269 // Handle pointers to go:notinheap types directly,
1270 // so we never materialize such pointers as an
1271 // unsafe.Pointer. (Such pointers are always indirect.)
1272 // See issue 42076.
1273 return *(*uintptr)(v.ptr)
1275 fallthrough
1276 case Chan, Map, UnsafePointer:
1277 return uintptr(v.pointer())
1278 case Func:
1279 p := v.pointer()
1280 // Non-nil func value points at data block.
1281 // First word of data block is actual code.
1282 if p != nil {
1283 p = *(*unsafe.Pointer)(p)
1285 return uintptr(p)
1287 case Slice:
1288 return (*SliceHeader)(v.ptr).Data
1290 panic(&ValueError{"reflect.Value.Pointer", v.kind()})
1293 // Recv receives and returns a value from the channel v.
1294 // It panics if v's Kind is not Chan.
1295 // The receive blocks until a value is ready.
1296 // The boolean value ok is true if the value x corresponds to a send
1297 // on the channel, false if it is a zero value received because the channel is closed.
1298 func (v Value) Recv() (x Value, ok bool) {
1299 v.mustBe(Chan)
1300 v.mustBeExported()
1301 return v.recv(false)
1304 // internal recv, possibly non-blocking (nb).
1305 // v is known to be a channel.
1306 func (v Value) recv(nb bool) (val Value, ok bool) {
1307 tt := (*chanType)(unsafe.Pointer(v.typ))
1308 if ChanDir(tt.dir)&RecvDir == 0 {
1309 panic("reflect: recv on send-only channel")
1311 t := tt.elem
1312 val = Value{t, nil, flag(t.Kind())}
1313 var p unsafe.Pointer
1314 if ifaceIndir(t) {
1315 p = unsafe_New(t)
1316 val.ptr = p
1317 val.flag |= flagIndir
1318 } else {
1319 p = unsafe.Pointer(&val.ptr)
1321 selected, ok := chanrecv(v.pointer(), nb, p)
1322 if !selected {
1323 val = Value{}
1325 return
1328 // Send sends x on the channel v.
1329 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1330 // As in Go, x's value must be assignable to the channel's element type.
1331 func (v Value) Send(x Value) {
1332 v.mustBe(Chan)
1333 v.mustBeExported()
1334 v.send(x, false)
1337 // internal send, possibly non-blocking.
1338 // v is known to be a channel.
1339 func (v Value) send(x Value, nb bool) (selected bool) {
1340 tt := (*chanType)(unsafe.Pointer(v.typ))
1341 if ChanDir(tt.dir)&SendDir == 0 {
1342 panic("reflect: send on recv-only channel")
1344 x.mustBeExported()
1345 x = x.assignTo("reflect.Value.Send", tt.elem, nil)
1346 var p unsafe.Pointer
1347 if x.flag&flagIndir != 0 {
1348 p = x.ptr
1349 } else {
1350 p = unsafe.Pointer(&x.ptr)
1352 return chansend(v.pointer(), p, nb)
1355 // Set assigns x to the value v.
1356 // It panics if CanSet returns false.
1357 // As in Go, x's value must be assignable to v's type.
1358 func (v Value) Set(x Value) {
1359 v.mustBeAssignable()
1360 x.mustBeExported() // do not let unexported x leak
1361 var target unsafe.Pointer
1362 if v.kind() == Interface {
1363 target = v.ptr
1365 x = x.assignTo("reflect.Set", v.typ, target)
1366 if x.flag&flagIndir != 0 {
1367 if x.ptr == unsafe.Pointer(&zeroVal[0]) {
1368 typedmemclr(v.typ, v.ptr)
1369 } else {
1370 typedmemmove(v.typ, v.ptr, x.ptr)
1372 } else {
1373 *(*unsafe.Pointer)(v.ptr) = x.ptr
1377 // SetBool sets v's underlying value.
1378 // It panics if v's Kind is not Bool or if CanSet() is false.
1379 func (v Value) SetBool(x bool) {
1380 v.mustBeAssignable()
1381 v.mustBe(Bool)
1382 *(*bool)(v.ptr) = x
1385 // SetBytes sets v's underlying value.
1386 // It panics if v's underlying value is not a slice of bytes.
1387 func (v Value) SetBytes(x []byte) {
1388 v.mustBeAssignable()
1389 v.mustBe(Slice)
1390 if v.typ.Elem().Kind() != Uint8 {
1391 panic("reflect.Value.SetBytes of non-byte slice")
1393 *(*[]byte)(v.ptr) = x
1396 // setRunes sets v's underlying value.
1397 // It panics if v's underlying value is not a slice of runes (int32s).
1398 func (v Value) setRunes(x []rune) {
1399 v.mustBeAssignable()
1400 v.mustBe(Slice)
1401 if v.typ.Elem().Kind() != Int32 {
1402 panic("reflect.Value.setRunes of non-rune slice")
1404 *(*[]rune)(v.ptr) = x
1407 // SetComplex sets v's underlying value to x.
1408 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1409 func (v Value) SetComplex(x complex128) {
1410 v.mustBeAssignable()
1411 switch k := v.kind(); k {
1412 default:
1413 panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
1414 case Complex64:
1415 *(*complex64)(v.ptr) = complex64(x)
1416 case Complex128:
1417 *(*complex128)(v.ptr) = x
1421 // SetFloat sets v's underlying value to x.
1422 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1423 func (v Value) SetFloat(x float64) {
1424 v.mustBeAssignable()
1425 switch k := v.kind(); k {
1426 default:
1427 panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
1428 case Float32:
1429 *(*float32)(v.ptr) = float32(x)
1430 case Float64:
1431 *(*float64)(v.ptr) = x
1435 // SetInt sets v's underlying value to x.
1436 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1437 func (v Value) SetInt(x int64) {
1438 v.mustBeAssignable()
1439 switch k := v.kind(); k {
1440 default:
1441 panic(&ValueError{"reflect.Value.SetInt", v.kind()})
1442 case Int:
1443 *(*int)(v.ptr) = int(x)
1444 case Int8:
1445 *(*int8)(v.ptr) = int8(x)
1446 case Int16:
1447 *(*int16)(v.ptr) = int16(x)
1448 case Int32:
1449 *(*int32)(v.ptr) = int32(x)
1450 case Int64:
1451 *(*int64)(v.ptr) = x
1455 // SetLen sets v's length to n.
1456 // It panics if v's Kind is not Slice or if n is negative or
1457 // greater than the capacity of the slice.
1458 func (v Value) SetLen(n int) {
1459 v.mustBeAssignable()
1460 v.mustBe(Slice)
1461 s := (*unsafeheader.Slice)(v.ptr)
1462 if uint(n) > uint(s.Cap) {
1463 panic("reflect: slice length out of range in SetLen")
1465 s.Len = n
1468 // SetCap sets v's capacity to n.
1469 // It panics if v's Kind is not Slice or if n is smaller than the length or
1470 // greater than the capacity of the slice.
1471 func (v Value) SetCap(n int) {
1472 v.mustBeAssignable()
1473 v.mustBe(Slice)
1474 s := (*unsafeheader.Slice)(v.ptr)
1475 if n < s.Len || n > s.Cap {
1476 panic("reflect: slice capacity out of range in SetCap")
1478 s.Cap = n
1481 // SetMapIndex sets the element associated with key in the map v to elem.
1482 // It panics if v's Kind is not Map.
1483 // If elem is the zero Value, SetMapIndex deletes the key from the map.
1484 // Otherwise if v holds a nil map, SetMapIndex will panic.
1485 // As in Go, key's elem must be assignable to the map's key type,
1486 // and elem's value must be assignable to the map's elem type.
1487 func (v Value) SetMapIndex(key, elem Value) {
1488 v.mustBe(Map)
1489 v.mustBeExported()
1490 key.mustBeExported()
1491 tt := (*mapType)(unsafe.Pointer(v.typ))
1492 key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
1493 var k unsafe.Pointer
1494 if key.flag&flagIndir != 0 {
1495 k = key.ptr
1496 } else {
1497 k = unsafe.Pointer(&key.ptr)
1499 if elem.typ == nil {
1500 mapdelete(v.typ, v.pointer(), k)
1501 return
1503 elem.mustBeExported()
1504 elem = elem.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
1505 var e unsafe.Pointer
1506 if elem.flag&flagIndir != 0 {
1507 e = elem.ptr
1508 } else {
1509 e = unsafe.Pointer(&elem.ptr)
1511 mapassign(v.typ, v.pointer(), k, e)
1514 // SetUint sets v's underlying value to x.
1515 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1516 func (v Value) SetUint(x uint64) {
1517 v.mustBeAssignable()
1518 switch k := v.kind(); k {
1519 default:
1520 panic(&ValueError{"reflect.Value.SetUint", v.kind()})
1521 case Uint:
1522 *(*uint)(v.ptr) = uint(x)
1523 case Uint8:
1524 *(*uint8)(v.ptr) = uint8(x)
1525 case Uint16:
1526 *(*uint16)(v.ptr) = uint16(x)
1527 case Uint32:
1528 *(*uint32)(v.ptr) = uint32(x)
1529 case Uint64:
1530 *(*uint64)(v.ptr) = x
1531 case Uintptr:
1532 *(*uintptr)(v.ptr) = uintptr(x)
1536 // SetPointer sets the unsafe.Pointer value v to x.
1537 // It panics if v's Kind is not UnsafePointer.
1538 func (v Value) SetPointer(x unsafe.Pointer) {
1539 v.mustBeAssignable()
1540 v.mustBe(UnsafePointer)
1541 *(*unsafe.Pointer)(v.ptr) = x
1544 // SetString sets v's underlying value to x.
1545 // It panics if v's Kind is not String or if CanSet() is false.
1546 func (v Value) SetString(x string) {
1547 v.mustBeAssignable()
1548 v.mustBe(String)
1549 *(*string)(v.ptr) = x
1552 // Slice returns v[i:j].
1553 // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
1554 // or if the indexes are out of bounds.
1555 func (v Value) Slice(i, j int) Value {
1556 var (
1557 cap int
1558 typ *sliceType
1559 base unsafe.Pointer
1561 switch kind := v.kind(); kind {
1562 default:
1563 panic(&ValueError{"reflect.Value.Slice", v.kind()})
1565 case Array:
1566 if v.flag&flagAddr == 0 {
1567 panic("reflect.Value.Slice: slice of unaddressable array")
1569 tt := (*arrayType)(unsafe.Pointer(v.typ))
1570 cap = int(tt.len)
1571 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1572 base = v.ptr
1574 case Slice:
1575 typ = (*sliceType)(unsafe.Pointer(v.typ))
1576 s := (*unsafeheader.Slice)(v.ptr)
1577 base = s.Data
1578 cap = s.Cap
1580 case String:
1581 s := (*unsafeheader.String)(v.ptr)
1582 if i < 0 || j < i || j > s.Len {
1583 panic("reflect.Value.Slice: string slice index out of bounds")
1585 var t unsafeheader.String
1586 if i < s.Len {
1587 t = unsafeheader.String{Data: arrayAt(s.Data, i, 1, "i < s.Len"), Len: j - i}
1589 return Value{v.typ, unsafe.Pointer(&t), v.flag}
1592 if i < 0 || j < i || j > cap {
1593 panic("reflect.Value.Slice: slice index out of bounds")
1596 // Declare slice so that gc can see the base pointer in it.
1597 var x []unsafe.Pointer
1599 // Reinterpret as *unsafeheader.Slice to edit.
1600 s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
1601 s.Len = j - i
1602 s.Cap = cap - i
1603 if cap-i > 0 {
1604 s.Data = arrayAt(base, i, typ.elem.Size(), "i < cap")
1605 } else {
1606 // do not advance pointer, to avoid pointing beyond end of slice
1607 s.Data = base
1610 fl := v.flag.ro() | flagIndir | flag(Slice)
1611 return Value{typ.common(), unsafe.Pointer(&x), fl}
1614 // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
1615 // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
1616 // or if the indexes are out of bounds.
1617 func (v Value) Slice3(i, j, k int) Value {
1618 var (
1619 cap int
1620 typ *sliceType
1621 base unsafe.Pointer
1623 switch kind := v.kind(); kind {
1624 default:
1625 panic(&ValueError{"reflect.Value.Slice3", v.kind()})
1627 case Array:
1628 if v.flag&flagAddr == 0 {
1629 panic("reflect.Value.Slice3: slice of unaddressable array")
1631 tt := (*arrayType)(unsafe.Pointer(v.typ))
1632 cap = int(tt.len)
1633 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1634 base = v.ptr
1636 case Slice:
1637 typ = (*sliceType)(unsafe.Pointer(v.typ))
1638 s := (*unsafeheader.Slice)(v.ptr)
1639 base = s.Data
1640 cap = s.Cap
1643 if i < 0 || j < i || k < j || k > cap {
1644 panic("reflect.Value.Slice3: slice index out of bounds")
1647 // Declare slice so that the garbage collector
1648 // can see the base pointer in it.
1649 var x []unsafe.Pointer
1651 // Reinterpret as *unsafeheader.Slice to edit.
1652 s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
1653 s.Len = j - i
1654 s.Cap = k - i
1655 if k-i > 0 {
1656 s.Data = arrayAt(base, i, typ.elem.Size(), "i < k <= cap")
1657 } else {
1658 // do not advance pointer, to avoid pointing beyond end of slice
1659 s.Data = base
1662 fl := v.flag.ro() | flagIndir | flag(Slice)
1663 return Value{typ.common(), unsafe.Pointer(&x), fl}
1666 // String returns the string v's underlying value, as a string.
1667 // String is a special case because of Go's String method convention.
1668 // Unlike the other getters, it does not panic if v's Kind is not String.
1669 // Instead, it returns a string of the form "<T value>" where T is v's type.
1670 // The fmt package treats Values specially. It does not call their String
1671 // method implicitly but instead prints the concrete values they hold.
1672 func (v Value) String() string {
1673 switch k := v.kind(); k {
1674 case Invalid:
1675 return "<invalid Value>"
1676 case String:
1677 return *(*string)(v.ptr)
1679 // If you call String on a reflect.Value of other type, it's better to
1680 // print something than to panic. Useful in debugging.
1681 return "<" + v.Type().String() + " Value>"
1684 // TryRecv attempts to receive a value from the channel v but will not block.
1685 // It panics if v's Kind is not Chan.
1686 // If the receive delivers a value, x is the transferred value and ok is true.
1687 // If the receive cannot finish without blocking, x is the zero Value and ok is false.
1688 // If the channel is closed, x is the zero value for the channel's element type and ok is false.
1689 func (v Value) TryRecv() (x Value, ok bool) {
1690 v.mustBe(Chan)
1691 v.mustBeExported()
1692 return v.recv(true)
1695 // TrySend attempts to send x on the channel v but will not block.
1696 // It panics if v's Kind is not Chan.
1697 // It reports whether the value was sent.
1698 // As in Go, x's value must be assignable to the channel's element type.
1699 func (v Value) TrySend(x Value) bool {
1700 v.mustBe(Chan)
1701 v.mustBeExported()
1702 return v.send(x, true)
1705 // Type returns v's type.
1706 func (v Value) Type() Type {
1707 f := v.flag
1708 if f == 0 {
1709 panic(&ValueError{"reflect.Value.Type", Invalid})
1711 if f&flagMethod == 0 {
1712 // Easy case
1713 return toType(v.typ)
1716 // Method value.
1717 // v.typ describes the receiver, not the method type.
1718 i := int(v.flag) >> flagMethodShift
1719 if v.typ.Kind() == Interface {
1720 // Method on interface.
1721 tt := (*interfaceType)(unsafe.Pointer(v.typ))
1722 if uint(i) >= uint(len(tt.methods)) {
1723 panic("reflect: internal error: invalid method index")
1725 m := &tt.methods[i]
1726 return toType(m.typ)
1728 // Method on concrete type.
1729 ms := v.typ.exportedMethods()
1730 if uint(i) >= uint(len(ms)) {
1731 panic("reflect: internal error: invalid method index")
1733 m := ms[i]
1734 return toType(m.mtyp)
1737 // Uint returns v's underlying value, as a uint64.
1738 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1739 func (v Value) Uint() uint64 {
1740 k := v.kind()
1741 p := v.ptr
1742 switch k {
1743 case Uint:
1744 return uint64(*(*uint)(p))
1745 case Uint8:
1746 return uint64(*(*uint8)(p))
1747 case Uint16:
1748 return uint64(*(*uint16)(p))
1749 case Uint32:
1750 return uint64(*(*uint32)(p))
1751 case Uint64:
1752 return *(*uint64)(p)
1753 case Uintptr:
1754 return uint64(*(*uintptr)(p))
1756 panic(&ValueError{"reflect.Value.Uint", v.kind()})
1759 //go:nocheckptr
1760 // This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled,
1761 // which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr())
1762 // and make an exception.
1764 // UnsafeAddr returns a pointer to v's data.
1765 // It is for advanced clients that also import the "unsafe" package.
1766 // It panics if v is not addressable.
1767 func (v Value) UnsafeAddr() uintptr {
1768 // TODO: deprecate
1769 if v.typ == nil {
1770 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
1772 if v.flag&flagAddr == 0 {
1773 panic("reflect.Value.UnsafeAddr of unaddressable value")
1775 return uintptr(v.ptr)
1778 // StringHeader is the runtime representation of a string.
1779 // It cannot be used safely or portably and its representation may
1780 // change in a later release.
1781 // Moreover, the Data field is not sufficient to guarantee the data
1782 // it references will not be garbage collected, so programs must keep
1783 // a separate, correctly typed pointer to the underlying data.
1784 type StringHeader struct {
1785 Data uintptr
1786 Len int
1789 // SliceHeader is the runtime representation of a slice.
1790 // It cannot be used safely or portably and its representation may
1791 // change in a later release.
1792 // Moreover, the Data field is not sufficient to guarantee the data
1793 // it references will not be garbage collected, so programs must keep
1794 // a separate, correctly typed pointer to the underlying data.
1795 type SliceHeader struct {
1796 Data uintptr
1797 Len int
1798 Cap int
1801 func typesMustMatch(what string, t1, t2 Type) {
1802 if !typeEqual(t1, t2) {
1803 panic(what + ": " + t1.String() + " != " + t2.String())
1807 // arrayAt returns the i-th element of p,
1808 // an array whose elements are eltSize bytes wide.
1809 // The array pointed at by p must have at least i+1 elements:
1810 // it is invalid (but impossible to check here) to pass i >= len,
1811 // because then the result will point outside the array.
1812 // whySafe must explain why i < len. (Passing "i < len" is fine;
1813 // the benefit is to surface this assumption at the call site.)
1814 func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
1815 return add(p, uintptr(i)*eltSize, "i < len")
1818 // grow grows the slice s so that it can hold extra more values, allocating
1819 // more capacity if needed. It also returns the old and new slice lengths.
1820 func grow(s Value, extra int) (Value, int, int) {
1821 i0 := s.Len()
1822 i1 := i0 + extra
1823 if i1 < i0 {
1824 panic("reflect.Append: slice overflow")
1826 m := s.Cap()
1827 if i1 <= m {
1828 return s.Slice(0, i1), i0, i1
1830 if m == 0 {
1831 m = extra
1832 } else {
1833 for m < i1 {
1834 if i0 < 1024 {
1835 m += m
1836 } else {
1837 m += m / 4
1841 t := MakeSlice(s.Type(), i1, m)
1842 Copy(t, s)
1843 return t, i0, i1
1846 // Append appends the values x to a slice s and returns the resulting slice.
1847 // As in Go, each x's value must be assignable to the slice's element type.
1848 func Append(s Value, x ...Value) Value {
1849 s.mustBe(Slice)
1850 s, i0, i1 := grow(s, len(x))
1851 for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
1852 s.Index(i).Set(x[j])
1854 return s
1857 // AppendSlice appends a slice t to a slice s and returns the resulting slice.
1858 // The slices s and t must have the same element type.
1859 func AppendSlice(s, t Value) Value {
1860 s.mustBe(Slice)
1861 t.mustBe(Slice)
1862 typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
1863 s, i0, i1 := grow(s, t.Len())
1864 Copy(s.Slice(i0, i1), t)
1865 return s
1868 // Copy copies the contents of src into dst until either
1869 // dst has been filled or src has been exhausted.
1870 // It returns the number of elements copied.
1871 // Dst and src each must have kind Slice or Array, and
1872 // dst and src must have the same element type.
1874 // As a special case, src can have kind String if the element type of dst is kind Uint8.
1875 func Copy(dst, src Value) int {
1876 dk := dst.kind()
1877 if dk != Array && dk != Slice {
1878 panic(&ValueError{"reflect.Copy", dk})
1880 if dk == Array {
1881 dst.mustBeAssignable()
1883 dst.mustBeExported()
1885 sk := src.kind()
1886 var stringCopy bool
1887 if sk != Array && sk != Slice {
1888 stringCopy = sk == String && dst.typ.Elem().Kind() == Uint8
1889 if !stringCopy {
1890 panic(&ValueError{"reflect.Copy", sk})
1893 src.mustBeExported()
1895 de := dst.typ.Elem()
1896 if !stringCopy {
1897 se := src.typ.Elem()
1898 typesMustMatch("reflect.Copy", de, se)
1901 var ds, ss unsafeheader.Slice
1902 if dk == Array {
1903 ds.Data = dst.ptr
1904 ds.Len = dst.Len()
1905 ds.Cap = ds.Len
1906 } else {
1907 ds = *(*unsafeheader.Slice)(dst.ptr)
1909 if sk == Array {
1910 ss.Data = src.ptr
1911 ss.Len = src.Len()
1912 ss.Cap = ss.Len
1913 } else if sk == Slice {
1914 ss = *(*unsafeheader.Slice)(src.ptr)
1915 } else {
1916 sh := *(*unsafeheader.String)(src.ptr)
1917 ss.Data = sh.Data
1918 ss.Len = sh.Len
1919 ss.Cap = sh.Len
1922 return typedslicecopy(de.common(), ds, ss)
1925 // A runtimeSelect is a single case passed to rselect.
1926 // This must match ../runtime/select.go:/runtimeSelect
1927 type runtimeSelect struct {
1928 dir SelectDir // SelectSend, SelectRecv or SelectDefault
1929 typ *rtype // channel type
1930 ch unsafe.Pointer // channel
1931 val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
1934 // rselect runs a select. It returns the index of the chosen case.
1935 // If the case was a receive, val is filled in with the received value.
1936 // The conventional OK bool indicates whether the receive corresponds
1937 // to a sent value.
1938 //go:noescape
1939 func rselect([]runtimeSelect) (chosen int, recvOK bool)
1941 // A SelectDir describes the communication direction of a select case.
1942 type SelectDir int
1944 // NOTE: These values must match ../runtime/select.go:/selectDir.
1946 const (
1947 _ SelectDir = iota
1948 SelectSend // case Chan <- Send
1949 SelectRecv // case <-Chan:
1950 SelectDefault // default
1953 // A SelectCase describes a single case in a select operation.
1954 // The kind of case depends on Dir, the communication direction.
1956 // If Dir is SelectDefault, the case represents a default case.
1957 // Chan and Send must be zero Values.
1959 // If Dir is SelectSend, the case represents a send operation.
1960 // Normally Chan's underlying value must be a channel, and Send's underlying value must be
1961 // assignable to the channel's element type. As a special case, if Chan is a zero Value,
1962 // then the case is ignored, and the field Send will also be ignored and may be either zero
1963 // or non-zero.
1965 // If Dir is SelectRecv, the case represents a receive operation.
1966 // Normally Chan's underlying value must be a channel and Send must be a zero Value.
1967 // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
1968 // When a receive operation is selected, the received Value is returned by Select.
1970 type SelectCase struct {
1971 Dir SelectDir // direction of case
1972 Chan Value // channel to use (for send or receive)
1973 Send Value // value to send (for send)
1976 // Select executes a select operation described by the list of cases.
1977 // Like the Go select statement, it blocks until at least one of the cases
1978 // can proceed, makes a uniform pseudo-random choice,
1979 // and then executes that case. It returns the index of the chosen case
1980 // and, if that case was a receive operation, the value received and a
1981 // boolean indicating whether the value corresponds to a send on the channel
1982 // (as opposed to a zero value received because the channel is closed).
1983 // Select supports a maximum of 65536 cases.
1984 func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
1985 if len(cases) > 65536 {
1986 panic("reflect.Select: too many cases (max 65536)")
1988 // NOTE: Do not trust that caller is not modifying cases data underfoot.
1989 // The range is safe because the caller cannot modify our copy of the len
1990 // and each iteration makes its own copy of the value c.
1991 var runcases []runtimeSelect
1992 if len(cases) > 4 {
1993 // Slice is heap allocated due to runtime dependent capacity.
1994 runcases = make([]runtimeSelect, len(cases))
1995 } else {
1996 // Slice can be stack allocated due to constant capacity.
1997 runcases = make([]runtimeSelect, len(cases), 4)
2000 haveDefault := false
2001 for i, c := range cases {
2002 rc := &runcases[i]
2003 rc.dir = c.Dir
2004 switch c.Dir {
2005 default:
2006 panic("reflect.Select: invalid Dir")
2008 case SelectDefault: // default
2009 if haveDefault {
2010 panic("reflect.Select: multiple default cases")
2012 haveDefault = true
2013 if c.Chan.IsValid() {
2014 panic("reflect.Select: default case has Chan value")
2016 if c.Send.IsValid() {
2017 panic("reflect.Select: default case has Send value")
2020 case SelectSend:
2021 ch := c.Chan
2022 if !ch.IsValid() {
2023 break
2025 ch.mustBe(Chan)
2026 ch.mustBeExported()
2027 tt := (*chanType)(unsafe.Pointer(ch.typ))
2028 if ChanDir(tt.dir)&SendDir == 0 {
2029 panic("reflect.Select: SendDir case using recv-only channel")
2031 rc.ch = ch.pointer()
2032 rc.typ = &tt.rtype
2033 v := c.Send
2034 if !v.IsValid() {
2035 panic("reflect.Select: SendDir case missing Send value")
2037 v.mustBeExported()
2038 v = v.assignTo("reflect.Select", tt.elem, nil)
2039 if v.flag&flagIndir != 0 {
2040 rc.val = v.ptr
2041 } else {
2042 rc.val = unsafe.Pointer(&v.ptr)
2045 case SelectRecv:
2046 if c.Send.IsValid() {
2047 panic("reflect.Select: RecvDir case has Send value")
2049 ch := c.Chan
2050 if !ch.IsValid() {
2051 break
2053 ch.mustBe(Chan)
2054 ch.mustBeExported()
2055 tt := (*chanType)(unsafe.Pointer(ch.typ))
2056 if ChanDir(tt.dir)&RecvDir == 0 {
2057 panic("reflect.Select: RecvDir case using send-only channel")
2059 rc.ch = ch.pointer()
2060 rc.typ = &tt.rtype
2061 rc.val = unsafe_New(tt.elem)
2065 chosen, recvOK = rselect(runcases)
2066 if runcases[chosen].dir == SelectRecv {
2067 tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
2068 t := tt.elem
2069 p := runcases[chosen].val
2070 fl := flag(t.Kind())
2071 if ifaceIndir(t) {
2072 recv = Value{t, p, fl | flagIndir}
2073 } else {
2074 recv = Value{t, *(*unsafe.Pointer)(p), fl}
2077 return chosen, recv, recvOK
2081 * constructors
2084 // implemented in package runtime
2085 func unsafe_New(*rtype) unsafe.Pointer
2086 func unsafe_NewArray(*rtype, int) unsafe.Pointer
2088 // MakeSlice creates a new zero-initialized slice value
2089 // for the specified slice type, length, and capacity.
2090 func MakeSlice(typ Type, len, cap int) Value {
2091 if typ.Kind() != Slice {
2092 panic("reflect.MakeSlice of non-slice type")
2094 if len < 0 {
2095 panic("reflect.MakeSlice: negative len")
2097 if cap < 0 {
2098 panic("reflect.MakeSlice: negative cap")
2100 if len > cap {
2101 panic("reflect.MakeSlice: len > cap")
2104 s := unsafeheader.Slice{Data: unsafe_NewArray(typ.Elem().(*rtype), cap), Len: len, Cap: cap}
2105 return Value{typ.(*rtype), unsafe.Pointer(&s), flagIndir | flag(Slice)}
2108 // MakeChan creates a new channel with the specified type and buffer size.
2109 func MakeChan(typ Type, buffer int) Value {
2110 if typ.Kind() != Chan {
2111 panic("reflect.MakeChan of non-chan type")
2113 if buffer < 0 {
2114 panic("reflect.MakeChan: negative buffer size")
2116 if typ.ChanDir() != BothDir {
2117 panic("reflect.MakeChan: unidirectional channel type")
2119 t := typ.(*rtype)
2120 ch := makechan(t, buffer)
2121 return Value{t, unsafe.Pointer(&ch), flag(Chan) | flagIndir}
2124 // MakeMap creates a new map with the specified type.
2125 func MakeMap(typ Type) Value {
2126 return MakeMapWithSize(typ, 0)
2129 // MakeMapWithSize creates a new map with the specified type
2130 // and initial space for approximately n elements.
2131 func MakeMapWithSize(typ Type, n int) Value {
2132 if typ.Kind() != Map {
2133 panic("reflect.MakeMapWithSize of non-map type")
2135 t := typ.(*rtype)
2136 m := makemap(t, n)
2137 return Value{t, unsafe.Pointer(&m), flag(Map) | flagIndir}
2140 // Indirect returns the value that v points to.
2141 // If v is a nil pointer, Indirect returns a zero Value.
2142 // If v is not a pointer, Indirect returns v.
2143 func Indirect(v Value) Value {
2144 if v.Kind() != Ptr {
2145 return v
2147 return v.Elem()
2150 // ValueOf returns a new Value initialized to the concrete value
2151 // stored in the interface i. ValueOf(nil) returns the zero Value.
2152 func ValueOf(i interface{}) Value {
2153 if i == nil {
2154 return Value{}
2157 // TODO: Maybe allow contents of a Value to live on the stack.
2158 // For now we make the contents always escape to the heap. It
2159 // makes life easier in a few places (see chanrecv/mapassign
2160 // comment below).
2161 escapes(i)
2163 return unpackEface(i)
2166 // Zero returns a Value representing the zero value for the specified type.
2167 // The result is different from the zero value of the Value struct,
2168 // which represents no value at all.
2169 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
2170 // The returned value is neither addressable nor settable.
2171 func Zero(typ Type) Value {
2172 if typ == nil {
2173 panic("reflect: Zero(nil)")
2175 t := typ.(*rtype)
2176 fl := flag(t.Kind())
2177 if ifaceIndir(t) {
2178 var p unsafe.Pointer
2179 if t.size <= maxZero {
2180 p = unsafe.Pointer(&zeroVal[0])
2181 } else {
2182 p = unsafe_New(t)
2184 return Value{t, p, fl | flagIndir}
2186 return Value{t, nil, fl}
2189 // must match declarations in runtime/map.go.
2190 const maxZero = 1024
2192 // Using linkname here doesn't work for gofrontend.
2193 // //go:linkname zeroVal runtime.zeroVal
2194 var zeroVal [maxZero]byte
2196 // New returns a Value representing a pointer to a new zero value
2197 // for the specified type. That is, the returned Value's Type is PtrTo(typ).
2198 func New(typ Type) Value {
2199 if typ == nil {
2200 panic("reflect: New(nil)")
2202 t := typ.(*rtype)
2203 ptr := unsafe_New(t)
2204 fl := flag(Ptr)
2205 return Value{t.ptrTo(), ptr, fl}
2208 // NewAt returns a Value representing a pointer to a value of the
2209 // specified type, using p as that pointer.
2210 func NewAt(typ Type, p unsafe.Pointer) Value {
2211 fl := flag(Ptr)
2212 t := typ.(*rtype)
2213 return Value{t.ptrTo(), p, fl}
2216 // assignTo returns a value v that can be assigned directly to typ.
2217 // It panics if v is not assignable to typ.
2218 // For a conversion to an interface type, target is a suggested scratch space to use.
2219 // target must be initialized memory (or nil).
2220 func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value {
2221 if v.flag&flagMethod != 0 {
2222 v = makeMethodValue(context, v)
2225 switch {
2226 case directlyAssignable(dst, v.typ):
2227 // Overwrite type so that they match.
2228 // Same memory layout, so no harm done.
2229 fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
2230 fl |= flag(dst.Kind())
2231 return Value{dst, v.ptr, fl}
2233 case implements(dst, v.typ):
2234 if target == nil {
2235 target = unsafe_New(dst)
2237 if v.Kind() == Interface && v.IsNil() {
2238 // A nil ReadWriter passed to nil Reader is OK,
2239 // but using ifaceE2I below will panic.
2240 // Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
2241 return Value{dst, nil, flag(Interface)}
2243 x := valueInterface(v, false)
2244 if dst.NumMethod() == 0 {
2245 *(*interface{})(target) = x
2246 } else {
2247 ifaceE2I(dst, x, target)
2249 return Value{dst, target, flagIndir | flag(Interface)}
2252 // Failed.
2253 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
2256 // Convert returns the value v converted to type t.
2257 // If the usual Go conversion rules do not allow conversion
2258 // of the value v to type t, Convert panics.
2259 func (v Value) Convert(t Type) Value {
2260 if v.flag&flagMethod != 0 {
2261 v = makeMethodValue("Convert", v)
2263 op := convertOp(t.common(), v.typ)
2264 if op == nil {
2265 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
2267 return op(v, t)
2270 // convertOp returns the function to convert a value of type src
2271 // to a value of type dst. If the conversion is illegal, convertOp returns nil.
2272 func convertOp(dst, src *rtype) func(Value, Type) Value {
2273 switch src.Kind() {
2274 case Int, Int8, Int16, Int32, Int64:
2275 switch dst.Kind() {
2276 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2277 return cvtInt
2278 case Float32, Float64:
2279 return cvtIntFloat
2280 case String:
2281 return cvtIntString
2284 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2285 switch dst.Kind() {
2286 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2287 return cvtUint
2288 case Float32, Float64:
2289 return cvtUintFloat
2290 case String:
2291 return cvtUintString
2294 case Float32, Float64:
2295 switch dst.Kind() {
2296 case Int, Int8, Int16, Int32, Int64:
2297 return cvtFloatInt
2298 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2299 return cvtFloatUint
2300 case Float32, Float64:
2301 return cvtFloat
2304 case Complex64, Complex128:
2305 switch dst.Kind() {
2306 case Complex64, Complex128:
2307 return cvtComplex
2310 case String:
2311 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
2312 switch dst.Elem().Kind() {
2313 case Uint8:
2314 return cvtStringBytes
2315 case Int32:
2316 return cvtStringRunes
2320 case Slice:
2321 if dst.Kind() == String && src.Elem().PkgPath() == "" {
2322 switch src.Elem().Kind() {
2323 case Uint8:
2324 return cvtBytesString
2325 case Int32:
2326 return cvtRunesString
2330 case Chan:
2331 if dst.Kind() == Chan && specialChannelAssignability(dst, src) {
2332 return cvtDirect
2336 // dst and src have same underlying type.
2337 if haveIdenticalUnderlyingType(dst, src, false) {
2338 return cvtDirect
2341 // dst and src are non-defined pointer types with same underlying base type.
2342 if dst.Kind() == Ptr && dst.Name() == "" &&
2343 src.Kind() == Ptr && src.Name() == "" &&
2344 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false) {
2345 return cvtDirect
2348 if implements(dst, src) {
2349 if src.Kind() == Interface {
2350 return cvtI2I
2352 return cvtT2I
2355 return nil
2358 // makeInt returns a Value of type t equal to bits (possibly truncated),
2359 // where t is a signed or unsigned int type.
2360 func makeInt(f flag, bits uint64, t Type) Value {
2361 typ := t.common()
2362 ptr := unsafe_New(typ)
2363 switch typ.size {
2364 case 1:
2365 *(*uint8)(ptr) = uint8(bits)
2366 case 2:
2367 *(*uint16)(ptr) = uint16(bits)
2368 case 4:
2369 *(*uint32)(ptr) = uint32(bits)
2370 case 8:
2371 *(*uint64)(ptr) = bits
2373 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2376 // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2377 // where t is a float32 or float64 type.
2378 func makeFloat(f flag, v float64, t Type) Value {
2379 typ := t.common()
2380 ptr := unsafe_New(typ)
2381 switch typ.size {
2382 case 4:
2383 *(*float32)(ptr) = float32(v)
2384 case 8:
2385 *(*float64)(ptr) = v
2387 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2390 // makeFloat returns a Value of type t equal to v, where t is a float32 type.
2391 func makeFloat32(f flag, v float32, t Type) Value {
2392 typ := t.common()
2393 ptr := unsafe_New(typ)
2394 *(*float32)(ptr) = v
2395 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2398 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2399 // where t is a complex64 or complex128 type.
2400 func makeComplex(f flag, v complex128, t Type) Value {
2401 typ := t.common()
2402 ptr := unsafe_New(typ)
2403 switch typ.size {
2404 case 8:
2405 *(*complex64)(ptr) = complex64(v)
2406 case 16:
2407 *(*complex128)(ptr) = v
2409 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2412 func makeString(f flag, v string, t Type) Value {
2413 ret := New(t).Elem()
2414 ret.SetString(v)
2415 ret.flag = ret.flag&^flagAddr | f
2416 return ret
2419 func makeBytes(f flag, v []byte, t Type) Value {
2420 ret := New(t).Elem()
2421 ret.SetBytes(v)
2422 ret.flag = ret.flag&^flagAddr | f
2423 return ret
2426 func makeRunes(f flag, v []rune, t Type) Value {
2427 ret := New(t).Elem()
2428 ret.setRunes(v)
2429 ret.flag = ret.flag&^flagAddr | f
2430 return ret
2433 // These conversion functions are returned by convertOp
2434 // for classes of conversions. For example, the first function, cvtInt,
2435 // takes any value v of signed int type and returns the value converted
2436 // to type t, where t is any signed or unsigned int type.
2438 // convertOp: intXX -> [u]intXX
2439 func cvtInt(v Value, t Type) Value {
2440 return makeInt(v.flag.ro(), uint64(v.Int()), t)
2443 // convertOp: uintXX -> [u]intXX
2444 func cvtUint(v Value, t Type) Value {
2445 return makeInt(v.flag.ro(), v.Uint(), t)
2448 // convertOp: floatXX -> intXX
2449 func cvtFloatInt(v Value, t Type) Value {
2450 return makeInt(v.flag.ro(), uint64(int64(v.Float())), t)
2453 // convertOp: floatXX -> uintXX
2454 func cvtFloatUint(v Value, t Type) Value {
2455 return makeInt(v.flag.ro(), uint64(v.Float()), t)
2458 // convertOp: intXX -> floatXX
2459 func cvtIntFloat(v Value, t Type) Value {
2460 return makeFloat(v.flag.ro(), float64(v.Int()), t)
2463 // convertOp: uintXX -> floatXX
2464 func cvtUintFloat(v Value, t Type) Value {
2465 return makeFloat(v.flag.ro(), float64(v.Uint()), t)
2468 // convertOp: floatXX -> floatXX
2469 func cvtFloat(v Value, t Type) Value {
2470 if v.Type().Kind() == Float32 && t.Kind() == Float32 {
2471 // Don't do any conversion if both types have underlying type float32.
2472 // This avoids converting to float64 and back, which will
2473 // convert a signaling NaN to a quiet NaN. See issue 36400.
2474 return makeFloat32(v.flag.ro(), *(*float32)(v.ptr), t)
2476 return makeFloat(v.flag.ro(), v.Float(), t)
2479 // convertOp: complexXX -> complexXX
2480 func cvtComplex(v Value, t Type) Value {
2481 return makeComplex(v.flag.ro(), v.Complex(), t)
2484 // convertOp: intXX -> string
2485 func cvtIntString(v Value, t Type) Value {
2486 s := "\uFFFD"
2487 if x := v.Int(); int64(rune(x)) == x {
2488 s = string(rune(x))
2490 return makeString(v.flag.ro(), s, t)
2493 // convertOp: uintXX -> string
2494 func cvtUintString(v Value, t Type) Value {
2495 s := "\uFFFD"
2496 if x := v.Uint(); uint64(rune(x)) == x {
2497 s = string(rune(x))
2499 return makeString(v.flag.ro(), s, t)
2502 // convertOp: []byte -> string
2503 func cvtBytesString(v Value, t Type) Value {
2504 return makeString(v.flag.ro(), string(v.Bytes()), t)
2507 // convertOp: string -> []byte
2508 func cvtStringBytes(v Value, t Type) Value {
2509 return makeBytes(v.flag.ro(), []byte(v.String()), t)
2512 // convertOp: []rune -> string
2513 func cvtRunesString(v Value, t Type) Value {
2514 return makeString(v.flag.ro(), string(v.runes()), t)
2517 // convertOp: string -> []rune
2518 func cvtStringRunes(v Value, t Type) Value {
2519 return makeRunes(v.flag.ro(), []rune(v.String()), t)
2522 // convertOp: direct copy
2523 func cvtDirect(v Value, typ Type) Value {
2524 f := v.flag
2525 t := typ.common()
2526 ptr := v.ptr
2527 if f&flagAddr != 0 {
2528 // indirect, mutable word - make a copy
2529 c := unsafe_New(t)
2530 typedmemmove(t, c, ptr)
2531 ptr = c
2532 f &^= flagAddr
2534 return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f?
2537 // convertOp: concrete -> interface
2538 func cvtT2I(v Value, typ Type) Value {
2539 target := unsafe_New(typ.common())
2540 x := valueInterface(v, false)
2541 if typ.NumMethod() == 0 {
2542 *(*interface{})(target) = x
2543 } else {
2544 ifaceE2I(typ.(*rtype), x, target)
2546 return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)}
2549 // convertOp: interface -> interface
2550 func cvtI2I(v Value, typ Type) Value {
2551 if v.IsNil() {
2552 ret := Zero(typ)
2553 ret.flag |= v.flag.ro()
2554 return ret
2556 return cvtT2I(v.Elem(), typ)
2559 // implemented in ../runtime
2560 func chancap(ch unsafe.Pointer) int
2561 func chanclose(ch unsafe.Pointer)
2562 func chanlen(ch unsafe.Pointer) int
2564 // Note: some of the noescape annotations below are technically a lie,
2565 // but safe in the context of this package. Functions like chansend
2566 // and mapassign don't escape the referent, but may escape anything
2567 // the referent points to (they do shallow copies of the referent).
2568 // It is safe in this package because the referent may only point
2569 // to something a Value may point to, and that is always in the heap
2570 // (due to the escapes() call in ValueOf).
2572 //go:noescape
2573 func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
2575 //go:noescape
2576 func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
2578 func makechan(typ *rtype, size int) (ch unsafe.Pointer)
2579 func makemap(t *rtype, cap int) (m unsafe.Pointer)
2581 //go:noescape
2582 func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
2584 //go:noescape
2585 func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
2587 //go:noescape
2588 func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
2590 // m escapes into the return value, but the caller of mapiterinit
2591 // doesn't let the return value escape.
2592 //go:noescape
2593 func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
2595 //go:noescape
2596 func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
2598 //go:noescape
2599 func mapiterelem(it unsafe.Pointer) (elem unsafe.Pointer)
2601 //go:noescape
2602 func mapiternext(it unsafe.Pointer)
2604 //go:noescape
2605 func maplen(m unsafe.Pointer) int
2607 //go:linkname call runtime.reflectcall
2608 func call(typ *funcType, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer)
2610 func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
2612 // memmove copies size bytes to dst from src. No write barriers are used.
2613 //go:noescape
2614 func memmove(dst, src unsafe.Pointer, size uintptr)
2616 // typedmemmove copies a value of type t to dst from src.
2617 //go:noescape
2618 func typedmemmove(t *rtype, dst, src unsafe.Pointer)
2620 // typedmemclr zeros the value at ptr of type t.
2621 //go:noescape
2622 func typedmemclr(t *rtype, ptr unsafe.Pointer)
2624 // typedslicecopy copies a slice of elemType values from src to dst,
2625 // returning the number of elements copied.
2626 //go:noescape
2627 func typedslicecopy(elemType *rtype, dst, src unsafeheader.Slice) int
2629 //go:noescape
2630 func typehash(t *rtype, p unsafe.Pointer, h uintptr) uintptr
2632 // Dummy annotation marking that the value x escapes,
2633 // for use in cases where the reflect code is so clever that
2634 // the compiler cannot follow.
2635 func escapes(x interface{}) {
2636 if dummy.b {
2637 dummy.x = x
2641 var dummy struct {
2642 b bool
2643 x interface{}