libgo: update to go1.9
[official-gcc.git] / libgo / go / reflect / value.go
blob792699a6f659349e0fb37c511f151ecd7227b1c3
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 "math"
9 "runtime"
10 "unsafe"
13 const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const
15 // Value is the reflection interface to a Go value.
17 // Not all methods apply to all kinds of values. Restrictions,
18 // if any, are noted in the documentation for each method.
19 // Use the Kind method to find out the kind of value before
20 // calling kind-specific methods. Calling a method
21 // inappropriate to the kind of type causes a run time panic.
23 // The zero Value represents no value.
24 // Its IsValid method returns false, its Kind method returns Invalid,
25 // its String method returns "<invalid Value>", and all other methods panic.
26 // Most functions and methods never return an invalid value.
27 // If one does, its documentation states the conditions explicitly.
29 // A Value can be used concurrently by multiple goroutines provided that
30 // the underlying Go value can be used concurrently for the equivalent
31 // direct operations.
33 // To compare two Values, compare the results of the Interface method.
34 // Using == on two Values does not compare the underlying values
35 // they represent.
36 type Value struct {
37 // typ holds the type of the value represented by a Value.
38 typ *rtype
40 // Pointer-valued data or, if flagIndir is set, pointer to data.
41 // Valid when either flagIndir is set or typ.pointers() is true.
42 ptr unsafe.Pointer
44 // flag holds metadata about the value.
45 // The lowest bits are flag bits:
46 // - flagStickyRO: obtained via unexported not embedded field, so read-only
47 // - flagEmbedRO: obtained via unexported embedded field, so read-only
48 // - flagIndir: val holds a pointer to the data
49 // - flagAddr: v.CanAddr is true (implies flagIndir)
50 // - flagMethod: v is a method value.
51 // The next five bits give the Kind of the value.
52 // This repeats typ.Kind() except for method values.
53 // The remaining 23+ bits give a method number for method values.
54 // If flag.kind() != Func, code can assume that flagMethod is unset.
55 // If ifaceIndir(typ), code can assume that flagIndir is set.
56 flag
58 // A method value represents a curried method invocation
59 // like r.Read for some receiver r. The typ+val+flag bits describe
60 // the receiver r, but the flag's Kind bits say Func (methods are
61 // functions), and the top bits of the flag give the method number
62 // in r's type's method table.
65 type flag uintptr
67 const (
68 flagKindWidth = 5 // there are 27 kinds
69 flagKindMask flag = 1<<flagKindWidth - 1
70 flagStickyRO flag = 1 << 5
71 flagEmbedRO flag = 1 << 6
72 flagIndir flag = 1 << 7
73 flagAddr flag = 1 << 8
74 flagMethod flag = 1 << 9
75 flagMethodFn flag = 1 << 10 // gccgo: first fn parameter is always pointer
76 flagMethodShift = 11
77 flagRO flag = flagStickyRO | flagEmbedRO
80 func (f flag) kind() Kind {
81 return Kind(f & flagKindMask)
84 // pointer returns the underlying pointer represented by v.
85 // v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer
86 func (v Value) pointer() unsafe.Pointer {
87 if v.typ.size != ptrSize || !v.typ.pointers() {
88 panic("can't call pointer on a non-pointer Value")
90 if v.flag&flagIndir != 0 {
91 return *(*unsafe.Pointer)(v.ptr)
93 return v.ptr
96 // packEface converts v to the empty interface.
97 func packEface(v Value) interface{} {
98 t := v.typ
99 var i interface{}
100 e := (*emptyInterface)(unsafe.Pointer(&i))
101 // First, fill in the data portion of the interface.
102 switch {
103 case ifaceIndir(t):
104 if v.flag&flagIndir == 0 {
105 panic("bad indir")
107 // Value is indirect, and so is the interface we're making.
108 ptr := v.ptr
109 if v.flag&flagAddr != 0 {
110 // TODO: pass safe boolean from valueInterface so
111 // we don't need to copy if safe==true?
112 c := unsafe_New(t)
113 typedmemmove(t, c, ptr)
114 ptr = c
116 e.word = ptr
117 case v.flag&flagIndir != 0:
118 // Value is indirect, but interface is direct. We need
119 // to load the data at v.ptr into the interface data word.
120 e.word = *(*unsafe.Pointer)(v.ptr)
121 default:
122 // Value is direct, and so is the interface.
123 e.word = v.ptr
125 // Now, fill in the type portion. We're very careful here not
126 // to have any operation between the e.word and e.typ assignments
127 // that would let the garbage collector observe the partially-built
128 // interface value.
129 e.typ = t
130 return i
133 // unpackEface converts the empty interface i to a Value.
134 func unpackEface(i interface{}) Value {
135 e := (*emptyInterface)(unsafe.Pointer(&i))
136 // NOTE: don't read e.word until we know whether it is really a pointer or not.
137 t := e.typ
138 if t == nil {
139 return Value{}
141 f := flag(t.Kind())
142 if ifaceIndir(t) {
143 f |= flagIndir
145 return Value{t, e.word, f}
148 // A ValueError occurs when a Value method is invoked on
149 // a Value that does not support it. Such cases are documented
150 // in the description of each method.
151 type ValueError struct {
152 Method string
153 Kind Kind
156 func (e *ValueError) Error() string {
157 if e.Kind == 0 {
158 return "reflect: call of " + e.Method + " on zero Value"
160 return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
163 // methodName returns the name of the calling method,
164 // assumed to be two stack frames above.
165 func methodName() string {
166 pc, _, _, _ := runtime.Caller(2)
167 f := runtime.FuncForPC(pc)
168 if f == nil {
169 return "unknown method"
171 return f.Name()
174 // emptyInterface is the header for an interface{} value.
175 type emptyInterface struct {
176 typ *rtype
177 word unsafe.Pointer
180 // nonEmptyInterface is the header for a interface value with methods.
181 type nonEmptyInterface struct {
182 // see ../runtime/iface.go:/Itab
183 itab *struct {
184 typ *rtype // dynamic concrete type
185 fun [100000]unsafe.Pointer // method table
187 word unsafe.Pointer
190 // mustBe panics if f's kind is not expected.
191 // Making this a method on flag instead of on Value
192 // (and embedding flag in Value) means that we can write
193 // the very clear v.mustBe(Bool) and have it compile into
194 // v.flag.mustBe(Bool), which will only bother to copy the
195 // single important word for the receiver.
196 func (f flag) mustBe(expected Kind) {
197 if f.kind() != expected {
198 panic(&ValueError{methodName(), f.kind()})
202 // mustBeExported panics if f records that the value was obtained using
203 // an unexported field.
204 func (f flag) mustBeExported() {
205 if f == 0 {
206 panic(&ValueError{methodName(), 0})
208 if f&flagRO != 0 {
209 panic("reflect: " + methodName() + " using value obtained using unexported field")
213 // mustBeAssignable panics if f records that the value is not assignable,
214 // which is to say that either it was obtained using an unexported field
215 // or it is not addressable.
216 func (f flag) mustBeAssignable() {
217 if f == 0 {
218 panic(&ValueError{methodName(), Invalid})
220 // Assignable if addressable and not read-only.
221 if f&flagRO != 0 {
222 panic("reflect: " + methodName() + " using value obtained using unexported field")
224 if f&flagAddr == 0 {
225 panic("reflect: " + methodName() + " using unaddressable value")
229 // Addr returns a pointer value representing the address of v.
230 // It panics if CanAddr() returns false.
231 // Addr is typically used to obtain a pointer to a struct field
232 // or slice element in order to call a method that requires a
233 // pointer receiver.
234 func (v Value) Addr() Value {
235 if v.flag&flagAddr == 0 {
236 panic("reflect.Value.Addr of unaddressable value")
238 return Value{v.typ.ptrTo(), v.ptr, (v.flag & flagRO) | flag(Ptr)}
241 // Bool returns v's underlying value.
242 // It panics if v's kind is not Bool.
243 func (v Value) Bool() bool {
244 v.mustBe(Bool)
245 return *(*bool)(v.ptr)
248 // Bytes returns v's underlying value.
249 // It panics if v's underlying value is not a slice of bytes.
250 func (v Value) Bytes() []byte {
251 v.mustBe(Slice)
252 if v.typ.Elem().Kind() != Uint8 {
253 panic("reflect.Value.Bytes of non-byte slice")
255 // Slice is always bigger than a word; assume flagIndir.
256 return *(*[]byte)(v.ptr)
259 // runes returns v's underlying value.
260 // It panics if v's underlying value is not a slice of runes (int32s).
261 func (v Value) runes() []rune {
262 v.mustBe(Slice)
263 if v.typ.Elem().Kind() != Int32 {
264 panic("reflect.Value.Bytes of non-rune slice")
266 // Slice is always bigger than a word; assume flagIndir.
267 return *(*[]rune)(v.ptr)
270 // CanAddr reports whether the value's address can be obtained with Addr.
271 // Such values are called addressable. A value is addressable if it is
272 // an element of a slice, an element of an addressable array,
273 // a field of an addressable struct, or the result of dereferencing a pointer.
274 // If CanAddr returns false, calling Addr will panic.
275 func (v Value) CanAddr() bool {
276 return v.flag&flagAddr != 0
279 // CanSet reports whether the value of v can be changed.
280 // A Value can be changed only if it is addressable and was not
281 // obtained by the use of unexported struct fields.
282 // If CanSet returns false, calling Set or any type-specific
283 // setter (e.g., SetBool, SetInt) will panic.
284 func (v Value) CanSet() bool {
285 return v.flag&(flagAddr|flagRO) == flagAddr
288 // Call calls the function v with the input arguments in.
289 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
290 // Call panics if v's Kind is not Func.
291 // It returns the output results as Values.
292 // As in Go, each input argument must be assignable to the
293 // type of the function's corresponding input parameter.
294 // If v is a variadic function, Call creates the variadic slice parameter
295 // itself, copying in the corresponding values.
296 func (v Value) Call(in []Value) []Value {
297 v.mustBe(Func)
298 v.mustBeExported()
299 return v.call("Call", in)
302 // CallSlice calls the variadic function v with the input arguments in,
303 // assigning the slice in[len(in)-1] to v's final variadic argument.
304 // For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).
305 // CallSlice panics if v's Kind is not Func or if v is not variadic.
306 // It returns the output results as Values.
307 // As in Go, each input argument must be assignable to the
308 // type of the function's corresponding input parameter.
309 func (v Value) CallSlice(in []Value) []Value {
310 v.mustBe(Func)
311 v.mustBeExported()
312 return v.call("CallSlice", in)
315 var callGC bool // for testing; see TestCallMethodJump
317 func (v Value) call(op string, in []Value) []Value {
318 // Get function pointer, type.
319 t := v.typ
320 var (
321 fn unsafe.Pointer
322 rcvr Value
324 if v.flag&flagMethod != 0 {
325 rcvr = v
326 _, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
327 } else if v.flag&flagIndir != 0 {
328 fn = *(*unsafe.Pointer)(v.ptr)
329 } else {
330 fn = v.ptr
333 if fn == nil {
334 panic("reflect.Value.Call: call of nil function")
337 isSlice := op == "CallSlice"
338 n := t.NumIn()
339 if isSlice {
340 if !t.IsVariadic() {
341 panic("reflect: CallSlice of non-variadic function")
343 if len(in) < n {
344 panic("reflect: CallSlice with too few input arguments")
346 if len(in) > n {
347 panic("reflect: CallSlice with too many input arguments")
349 } else {
350 if t.IsVariadic() {
353 if len(in) < n {
354 panic("reflect: Call with too few input arguments")
356 if !t.IsVariadic() && len(in) > n {
357 panic("reflect: Call with too many input arguments")
360 for _, x := range in {
361 if x.Kind() == Invalid {
362 panic("reflect: " + op + " using zero Value argument")
365 for i := 0; i < n; i++ {
366 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
367 panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String())
370 if !isSlice && t.IsVariadic() {
371 // prepare slice for remaining values
372 m := len(in) - n
373 slice := MakeSlice(t.In(n), m, m)
374 elem := t.In(n).Elem()
375 for i := 0; i < m; i++ {
376 x := in[n+i]
377 if xt := x.Type(); !xt.AssignableTo(elem) {
378 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
380 slice.Index(i).Set(x)
382 origIn := in
383 in = make([]Value, n+1)
384 copy(in[:n], origIn)
385 in[n] = slice
388 nin := len(in)
389 if nin != t.NumIn() {
390 panic("reflect.Value.Call: wrong argument count")
392 nout := t.NumOut()
394 if v.flag&flagMethod != 0 {
395 nin++
397 firstPointer := len(in) > 0 && t.In(0).Kind() != Ptr && v.flag&flagMethodFn != 0
398 params := make([]unsafe.Pointer, nin)
399 off := 0
400 if v.flag&flagMethod != 0 {
401 // Hard-wired first argument.
402 p := new(unsafe.Pointer)
403 if rcvr.typ.Kind() == Interface {
404 *p = unsafe.Pointer((*nonEmptyInterface)(v.ptr).word)
405 } else if rcvr.typ.Kind() == Ptr || rcvr.typ.Kind() == UnsafePointer {
406 *p = rcvr.pointer()
407 } else {
408 *p = rcvr.ptr
410 params[0] = unsafe.Pointer(p)
411 off = 1
413 for i, pv := range in {
414 pv.mustBeExported()
415 targ := t.In(i).(*rtype)
416 pv = pv.assignTo("reflect.Value.Call", targ, nil)
417 if pv.flag&flagIndir == 0 {
418 p := new(unsafe.Pointer)
419 *p = pv.ptr
420 params[off] = unsafe.Pointer(p)
421 } else {
422 params[off] = pv.ptr
424 if i == 0 && firstPointer {
425 p := new(unsafe.Pointer)
426 *p = params[off]
427 params[off] = unsafe.Pointer(p)
429 off++
432 ret := make([]Value, nout)
433 results := make([]unsafe.Pointer, nout)
434 for i := 0; i < nout; i++ {
435 tv := t.Out(i)
436 v := New(tv)
437 results[i] = v.pointer()
438 fl := flagIndir | flag(tv.Kind())
439 ret[i] = Value{tv.common(), v.pointer(), fl}
442 var pp *unsafe.Pointer
443 if len(params) > 0 {
444 pp = &params[0]
446 var pr *unsafe.Pointer
447 if len(results) > 0 {
448 pr = &results[0]
451 call(t, fn, v.flag&flagMethod != 0, firstPointer, pp, pr)
453 // For testing; see TestCallMethodJump.
454 if callGC {
455 runtime.GC()
458 return ret
461 // methodReceiver returns information about the receiver
462 // described by v. The Value v may or may not have the
463 // flagMethod bit set, so the kind cached in v.flag should
464 // not be used.
465 // The return value rcvrtype gives the method's actual receiver type.
466 // The return value t gives the method type signature (without the receiver).
467 // The return value fn is a pointer to the method code.
468 func methodReceiver(op string, v Value, methodIndex int) (rcvrtype, t *rtype, fn unsafe.Pointer) {
469 i := methodIndex
470 if v.typ.Kind() == Interface {
471 tt := (*interfaceType)(unsafe.Pointer(v.typ))
472 if uint(i) >= uint(len(tt.methods)) {
473 panic("reflect: internal error: invalid method index")
475 m := &tt.methods[i]
476 if m.pkgPath != nil {
477 panic("reflect: " + op + " of unexported method")
479 iface := (*nonEmptyInterface)(v.ptr)
480 if iface.itab == nil {
481 panic("reflect: " + op + " of method on nil interface value")
483 rcvrtype = iface.itab.typ
484 fn = unsafe.Pointer(&iface.itab.fun[i])
485 t = m.typ
486 } else {
487 rcvrtype = v.typ
488 ut := v.typ.uncommon()
489 if ut == nil || uint(i) >= uint(len(ut.methods)) {
490 panic("reflect: internal error: invalid method index")
492 m := &ut.methods[i]
493 if m.pkgPath != nil {
494 panic("reflect: " + op + " of unexported method")
496 fn = unsafe.Pointer(&m.tfn)
497 t = m.mtyp
499 return
502 // v is a method receiver. Store at p the word which is used to
503 // encode that receiver at the start of the argument list.
504 // Reflect uses the "interface" calling convention for
505 // methods, which always uses one word to record the receiver.
506 func storeRcvr(v Value, p unsafe.Pointer) {
507 t := v.typ
508 if t.Kind() == Interface {
509 // the interface data word becomes the receiver word
510 iface := (*nonEmptyInterface)(v.ptr)
511 *(*unsafe.Pointer)(p) = iface.word
512 } else if v.flag&flagIndir != 0 && !ifaceIndir(t) {
513 *(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
514 } else {
515 *(*unsafe.Pointer)(p) = v.ptr
519 // align returns the result of rounding x up to a multiple of n.
520 // n must be a power of two.
521 func align(x, n uintptr) uintptr {
522 return (x + n - 1) &^ (n - 1)
525 // funcName returns the name of f, for use in error messages.
526 func funcName(f func([]Value) []Value) string {
527 pc := *(*uintptr)(unsafe.Pointer(&f))
528 rf := runtime.FuncForPC(pc)
529 if rf != nil {
530 return rf.Name()
532 return "closure"
535 // Cap returns v's capacity.
536 // It panics if v's Kind is not Array, Chan, or Slice.
537 func (v Value) Cap() int {
538 k := v.kind()
539 switch k {
540 case Array:
541 return v.typ.Len()
542 case Chan:
543 return chancap(v.pointer())
544 case Slice:
545 // Slice is always bigger than a word; assume flagIndir.
546 return (*sliceHeader)(v.ptr).Cap
548 panic(&ValueError{"reflect.Value.Cap", v.kind()})
551 // Close closes the channel v.
552 // It panics if v's Kind is not Chan.
553 func (v Value) Close() {
554 v.mustBe(Chan)
555 v.mustBeExported()
556 chanclose(v.pointer())
559 // Complex returns v's underlying value, as a complex128.
560 // It panics if v's Kind is not Complex64 or Complex128
561 func (v Value) Complex() complex128 {
562 k := v.kind()
563 switch k {
564 case Complex64:
565 return complex128(*(*complex64)(v.ptr))
566 case Complex128:
567 return *(*complex128)(v.ptr)
569 panic(&ValueError{"reflect.Value.Complex", v.kind()})
572 // Elem returns the value that the interface v contains
573 // or that the pointer v points to.
574 // It panics if v's Kind is not Interface or Ptr.
575 // It returns the zero Value if v is nil.
576 func (v Value) Elem() Value {
577 k := v.kind()
578 switch k {
579 case Interface:
580 var eface interface{}
581 if v.typ.NumMethod() == 0 {
582 eface = *(*interface{})(v.ptr)
583 } else {
584 eface = (interface{})(*(*interface {
586 })(v.ptr))
588 x := unpackEface(eface)
589 if x.flag != 0 {
590 x.flag |= v.flag & flagRO
592 return x
593 case Ptr:
594 ptr := v.ptr
595 if v.flag&flagIndir != 0 {
596 ptr = *(*unsafe.Pointer)(ptr)
598 // The returned value's address is v's value.
599 if ptr == nil {
600 return Value{}
602 tt := (*ptrType)(unsafe.Pointer(v.typ))
603 typ := tt.elem
604 fl := v.flag&flagRO | flagIndir | flagAddr
605 fl |= flag(typ.Kind())
606 return Value{typ, ptr, fl}
608 panic(&ValueError{"reflect.Value.Elem", v.kind()})
611 // Field returns the i'th field of the struct v.
612 // It panics if v's Kind is not Struct or i is out of range.
613 func (v Value) Field(i int) Value {
614 if v.kind() != Struct {
615 panic(&ValueError{"reflect.Value.Field", v.kind()})
617 tt := (*structType)(unsafe.Pointer(v.typ))
618 if uint(i) >= uint(len(tt.fields)) {
619 panic("reflect: Field index out of range")
621 field := &tt.fields[i]
622 typ := field.typ
624 // Inherit permission bits from v, but clear flagEmbedRO.
625 fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind())
626 // Using an unexported field forces flagRO.
627 if field.pkgPath != nil {
628 if field.anon() {
629 fl |= flagEmbedRO
630 } else {
631 fl |= flagStickyRO
634 // Either flagIndir is set and v.ptr points at struct,
635 // or flagIndir is not set and v.ptr is the actual struct data.
636 // In the former case, we want v.ptr + offset.
637 // In the latter case, we must have field.offset = 0,
638 // so v.ptr + field.offset is still okay.
639 ptr := unsafe.Pointer(uintptr(v.ptr) + field.offset())
640 return Value{typ, ptr, fl}
643 // FieldByIndex returns the nested field corresponding to index.
644 // It panics if v's Kind is not struct.
645 func (v Value) FieldByIndex(index []int) Value {
646 if len(index) == 1 {
647 return v.Field(index[0])
649 v.mustBe(Struct)
650 for i, x := range index {
651 if i > 0 {
652 if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct {
653 if v.IsNil() {
654 panic("reflect: indirection through nil pointer to embedded struct")
656 v = v.Elem()
659 v = v.Field(x)
661 return v
664 // FieldByName returns the struct field with the given name.
665 // It returns the zero Value if no field was found.
666 // It panics if v's Kind is not struct.
667 func (v Value) FieldByName(name string) Value {
668 v.mustBe(Struct)
669 if f, ok := v.typ.FieldByName(name); ok {
670 return v.FieldByIndex(f.Index)
672 return Value{}
675 // FieldByNameFunc returns the struct field with a name
676 // that satisfies the match function.
677 // It panics if v's Kind is not struct.
678 // It returns the zero Value if no field was found.
679 func (v Value) FieldByNameFunc(match func(string) bool) Value {
680 if f, ok := v.typ.FieldByNameFunc(match); ok {
681 return v.FieldByIndex(f.Index)
683 return Value{}
686 // Float returns v's underlying value, as a float64.
687 // It panics if v's Kind is not Float32 or Float64
688 func (v Value) Float() float64 {
689 k := v.kind()
690 switch k {
691 case Float32:
692 return float64(*(*float32)(v.ptr))
693 case Float64:
694 return *(*float64)(v.ptr)
696 panic(&ValueError{"reflect.Value.Float", v.kind()})
699 var uint8Type = TypeOf(uint8(0)).(*rtype)
701 // Index returns v's i'th element.
702 // It panics if v's Kind is not Array, Slice, or String or i is out of range.
703 func (v Value) Index(i int) Value {
704 switch v.kind() {
705 case Array:
706 tt := (*arrayType)(unsafe.Pointer(v.typ))
707 if uint(i) >= uint(tt.len) {
708 panic("reflect: array index out of range")
710 typ := tt.elem
711 offset := uintptr(i) * typ.size
713 // Either flagIndir is set and v.ptr points at array,
714 // or flagIndir is not set and v.ptr is the actual array data.
715 // In the former case, we want v.ptr + offset.
716 // In the latter case, we must be doing Index(0), so offset = 0,
717 // so v.ptr + offset is still okay.
718 val := unsafe.Pointer(uintptr(v.ptr) + offset)
719 fl := v.flag&(flagRO|flagIndir|flagAddr) | flag(typ.Kind()) // bits same as overall array
720 return Value{typ, val, fl}
722 case Slice:
723 // Element flag same as Elem of Ptr.
724 // Addressable, indirect, possibly read-only.
725 s := (*sliceHeader)(v.ptr)
726 if uint(i) >= uint(s.Len) {
727 panic("reflect: slice index out of range")
729 tt := (*sliceType)(unsafe.Pointer(v.typ))
730 typ := tt.elem
731 val := arrayAt(s.Data, i, typ.size)
732 fl := flagAddr | flagIndir | v.flag&flagRO | flag(typ.Kind())
733 return Value{typ, val, fl}
735 case String:
736 s := (*stringHeader)(v.ptr)
737 if uint(i) >= uint(s.Len) {
738 panic("reflect: string index out of range")
740 p := arrayAt(s.Data, i, 1)
741 fl := v.flag&flagRO | flag(Uint8) | flagIndir
742 return Value{uint8Type, p, fl}
744 panic(&ValueError{"reflect.Value.Index", v.kind()})
747 // Int returns v's underlying value, as an int64.
748 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
749 func (v Value) Int() int64 {
750 k := v.kind()
751 p := v.ptr
752 switch k {
753 case Int:
754 return int64(*(*int)(p))
755 case Int8:
756 return int64(*(*int8)(p))
757 case Int16:
758 return int64(*(*int16)(p))
759 case Int32:
760 return int64(*(*int32)(p))
761 case Int64:
762 return *(*int64)(p)
764 panic(&ValueError{"reflect.Value.Int", v.kind()})
767 // CanInterface reports whether Interface can be used without panicking.
768 func (v Value) CanInterface() bool {
769 if v.flag == 0 {
770 panic(&ValueError{"reflect.Value.CanInterface", Invalid})
772 return v.flag&flagRO == 0
775 // Interface returns v's current value as an interface{}.
776 // It is equivalent to:
777 // var i interface{} = (v's underlying value)
778 // It panics if the Value was obtained by accessing
779 // unexported struct fields.
780 func (v Value) Interface() (i interface{}) {
781 return valueInterface(v, true)
784 func valueInterface(v Value, safe bool) interface{} {
785 if v.flag == 0 {
786 panic(&ValueError{"reflect.Value.Interface", 0})
788 if safe && v.flag&flagRO != 0 {
789 // Do not allow access to unexported values via Interface,
790 // because they might be pointers that should not be
791 // writable or methods or function that should not be callable.
792 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
794 if v.flag&flagMethod != 0 {
795 v = makeMethodValue("Interface", v)
798 if v.flag&flagMethodFn != 0 {
799 if v.typ.Kind() != Func {
800 panic("reflect: MethodFn of non-Func")
802 ft := (*funcType)(unsafe.Pointer(v.typ))
803 if ft.in[0].Kind() != Ptr {
804 v = makeValueMethod(v)
808 if v.kind() == Interface {
809 // Special case: return the element inside the interface.
810 // Empty interface has one layout, all interfaces with
811 // methods have a second layout.
812 if v.NumMethod() == 0 {
813 return *(*interface{})(v.ptr)
815 return *(*interface {
817 })(v.ptr)
820 // TODO: pass safe to packEface so we don't need to copy if safe==true?
821 return packEface(v)
824 // InterfaceData returns the interface v's value as a uintptr pair.
825 // It panics if v's Kind is not Interface.
826 func (v Value) InterfaceData() [2]uintptr {
827 // TODO: deprecate this
828 v.mustBe(Interface)
829 // We treat this as a read operation, so we allow
830 // it even for unexported data, because the caller
831 // has to import "unsafe" to turn it into something
832 // that can be abused.
833 // Interface value is always bigger than a word; assume flagIndir.
834 return *(*[2]uintptr)(v.ptr)
837 // IsNil reports whether its argument v is nil. The argument must be
838 // a chan, func, interface, map, pointer, or slice value; if it is
839 // not, IsNil panics. Note that IsNil is not always equivalent to a
840 // regular comparison with nil in Go. For example, if v was created
841 // by calling ValueOf with an uninitialized interface variable i,
842 // i==nil will be true but v.IsNil will panic as v will be the zero
843 // Value.
844 func (v Value) IsNil() bool {
845 k := v.kind()
846 switch k {
847 case Chan, Func, Map, Ptr:
848 if v.flag&flagMethod != 0 {
849 return false
851 ptr := v.ptr
852 if v.flag&flagIndir != 0 {
853 ptr = *(*unsafe.Pointer)(ptr)
855 return ptr == nil
856 case Interface, Slice:
857 // Both interface and slice are nil if first word is 0.
858 // Both are always bigger than a word; assume flagIndir.
859 return *(*unsafe.Pointer)(v.ptr) == nil
861 panic(&ValueError{"reflect.Value.IsNil", v.kind()})
864 // IsValid reports whether v represents a value.
865 // It returns false if v is the zero Value.
866 // If IsValid returns false, all other methods except String panic.
867 // Most functions and methods never return an invalid value.
868 // If one does, its documentation states the conditions explicitly.
869 func (v Value) IsValid() bool {
870 return v.flag != 0
873 // Kind returns v's Kind.
874 // If v is the zero Value (IsValid returns false), Kind returns Invalid.
875 func (v Value) Kind() Kind {
876 return v.kind()
879 // Len returns v's length.
880 // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
881 func (v Value) Len() int {
882 k := v.kind()
883 switch k {
884 case Array:
885 tt := (*arrayType)(unsafe.Pointer(v.typ))
886 return int(tt.len)
887 case Chan:
888 return chanlen(v.pointer())
889 case Map:
890 return maplen(v.pointer())
891 case Slice:
892 // Slice is bigger than a word; assume flagIndir.
893 return (*sliceHeader)(v.ptr).Len
894 case String:
895 // String is bigger than a word; assume flagIndir.
896 return (*stringHeader)(v.ptr).Len
898 panic(&ValueError{"reflect.Value.Len", v.kind()})
901 // MapIndex returns the value associated with key in the map v.
902 // It panics if v's Kind is not Map.
903 // It returns the zero Value if key is not found in the map or if v represents a nil map.
904 // As in Go, the key's value must be assignable to the map's key type.
905 func (v Value) MapIndex(key Value) Value {
906 v.mustBe(Map)
907 tt := (*mapType)(unsafe.Pointer(v.typ))
909 // Do not require key to be exported, so that DeepEqual
910 // and other programs can use all the keys returned by
911 // MapKeys as arguments to MapIndex. If either the map
912 // or the key is unexported, though, the result will be
913 // considered unexported. This is consistent with the
914 // behavior for structs, which allow read but not write
915 // of unexported fields.
916 key = key.assignTo("reflect.Value.MapIndex", tt.key, nil)
918 var k unsafe.Pointer
919 if key.flag&flagIndir != 0 {
920 k = key.ptr
921 } else {
922 k = unsafe.Pointer(&key.ptr)
924 e := mapaccess(v.typ, v.pointer(), k)
925 if e == nil {
926 return Value{}
928 typ := tt.elem
929 fl := (v.flag | key.flag) & flagRO
930 fl |= flag(typ.Kind())
931 if ifaceIndir(typ) {
932 // Copy result so future changes to the map
933 // won't change the underlying value.
934 c := unsafe_New(typ)
935 typedmemmove(typ, c, e)
936 return Value{typ, c, fl | flagIndir}
937 } else {
938 return Value{typ, *(*unsafe.Pointer)(e), fl}
942 // MapKeys returns a slice containing all the keys present in the map,
943 // in unspecified order.
944 // It panics if v's Kind is not Map.
945 // It returns an empty slice if v represents a nil map.
946 func (v Value) MapKeys() []Value {
947 v.mustBe(Map)
948 tt := (*mapType)(unsafe.Pointer(v.typ))
949 keyType := tt.key
951 fl := v.flag&flagRO | flag(keyType.Kind())
953 m := v.pointer()
954 mlen := int(0)
955 if m != nil {
956 mlen = maplen(m)
958 it := mapiterinit(v.typ, m)
959 a := make([]Value, mlen)
960 var i int
961 for i = 0; i < len(a); i++ {
962 key := mapiterkey(it)
963 if key == nil {
964 // Someone deleted an entry from the map since we
965 // called maplen above. It's a data race, but nothing
966 // we can do about it.
967 break
969 if ifaceIndir(keyType) {
970 // Copy result so future changes to the map
971 // won't change the underlying value.
972 c := unsafe_New(keyType)
973 typedmemmove(keyType, c, key)
974 a[i] = Value{keyType, c, fl | flagIndir}
975 } else {
976 a[i] = Value{keyType, *(*unsafe.Pointer)(key), fl}
978 mapiternext(it)
980 return a[:i]
983 // Method returns a function value corresponding to v's i'th method.
984 // The arguments to a Call on the returned function should not include
985 // a receiver; the returned function will always use v as the receiver.
986 // Method panics if i is out of range or if v is a nil interface value.
987 func (v Value) Method(i int) Value {
988 if v.typ == nil {
989 panic(&ValueError{"reflect.Value.Method", Invalid})
991 if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) {
992 panic("reflect: Method index out of range")
994 if v.typ.Kind() == Interface && v.IsNil() {
995 panic("reflect: Method on nil interface value")
997 fl := v.flag & (flagStickyRO | flagIndir) // Clear flagEmbedRO
998 fl |= flag(Func)
999 fl |= flag(i)<<flagMethodShift | flagMethod
1000 return Value{v.typ, v.ptr, fl}
1003 // NumMethod returns the number of exported methods in the value's method set.
1004 func (v Value) NumMethod() int {
1005 if v.typ == nil {
1006 panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1008 if v.flag&flagMethod != 0 {
1009 return 0
1011 return v.typ.NumMethod()
1014 // MethodByName returns a function value corresponding to the method
1015 // of v with the given name.
1016 // The arguments to a Call on the returned function should not include
1017 // a receiver; the returned function will always use v as the receiver.
1018 // It returns the zero Value if no method was found.
1019 func (v Value) MethodByName(name string) Value {
1020 if v.typ == nil {
1021 panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1023 if v.flag&flagMethod != 0 {
1024 return Value{}
1026 m, ok := v.typ.MethodByName(name)
1027 if !ok {
1028 return Value{}
1030 return v.Method(m.Index)
1033 // NumField returns the number of fields in the struct v.
1034 // It panics if v's Kind is not Struct.
1035 func (v Value) NumField() int {
1036 v.mustBe(Struct)
1037 tt := (*structType)(unsafe.Pointer(v.typ))
1038 return len(tt.fields)
1041 // OverflowComplex reports whether the complex128 x cannot be represented by v's type.
1042 // It panics if v's Kind is not Complex64 or Complex128.
1043 func (v Value) OverflowComplex(x complex128) bool {
1044 k := v.kind()
1045 switch k {
1046 case Complex64:
1047 return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1048 case Complex128:
1049 return false
1051 panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
1054 // OverflowFloat reports whether the float64 x cannot be represented by v's type.
1055 // It panics if v's Kind is not Float32 or Float64.
1056 func (v Value) OverflowFloat(x float64) bool {
1057 k := v.kind()
1058 switch k {
1059 case Float32:
1060 return overflowFloat32(x)
1061 case Float64:
1062 return false
1064 panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
1067 func overflowFloat32(x float64) bool {
1068 if x < 0 {
1069 x = -x
1071 return math.MaxFloat32 < x && x <= math.MaxFloat64
1074 // OverflowInt reports whether the int64 x cannot be represented by v's type.
1075 // It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
1076 func (v Value) OverflowInt(x int64) bool {
1077 k := v.kind()
1078 switch k {
1079 case Int, Int8, Int16, Int32, Int64:
1080 bitSize := v.typ.size * 8
1081 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1082 return x != trunc
1084 panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
1087 // OverflowUint reports whether the uint64 x cannot be represented by v's type.
1088 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1089 func (v Value) OverflowUint(x uint64) bool {
1090 k := v.kind()
1091 switch k {
1092 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1093 bitSize := v.typ.size * 8
1094 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1095 return x != trunc
1097 panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
1100 // Pointer returns v's value as a uintptr.
1101 // It returns uintptr instead of unsafe.Pointer so that
1102 // code using reflect cannot obtain unsafe.Pointers
1103 // without importing the unsafe package explicitly.
1104 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1106 // If v's Kind is Func, the returned pointer is an underlying
1107 // code pointer, but not necessarily enough to identify a
1108 // single function uniquely. The only guarantee is that the
1109 // result is zero if and only if v is a nil func Value.
1111 // If v's Kind is Slice, the returned pointer is to the first
1112 // element of the slice. If the slice is nil the returned value
1113 // is 0. If the slice is empty but non-nil the return value is non-zero.
1114 func (v Value) Pointer() uintptr {
1115 // TODO: deprecate
1116 k := v.kind()
1117 switch k {
1118 case Chan, Map, Ptr, UnsafePointer:
1119 return uintptr(v.pointer())
1120 case Func:
1121 p := v.pointer()
1122 // Non-nil func value points at data block.
1123 // First word of data block is actual code.
1124 if p != nil {
1125 p = *(*unsafe.Pointer)(p)
1127 return uintptr(p)
1129 case Slice:
1130 return (*SliceHeader)(v.ptr).Data
1132 panic(&ValueError{"reflect.Value.Pointer", v.kind()})
1135 // Recv receives and returns a value from the channel v.
1136 // It panics if v's Kind is not Chan.
1137 // The receive blocks until a value is ready.
1138 // The boolean value ok is true if the value x corresponds to a send
1139 // on the channel, false if it is a zero value received because the channel is closed.
1140 func (v Value) Recv() (x Value, ok bool) {
1141 v.mustBe(Chan)
1142 v.mustBeExported()
1143 return v.recv(false)
1146 // internal recv, possibly non-blocking (nb).
1147 // v is known to be a channel.
1148 func (v Value) recv(nb bool) (val Value, ok bool) {
1149 tt := (*chanType)(unsafe.Pointer(v.typ))
1150 if ChanDir(tt.dir)&RecvDir == 0 {
1151 panic("reflect: recv on send-only channel")
1153 t := tt.elem
1154 val = Value{t, nil, flag(t.Kind())}
1155 var p unsafe.Pointer
1156 if ifaceIndir(t) {
1157 p = unsafe_New(t)
1158 val.ptr = p
1159 val.flag |= flagIndir
1160 } else {
1161 p = unsafe.Pointer(&val.ptr)
1163 selected, ok := chanrecv(v.pointer(), nb, p)
1164 if !selected {
1165 val = Value{}
1167 return
1170 // Send sends x on the channel v.
1171 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1172 // As in Go, x's value must be assignable to the channel's element type.
1173 func (v Value) Send(x Value) {
1174 v.mustBe(Chan)
1175 v.mustBeExported()
1176 v.send(x, false)
1179 // internal send, possibly non-blocking.
1180 // v is known to be a channel.
1181 func (v Value) send(x Value, nb bool) (selected bool) {
1182 tt := (*chanType)(unsafe.Pointer(v.typ))
1183 if ChanDir(tt.dir)&SendDir == 0 {
1184 panic("reflect: send on recv-only channel")
1186 x.mustBeExported()
1187 x = x.assignTo("reflect.Value.Send", tt.elem, nil)
1188 var p unsafe.Pointer
1189 if x.flag&flagIndir != 0 {
1190 p = x.ptr
1191 } else {
1192 p = unsafe.Pointer(&x.ptr)
1194 return chansend(v.pointer(), p, nb)
1197 // Set assigns x to the value v.
1198 // It panics if CanSet returns false.
1199 // As in Go, x's value must be assignable to v's type.
1200 func (v Value) Set(x Value) {
1201 v.mustBeAssignable()
1202 x.mustBeExported() // do not let unexported x leak
1203 var target unsafe.Pointer
1204 if v.kind() == Interface {
1205 target = v.ptr
1207 x = x.assignTo("reflect.Set", v.typ, target)
1208 if x.flag&flagIndir != 0 {
1209 typedmemmove(v.typ, v.ptr, x.ptr)
1210 } else {
1211 *(*unsafe.Pointer)(v.ptr) = x.ptr
1215 // SetBool sets v's underlying value.
1216 // It panics if v's Kind is not Bool or if CanSet() is false.
1217 func (v Value) SetBool(x bool) {
1218 v.mustBeAssignable()
1219 v.mustBe(Bool)
1220 *(*bool)(v.ptr) = x
1223 // SetBytes sets v's underlying value.
1224 // It panics if v's underlying value is not a slice of bytes.
1225 func (v Value) SetBytes(x []byte) {
1226 v.mustBeAssignable()
1227 v.mustBe(Slice)
1228 if v.typ.Elem().Kind() != Uint8 {
1229 panic("reflect.Value.SetBytes of non-byte slice")
1231 *(*[]byte)(v.ptr) = x
1234 // setRunes sets v's underlying value.
1235 // It panics if v's underlying value is not a slice of runes (int32s).
1236 func (v Value) setRunes(x []rune) {
1237 v.mustBeAssignable()
1238 v.mustBe(Slice)
1239 if v.typ.Elem().Kind() != Int32 {
1240 panic("reflect.Value.setRunes of non-rune slice")
1242 *(*[]rune)(v.ptr) = x
1245 // SetComplex sets v's underlying value to x.
1246 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1247 func (v Value) SetComplex(x complex128) {
1248 v.mustBeAssignable()
1249 switch k := v.kind(); k {
1250 default:
1251 panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
1252 case Complex64:
1253 *(*complex64)(v.ptr) = complex64(x)
1254 case Complex128:
1255 *(*complex128)(v.ptr) = x
1259 // SetFloat sets v's underlying value to x.
1260 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1261 func (v Value) SetFloat(x float64) {
1262 v.mustBeAssignable()
1263 switch k := v.kind(); k {
1264 default:
1265 panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
1266 case Float32:
1267 *(*float32)(v.ptr) = float32(x)
1268 case Float64:
1269 *(*float64)(v.ptr) = x
1273 // SetInt sets v's underlying value to x.
1274 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1275 func (v Value) SetInt(x int64) {
1276 v.mustBeAssignable()
1277 switch k := v.kind(); k {
1278 default:
1279 panic(&ValueError{"reflect.Value.SetInt", v.kind()})
1280 case Int:
1281 *(*int)(v.ptr) = int(x)
1282 case Int8:
1283 *(*int8)(v.ptr) = int8(x)
1284 case Int16:
1285 *(*int16)(v.ptr) = int16(x)
1286 case Int32:
1287 *(*int32)(v.ptr) = int32(x)
1288 case Int64:
1289 *(*int64)(v.ptr) = x
1293 // SetLen sets v's length to n.
1294 // It panics if v's Kind is not Slice or if n is negative or
1295 // greater than the capacity of the slice.
1296 func (v Value) SetLen(n int) {
1297 v.mustBeAssignable()
1298 v.mustBe(Slice)
1299 s := (*sliceHeader)(v.ptr)
1300 if uint(n) > uint(s.Cap) {
1301 panic("reflect: slice length out of range in SetLen")
1303 s.Len = n
1306 // SetCap sets v's capacity to n.
1307 // It panics if v's Kind is not Slice or if n is smaller than the length or
1308 // greater than the capacity of the slice.
1309 func (v Value) SetCap(n int) {
1310 v.mustBeAssignable()
1311 v.mustBe(Slice)
1312 s := (*sliceHeader)(v.ptr)
1313 if n < s.Len || n > s.Cap {
1314 panic("reflect: slice capacity out of range in SetCap")
1316 s.Cap = n
1319 // SetMapIndex sets the value associated with key in the map v to val.
1320 // It panics if v's Kind is not Map.
1321 // If val is the zero Value, SetMapIndex deletes the key from the map.
1322 // Otherwise if v holds a nil map, SetMapIndex will panic.
1323 // As in Go, key's value must be assignable to the map's key type,
1324 // and val's value must be assignable to the map's value type.
1325 func (v Value) SetMapIndex(key, val Value) {
1326 v.mustBe(Map)
1327 v.mustBeExported()
1328 key.mustBeExported()
1329 tt := (*mapType)(unsafe.Pointer(v.typ))
1330 key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
1331 var k unsafe.Pointer
1332 if key.flag&flagIndir != 0 {
1333 k = key.ptr
1334 } else {
1335 k = unsafe.Pointer(&key.ptr)
1337 if val.typ == nil {
1338 mapdelete(v.typ, v.pointer(), k)
1339 return
1341 val.mustBeExported()
1342 val = val.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
1343 var e unsafe.Pointer
1344 if val.flag&flagIndir != 0 {
1345 e = val.ptr
1346 } else {
1347 e = unsafe.Pointer(&val.ptr)
1349 mapassign(v.typ, v.pointer(), k, e)
1352 // SetUint sets v's underlying value to x.
1353 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1354 func (v Value) SetUint(x uint64) {
1355 v.mustBeAssignable()
1356 switch k := v.kind(); k {
1357 default:
1358 panic(&ValueError{"reflect.Value.SetUint", v.kind()})
1359 case Uint:
1360 *(*uint)(v.ptr) = uint(x)
1361 case Uint8:
1362 *(*uint8)(v.ptr) = uint8(x)
1363 case Uint16:
1364 *(*uint16)(v.ptr) = uint16(x)
1365 case Uint32:
1366 *(*uint32)(v.ptr) = uint32(x)
1367 case Uint64:
1368 *(*uint64)(v.ptr) = x
1369 case Uintptr:
1370 *(*uintptr)(v.ptr) = uintptr(x)
1374 // SetPointer sets the unsafe.Pointer value v to x.
1375 // It panics if v's Kind is not UnsafePointer.
1376 func (v Value) SetPointer(x unsafe.Pointer) {
1377 v.mustBeAssignable()
1378 v.mustBe(UnsafePointer)
1379 *(*unsafe.Pointer)(v.ptr) = x
1382 // SetString sets v's underlying value to x.
1383 // It panics if v's Kind is not String or if CanSet() is false.
1384 func (v Value) SetString(x string) {
1385 v.mustBeAssignable()
1386 v.mustBe(String)
1387 *(*string)(v.ptr) = x
1390 // Slice returns v[i:j].
1391 // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
1392 // or if the indexes are out of bounds.
1393 func (v Value) Slice(i, j int) Value {
1394 var (
1395 cap int
1396 typ *sliceType
1397 base unsafe.Pointer
1399 switch kind := v.kind(); kind {
1400 default:
1401 panic(&ValueError{"reflect.Value.Slice", v.kind()})
1403 case Array:
1404 if v.flag&flagAddr == 0 {
1405 panic("reflect.Value.Slice: slice of unaddressable array")
1407 tt := (*arrayType)(unsafe.Pointer(v.typ))
1408 cap = int(tt.len)
1409 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1410 base = v.ptr
1412 case Slice:
1413 typ = (*sliceType)(unsafe.Pointer(v.typ))
1414 s := (*sliceHeader)(v.ptr)
1415 base = s.Data
1416 cap = s.Cap
1418 case String:
1419 s := (*stringHeader)(v.ptr)
1420 if i < 0 || j < i || j > s.Len {
1421 panic("reflect.Value.Slice: string slice index out of bounds")
1423 t := stringHeader{arrayAt(s.Data, i, 1), j - i}
1424 return Value{v.typ, unsafe.Pointer(&t), v.flag}
1427 if i < 0 || j < i || j > cap {
1428 panic("reflect.Value.Slice: slice index out of bounds")
1431 // Declare slice so that gc can see the base pointer in it.
1432 var x []unsafe.Pointer
1434 // Reinterpret as *sliceHeader to edit.
1435 s := (*sliceHeader)(unsafe.Pointer(&x))
1436 s.Len = j - i
1437 s.Cap = cap - i
1438 if cap-i > 0 {
1439 s.Data = arrayAt(base, i, typ.elem.Size())
1440 } else {
1441 // do not advance pointer, to avoid pointing beyond end of slice
1442 s.Data = base
1445 fl := v.flag&flagRO | flagIndir | flag(Slice)
1446 return Value{typ.common(), unsafe.Pointer(&x), fl}
1449 // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
1450 // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
1451 // or if the indexes are out of bounds.
1452 func (v Value) Slice3(i, j, k int) Value {
1453 var (
1454 cap int
1455 typ *sliceType
1456 base unsafe.Pointer
1458 switch kind := v.kind(); kind {
1459 default:
1460 panic(&ValueError{"reflect.Value.Slice3", v.kind()})
1462 case Array:
1463 if v.flag&flagAddr == 0 {
1464 panic("reflect.Value.Slice3: slice of unaddressable array")
1466 tt := (*arrayType)(unsafe.Pointer(v.typ))
1467 cap = int(tt.len)
1468 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1469 base = v.ptr
1471 case Slice:
1472 typ = (*sliceType)(unsafe.Pointer(v.typ))
1473 s := (*sliceHeader)(v.ptr)
1474 base = s.Data
1475 cap = s.Cap
1478 if i < 0 || j < i || k < j || k > cap {
1479 panic("reflect.Value.Slice3: slice index out of bounds")
1482 // Declare slice so that the garbage collector
1483 // can see the base pointer in it.
1484 var x []unsafe.Pointer
1486 // Reinterpret as *sliceHeader to edit.
1487 s := (*sliceHeader)(unsafe.Pointer(&x))
1488 s.Len = j - i
1489 s.Cap = k - i
1490 if k-i > 0 {
1491 s.Data = arrayAt(base, i, typ.elem.Size())
1492 } else {
1493 // do not advance pointer, to avoid pointing beyond end of slice
1494 s.Data = base
1497 fl := v.flag&flagRO | flagIndir | flag(Slice)
1498 return Value{typ.common(), unsafe.Pointer(&x), fl}
1501 // String returns the string v's underlying value, as a string.
1502 // String is a special case because of Go's String method convention.
1503 // Unlike the other getters, it does not panic if v's Kind is not String.
1504 // Instead, it returns a string of the form "<T value>" where T is v's type.
1505 // The fmt package treats Values specially. It does not call their String
1506 // method implicitly but instead prints the concrete values they hold.
1507 func (v Value) String() string {
1508 switch k := v.kind(); k {
1509 case Invalid:
1510 return "<invalid Value>"
1511 case String:
1512 return *(*string)(v.ptr)
1514 // If you call String on a reflect.Value of other type, it's better to
1515 // print something than to panic. Useful in debugging.
1516 return "<" + v.Type().String() + " Value>"
1519 // TryRecv attempts to receive a value from the channel v but will not block.
1520 // It panics if v's Kind is not Chan.
1521 // If the receive delivers a value, x is the transferred value and ok is true.
1522 // If the receive cannot finish without blocking, x is the zero Value and ok is false.
1523 // If the channel is closed, x is the zero value for the channel's element type and ok is false.
1524 func (v Value) TryRecv() (x Value, ok bool) {
1525 v.mustBe(Chan)
1526 v.mustBeExported()
1527 return v.recv(true)
1530 // TrySend attempts to send x on the channel v but will not block.
1531 // It panics if v's Kind is not Chan.
1532 // It reports whether the value was sent.
1533 // As in Go, x's value must be assignable to the channel's element type.
1534 func (v Value) TrySend(x Value) bool {
1535 v.mustBe(Chan)
1536 v.mustBeExported()
1537 return v.send(x, true)
1540 // Type returns v's type.
1541 func (v Value) Type() Type {
1542 f := v.flag
1543 if f == 0 {
1544 panic(&ValueError{"reflect.Value.Type", Invalid})
1546 if f&flagMethod == 0 {
1547 // Easy case
1548 return toType(v.typ)
1551 // Method value.
1552 // v.typ describes the receiver, not the method type.
1553 i := int(v.flag) >> flagMethodShift
1554 if v.typ.Kind() == Interface {
1555 // Method on interface.
1556 tt := (*interfaceType)(unsafe.Pointer(v.typ))
1557 if uint(i) >= uint(len(tt.methods)) {
1558 panic("reflect: internal error: invalid method index")
1560 m := &tt.methods[i]
1561 return toType(m.typ)
1563 // Method on concrete type.
1564 ut := v.typ.uncommon()
1565 if ut == nil || uint(i) >= uint(len(ut.methods)) {
1566 panic("reflect: internal error: invalid method index")
1568 m := &ut.methods[i]
1569 return toType(m.mtyp)
1572 // Uint returns v's underlying value, as a uint64.
1573 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1574 func (v Value) Uint() uint64 {
1575 k := v.kind()
1576 p := v.ptr
1577 switch k {
1578 case Uint:
1579 return uint64(*(*uint)(p))
1580 case Uint8:
1581 return uint64(*(*uint8)(p))
1582 case Uint16:
1583 return uint64(*(*uint16)(p))
1584 case Uint32:
1585 return uint64(*(*uint32)(p))
1586 case Uint64:
1587 return *(*uint64)(p)
1588 case Uintptr:
1589 return uint64(*(*uintptr)(p))
1591 panic(&ValueError{"reflect.Value.Uint", v.kind()})
1594 // UnsafeAddr returns a pointer to v's data.
1595 // It is for advanced clients that also import the "unsafe" package.
1596 // It panics if v is not addressable.
1597 func (v Value) UnsafeAddr() uintptr {
1598 // TODO: deprecate
1599 if v.typ == nil {
1600 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
1602 if v.flag&flagAddr == 0 {
1603 panic("reflect.Value.UnsafeAddr of unaddressable value")
1605 return uintptr(v.ptr)
1608 // StringHeader is the runtime representation of a string.
1609 // It cannot be used safely or portably and its representation may
1610 // change in a later release.
1611 // Moreover, the Data field is not sufficient to guarantee the data
1612 // it references will not be garbage collected, so programs must keep
1613 // a separate, correctly typed pointer to the underlying data.
1614 type StringHeader struct {
1615 Data uintptr
1616 Len int
1619 // stringHeader is a safe version of StringHeader used within this package.
1620 type stringHeader struct {
1621 Data unsafe.Pointer
1622 Len int
1625 // SliceHeader is the runtime representation of a slice.
1626 // It cannot be used safely or portably and its representation may
1627 // change in a later release.
1628 // Moreover, the Data field is not sufficient to guarantee the data
1629 // it references will not be garbage collected, so programs must keep
1630 // a separate, correctly typed pointer to the underlying data.
1631 type SliceHeader struct {
1632 Data uintptr
1633 Len int
1634 Cap int
1637 // sliceHeader is a safe version of SliceHeader used within this package.
1638 type sliceHeader struct {
1639 Data unsafe.Pointer
1640 Len int
1641 Cap int
1644 func typesMustMatch(what string, t1, t2 Type) {
1645 if t1 != t2 {
1646 panic(what + ": " + t1.String() + " != " + t2.String())
1650 // arrayAt returns the i-th element of p, a C-array whose elements are
1651 // eltSize wide (in bytes).
1652 func arrayAt(p unsafe.Pointer, i int, eltSize uintptr) unsafe.Pointer {
1653 return unsafe.Pointer(uintptr(p) + uintptr(i)*eltSize)
1656 // grow grows the slice s so that it can hold extra more values, allocating
1657 // more capacity if needed. It also returns the old and new slice lengths.
1658 func grow(s Value, extra int) (Value, int, int) {
1659 i0 := s.Len()
1660 i1 := i0 + extra
1661 if i1 < i0 {
1662 panic("reflect.Append: slice overflow")
1664 m := s.Cap()
1665 if i1 <= m {
1666 return s.Slice(0, i1), i0, i1
1668 if m == 0 {
1669 m = extra
1670 } else {
1671 for m < i1 {
1672 if i0 < 1024 {
1673 m += m
1674 } else {
1675 m += m / 4
1679 t := MakeSlice(s.Type(), i1, m)
1680 Copy(t, s)
1681 return t, i0, i1
1684 // Append appends the values x to a slice s and returns the resulting slice.
1685 // As in Go, each x's value must be assignable to the slice's element type.
1686 func Append(s Value, x ...Value) Value {
1687 s.mustBe(Slice)
1688 s, i0, i1 := grow(s, len(x))
1689 for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
1690 s.Index(i).Set(x[j])
1692 return s
1695 // AppendSlice appends a slice t to a slice s and returns the resulting slice.
1696 // The slices s and t must have the same element type.
1697 func AppendSlice(s, t Value) Value {
1698 s.mustBe(Slice)
1699 t.mustBe(Slice)
1700 typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
1701 s, i0, i1 := grow(s, t.Len())
1702 Copy(s.Slice(i0, i1), t)
1703 return s
1706 // Copy copies the contents of src into dst until either
1707 // dst has been filled or src has been exhausted.
1708 // It returns the number of elements copied.
1709 // Dst and src each must have kind Slice or Array, and
1710 // dst and src must have the same element type.
1711 func Copy(dst, src Value) int {
1712 dk := dst.kind()
1713 if dk != Array && dk != Slice {
1714 panic(&ValueError{"reflect.Copy", dk})
1716 if dk == Array {
1717 dst.mustBeAssignable()
1719 dst.mustBeExported()
1721 sk := src.kind()
1722 if sk != Array && sk != Slice {
1723 panic(&ValueError{"reflect.Copy", sk})
1725 src.mustBeExported()
1727 de := dst.typ.Elem()
1728 se := src.typ.Elem()
1729 typesMustMatch("reflect.Copy", de, se)
1731 var ds, ss sliceHeader
1732 if dk == Array {
1733 ds.Data = dst.ptr
1734 ds.Len = dst.Len()
1735 ds.Cap = ds.Len
1736 } else {
1737 ds = *(*sliceHeader)(dst.ptr)
1739 if sk == Array {
1740 ss.Data = src.ptr
1741 ss.Len = src.Len()
1742 ss.Cap = ss.Len
1743 } else {
1744 ss = *(*sliceHeader)(src.ptr)
1747 return typedslicecopy(de.common(), ds, ss)
1750 // A runtimeSelect is a single case passed to rselect.
1751 // This must match ../runtime/select.go:/runtimeSelect
1752 type runtimeSelect struct {
1753 dir SelectDir // SelectSend, SelectRecv or SelectDefault
1754 typ *rtype // channel type
1755 ch unsafe.Pointer // channel
1756 val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
1759 // rselect runs a select. It returns the index of the chosen case.
1760 // If the case was a receive, val is filled in with the received value.
1761 // The conventional OK bool indicates whether the receive corresponds
1762 // to a sent value.
1763 //go:noescape
1764 func rselect([]runtimeSelect) (chosen int, recvOK bool)
1766 // A SelectDir describes the communication direction of a select case.
1767 type SelectDir int
1769 // NOTE: These values must match ../runtime/select.go:/selectDir.
1771 const (
1772 _ SelectDir = iota
1773 SelectSend // case Chan <- Send
1774 SelectRecv // case <-Chan:
1775 SelectDefault // default
1778 // A SelectCase describes a single case in a select operation.
1779 // The kind of case depends on Dir, the communication direction.
1781 // If Dir is SelectDefault, the case represents a default case.
1782 // Chan and Send must be zero Values.
1784 // If Dir is SelectSend, the case represents a send operation.
1785 // Normally Chan's underlying value must be a channel, and Send's underlying value must be
1786 // assignable to the channel's element type. As a special case, if Chan is a zero Value,
1787 // then the case is ignored, and the field Send will also be ignored and may be either zero
1788 // or non-zero.
1790 // If Dir is SelectRecv, the case represents a receive operation.
1791 // Normally Chan's underlying value must be a channel and Send must be a zero Value.
1792 // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
1793 // When a receive operation is selected, the received Value is returned by Select.
1795 type SelectCase struct {
1796 Dir SelectDir // direction of case
1797 Chan Value // channel to use (for send or receive)
1798 Send Value // value to send (for send)
1801 // Select executes a select operation described by the list of cases.
1802 // Like the Go select statement, it blocks until at least one of the cases
1803 // can proceed, makes a uniform pseudo-random choice,
1804 // and then executes that case. It returns the index of the chosen case
1805 // and, if that case was a receive operation, the value received and a
1806 // boolean indicating whether the value corresponds to a send on the channel
1807 // (as opposed to a zero value received because the channel is closed).
1808 func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
1809 // NOTE: Do not trust that caller is not modifying cases data underfoot.
1810 // The range is safe because the caller cannot modify our copy of the len
1811 // and each iteration makes its own copy of the value c.
1812 runcases := make([]runtimeSelect, len(cases))
1813 haveDefault := false
1814 for i, c := range cases {
1815 rc := &runcases[i]
1816 rc.dir = c.Dir
1817 switch c.Dir {
1818 default:
1819 panic("reflect.Select: invalid Dir")
1821 case SelectDefault: // default
1822 if haveDefault {
1823 panic("reflect.Select: multiple default cases")
1825 haveDefault = true
1826 if c.Chan.IsValid() {
1827 panic("reflect.Select: default case has Chan value")
1829 if c.Send.IsValid() {
1830 panic("reflect.Select: default case has Send value")
1833 case SelectSend:
1834 ch := c.Chan
1835 if !ch.IsValid() {
1836 break
1838 ch.mustBe(Chan)
1839 ch.mustBeExported()
1840 tt := (*chanType)(unsafe.Pointer(ch.typ))
1841 if ChanDir(tt.dir)&SendDir == 0 {
1842 panic("reflect.Select: SendDir case using recv-only channel")
1844 rc.ch = ch.pointer()
1845 rc.typ = &tt.rtype
1846 v := c.Send
1847 if !v.IsValid() {
1848 panic("reflect.Select: SendDir case missing Send value")
1850 v.mustBeExported()
1851 v = v.assignTo("reflect.Select", tt.elem, nil)
1852 if v.flag&flagIndir != 0 {
1853 rc.val = v.ptr
1854 } else {
1855 rc.val = unsafe.Pointer(&v.ptr)
1858 case SelectRecv:
1859 if c.Send.IsValid() {
1860 panic("reflect.Select: RecvDir case has Send value")
1862 ch := c.Chan
1863 if !ch.IsValid() {
1864 break
1866 ch.mustBe(Chan)
1867 ch.mustBeExported()
1868 tt := (*chanType)(unsafe.Pointer(ch.typ))
1869 if ChanDir(tt.dir)&RecvDir == 0 {
1870 panic("reflect.Select: RecvDir case using send-only channel")
1872 rc.ch = ch.pointer()
1873 rc.typ = &tt.rtype
1874 rc.val = unsafe_New(tt.elem)
1878 chosen, recvOK = rselect(runcases)
1879 if runcases[chosen].dir == SelectRecv {
1880 tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
1881 t := tt.elem
1882 p := runcases[chosen].val
1883 fl := flag(t.Kind())
1884 if ifaceIndir(t) {
1885 recv = Value{t, p, fl | flagIndir}
1886 } else {
1887 recv = Value{t, *(*unsafe.Pointer)(p), fl}
1890 return chosen, recv, recvOK
1894 * constructors
1897 // implemented in package runtime
1898 func unsafe_New(*rtype) unsafe.Pointer
1899 func unsafe_NewArray(*rtype, int) unsafe.Pointer
1901 // MakeSlice creates a new zero-initialized slice value
1902 // for the specified slice type, length, and capacity.
1903 func MakeSlice(typ Type, len, cap int) Value {
1904 if typ.Kind() != Slice {
1905 panic("reflect.MakeSlice of non-slice type")
1907 if len < 0 {
1908 panic("reflect.MakeSlice: negative len")
1910 if cap < 0 {
1911 panic("reflect.MakeSlice: negative cap")
1913 if len > cap {
1914 panic("reflect.MakeSlice: len > cap")
1917 s := sliceHeader{unsafe_NewArray(typ.Elem().(*rtype), cap), len, cap}
1918 return Value{typ.common(), unsafe.Pointer(&s), flagIndir | flag(Slice)}
1921 // MakeChan creates a new channel with the specified type and buffer size.
1922 func MakeChan(typ Type, buffer int) Value {
1923 if typ.Kind() != Chan {
1924 panic("reflect.MakeChan of non-chan type")
1926 if buffer < 0 {
1927 panic("reflect.MakeChan: negative buffer size")
1929 if typ.ChanDir() != BothDir {
1930 panic("reflect.MakeChan: unidirectional channel type")
1932 ch := makechan(typ.(*rtype), uint64(buffer))
1933 return Value{typ.common(), unsafe.Pointer(&ch), flag(Chan) | flagIndir}
1936 // MakeMap creates a new map with the specified type.
1937 func MakeMap(typ Type) Value {
1938 return MakeMapWithSize(typ, 0)
1941 // MakeMapWithSize creates a new map with the specified type
1942 // and initial space for approximately n elements.
1943 func MakeMapWithSize(typ Type, n int) Value {
1944 if typ.Kind() != Map {
1945 panic("reflect.MakeMapWithSize of non-map type")
1947 m := makemap(typ.(*rtype), n)
1948 return Value{typ.common(), unsafe.Pointer(&m), flag(Map) | flagIndir}
1951 // Indirect returns the value that v points to.
1952 // If v is a nil pointer, Indirect returns a zero Value.
1953 // If v is not a pointer, Indirect returns v.
1954 func Indirect(v Value) Value {
1955 if v.Kind() != Ptr {
1956 return v
1958 return v.Elem()
1961 // ValueOf returns a new Value initialized to the concrete value
1962 // stored in the interface i. ValueOf(nil) returns the zero Value.
1963 func ValueOf(i interface{}) Value {
1964 if i == nil {
1965 return Value{}
1968 // TODO: Maybe allow contents of a Value to live on the stack.
1969 // For now we make the contents always escape to the heap. It
1970 // makes life easier in a few places (see chanrecv/mapassign
1971 // comment below).
1972 escapes(i)
1974 return unpackEface(i)
1977 // Zero returns a Value representing the zero value for the specified type.
1978 // The result is different from the zero value of the Value struct,
1979 // which represents no value at all.
1980 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
1981 // The returned value is neither addressable nor settable.
1982 func Zero(typ Type) Value {
1983 if typ == nil {
1984 panic("reflect: Zero(nil)")
1986 t := typ.common()
1987 fl := flag(t.Kind())
1988 if ifaceIndir(t) {
1989 return Value{t, unsafe_New(typ.(*rtype)), fl | flagIndir}
1991 return Value{t, nil, fl}
1994 // New returns a Value representing a pointer to a new zero value
1995 // for the specified type. That is, the returned Value's Type is PtrTo(typ).
1996 func New(typ Type) Value {
1997 if typ == nil {
1998 panic("reflect: New(nil)")
2000 ptr := unsafe_New(typ.(*rtype))
2001 fl := flag(Ptr)
2002 return Value{typ.common().ptrTo(), ptr, fl}
2005 // NewAt returns a Value representing a pointer to a value of the
2006 // specified type, using p as that pointer.
2007 func NewAt(typ Type, p unsafe.Pointer) Value {
2008 fl := flag(Ptr)
2009 return Value{typ.common().ptrTo(), p, fl}
2012 // assignTo returns a value v that can be assigned directly to typ.
2013 // It panics if v is not assignable to typ.
2014 // For a conversion to an interface type, target is a suggested scratch space to use.
2015 func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value {
2016 if v.flag&flagMethod != 0 {
2017 v = makeMethodValue(context, v)
2020 switch {
2021 case directlyAssignable(dst, v.typ):
2022 // Overwrite type so that they match.
2023 // Same memory layout, so no harm done.
2024 fl := v.flag & (flagRO | flagAddr | flagIndir)
2025 fl |= flag(dst.Kind())
2026 return Value{dst, v.ptr, fl}
2028 case implements(dst, v.typ):
2029 if target == nil {
2030 target = unsafe_New(dst)
2032 x := valueInterface(v, false)
2033 if dst.NumMethod() == 0 {
2034 *(*interface{})(target) = x
2035 } else {
2036 ifaceE2I(dst, x, target)
2038 return Value{dst, target, flagIndir | flag(Interface)}
2041 // Failed.
2042 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
2045 // Convert returns the value v converted to type t.
2046 // If the usual Go conversion rules do not allow conversion
2047 // of the value v to type t, Convert panics.
2048 func (v Value) Convert(t Type) Value {
2049 if v.flag&flagMethod != 0 {
2050 v = makeMethodValue("Convert", v)
2052 op := convertOp(t.common(), v.typ)
2053 if op == nil {
2054 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
2056 return op(v, t)
2059 // convertOp returns the function to convert a value of type src
2060 // to a value of type dst. If the conversion is illegal, convertOp returns nil.
2061 func convertOp(dst, src *rtype) func(Value, Type) Value {
2062 switch src.Kind() {
2063 case Int, Int8, Int16, Int32, Int64:
2064 switch dst.Kind() {
2065 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2066 return cvtInt
2067 case Float32, Float64:
2068 return cvtIntFloat
2069 case String:
2070 return cvtIntString
2073 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2074 switch dst.Kind() {
2075 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2076 return cvtUint
2077 case Float32, Float64:
2078 return cvtUintFloat
2079 case String:
2080 return cvtUintString
2083 case Float32, Float64:
2084 switch dst.Kind() {
2085 case Int, Int8, Int16, Int32, Int64:
2086 return cvtFloatInt
2087 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2088 return cvtFloatUint
2089 case Float32, Float64:
2090 return cvtFloat
2093 case Complex64, Complex128:
2094 switch dst.Kind() {
2095 case Complex64, Complex128:
2096 return cvtComplex
2099 case String:
2100 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
2101 switch dst.Elem().Kind() {
2102 case Uint8:
2103 return cvtStringBytes
2104 case Int32:
2105 return cvtStringRunes
2109 case Slice:
2110 if dst.Kind() == String && src.Elem().PkgPath() == "" {
2111 switch src.Elem().Kind() {
2112 case Uint8:
2113 return cvtBytesString
2114 case Int32:
2115 return cvtRunesString
2120 // dst and src have same underlying type.
2121 if haveIdenticalUnderlyingType(dst, src, false) {
2122 return cvtDirect
2125 // dst and src are unnamed pointer types with same underlying base type.
2126 if dst.Kind() == Ptr && dst.Name() == "" &&
2127 src.Kind() == Ptr && src.Name() == "" &&
2128 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false) {
2129 return cvtDirect
2132 if implements(dst, src) {
2133 if src.Kind() == Interface {
2134 return cvtI2I
2136 return cvtT2I
2139 return nil
2142 // makeInt returns a Value of type t equal to bits (possibly truncated),
2143 // where t is a signed or unsigned int type.
2144 func makeInt(f flag, bits uint64, t Type) Value {
2145 typ := t.common()
2146 ptr := unsafe_New(typ)
2147 switch typ.size {
2148 case 1:
2149 *(*uint8)(ptr) = uint8(bits)
2150 case 2:
2151 *(*uint16)(ptr) = uint16(bits)
2152 case 4:
2153 *(*uint32)(ptr) = uint32(bits)
2154 case 8:
2155 *(*uint64)(ptr) = bits
2157 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2160 // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2161 // where t is a float32 or float64 type.
2162 func makeFloat(f flag, v float64, t Type) Value {
2163 typ := t.common()
2164 ptr := unsafe_New(typ)
2165 switch typ.size {
2166 case 4:
2167 *(*float32)(ptr) = float32(v)
2168 case 8:
2169 *(*float64)(ptr) = v
2171 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2174 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2175 // where t is a complex64 or complex128 type.
2176 func makeComplex(f flag, v complex128, t Type) Value {
2177 typ := t.common()
2178 ptr := unsafe_New(typ)
2179 switch typ.size {
2180 case 8:
2181 *(*complex64)(ptr) = complex64(v)
2182 case 16:
2183 *(*complex128)(ptr) = v
2185 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2188 func makeString(f flag, v string, t Type) Value {
2189 ret := New(t).Elem()
2190 ret.SetString(v)
2191 ret.flag = ret.flag&^flagAddr | f
2192 return ret
2195 func makeBytes(f flag, v []byte, t Type) Value {
2196 ret := New(t).Elem()
2197 ret.SetBytes(v)
2198 ret.flag = ret.flag&^flagAddr | f
2199 return ret
2202 func makeRunes(f flag, v []rune, t Type) Value {
2203 ret := New(t).Elem()
2204 ret.setRunes(v)
2205 ret.flag = ret.flag&^flagAddr | f
2206 return ret
2209 // These conversion functions are returned by convertOp
2210 // for classes of conversions. For example, the first function, cvtInt,
2211 // takes any value v of signed int type and returns the value converted
2212 // to type t, where t is any signed or unsigned int type.
2214 // convertOp: intXX -> [u]intXX
2215 func cvtInt(v Value, t Type) Value {
2216 return makeInt(v.flag&flagRO, uint64(v.Int()), t)
2219 // convertOp: uintXX -> [u]intXX
2220 func cvtUint(v Value, t Type) Value {
2221 return makeInt(v.flag&flagRO, v.Uint(), t)
2224 // convertOp: floatXX -> intXX
2225 func cvtFloatInt(v Value, t Type) Value {
2226 return makeInt(v.flag&flagRO, uint64(int64(v.Float())), t)
2229 // convertOp: floatXX -> uintXX
2230 func cvtFloatUint(v Value, t Type) Value {
2231 return makeInt(v.flag&flagRO, uint64(v.Float()), t)
2234 // convertOp: intXX -> floatXX
2235 func cvtIntFloat(v Value, t Type) Value {
2236 return makeFloat(v.flag&flagRO, float64(v.Int()), t)
2239 // convertOp: uintXX -> floatXX
2240 func cvtUintFloat(v Value, t Type) Value {
2241 return makeFloat(v.flag&flagRO, float64(v.Uint()), t)
2244 // convertOp: floatXX -> floatXX
2245 func cvtFloat(v Value, t Type) Value {
2246 return makeFloat(v.flag&flagRO, v.Float(), t)
2249 // convertOp: complexXX -> complexXX
2250 func cvtComplex(v Value, t Type) Value {
2251 return makeComplex(v.flag&flagRO, v.Complex(), t)
2254 // convertOp: intXX -> string
2255 func cvtIntString(v Value, t Type) Value {
2256 return makeString(v.flag&flagRO, string(v.Int()), t)
2259 // convertOp: uintXX -> string
2260 func cvtUintString(v Value, t Type) Value {
2261 return makeString(v.flag&flagRO, string(v.Uint()), t)
2264 // convertOp: []byte -> string
2265 func cvtBytesString(v Value, t Type) Value {
2266 return makeString(v.flag&flagRO, string(v.Bytes()), t)
2269 // convertOp: string -> []byte
2270 func cvtStringBytes(v Value, t Type) Value {
2271 return makeBytes(v.flag&flagRO, []byte(v.String()), t)
2274 // convertOp: []rune -> string
2275 func cvtRunesString(v Value, t Type) Value {
2276 return makeString(v.flag&flagRO, string(v.runes()), t)
2279 // convertOp: string -> []rune
2280 func cvtStringRunes(v Value, t Type) Value {
2281 return makeRunes(v.flag&flagRO, []rune(v.String()), t)
2284 // convertOp: direct copy
2285 func cvtDirect(v Value, typ Type) Value {
2286 f := v.flag
2287 t := typ.common()
2288 ptr := v.ptr
2289 if f&flagAddr != 0 {
2290 // indirect, mutable word - make a copy
2291 c := unsafe_New(t)
2292 typedmemmove(t, c, ptr)
2293 ptr = c
2294 f &^= flagAddr
2296 return Value{t, ptr, v.flag&flagRO | f} // v.flag&flagRO|f == f?
2299 // convertOp: concrete -> interface
2300 func cvtT2I(v Value, typ Type) Value {
2301 target := unsafe_New(typ.common())
2302 x := valueInterface(v, false)
2303 if typ.NumMethod() == 0 {
2304 *(*interface{})(target) = x
2305 } else {
2306 ifaceE2I(typ.(*rtype), x, target)
2308 return Value{typ.common(), target, v.flag&flagRO | flagIndir | flag(Interface)}
2311 // convertOp: interface -> interface
2312 func cvtI2I(v Value, typ Type) Value {
2313 if v.IsNil() {
2314 ret := Zero(typ)
2315 ret.flag |= v.flag & flagRO
2316 return ret
2318 return cvtT2I(v.Elem(), typ)
2321 // implemented in ../runtime
2322 func chancap(ch unsafe.Pointer) int
2323 func chanclose(ch unsafe.Pointer)
2324 func chanlen(ch unsafe.Pointer) int
2326 // Note: some of the noescape annotations below are technically a lie,
2327 // but safe in the context of this package. Functions like chansend
2328 // and mapassign don't escape the referent, but may escape anything
2329 // the referent points to (they do shallow copies of the referent).
2330 // It is safe in this package because the referent may only point
2331 // to something a Value may point to, and that is always in the heap
2332 // (due to the escapes() call in ValueOf).
2334 //go:noescape
2335 func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
2337 //go:noescape
2338 func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
2340 func makechan(typ *rtype, size uint64) (ch unsafe.Pointer)
2341 func makemap(t *rtype, cap int) (m unsafe.Pointer)
2343 //go:noescape
2344 func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
2346 //go:noescape
2347 func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
2349 //go:noescape
2350 func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
2352 // m escapes into the return value, but the caller of mapiterinit
2353 // doesn't let the return value escape.
2354 //go:noescape
2355 func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
2357 //go:noescape
2358 func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
2360 //go:noescape
2361 func mapiternext(it unsafe.Pointer)
2363 //go:noescape
2364 func maplen(m unsafe.Pointer) int
2365 func call(typ *rtype, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer)
2367 func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
2369 // typedmemmove copies a value of type t to dst from src.
2370 //go:noescape
2371 func typedmemmove(t *rtype, dst, src unsafe.Pointer)
2373 // typedslicecopy copies a slice of elemType values from src to dst,
2374 // returning the number of elements copied.
2375 //go:noescape
2376 func typedslicecopy(elemType *rtype, dst, src sliceHeader) int
2378 //go:noescape
2379 //extern memmove
2380 func memmove(adst, asrc unsafe.Pointer, n uintptr)
2382 // Dummy annotation marking that the value x escapes,
2383 // for use in cases where the reflect code is so clever that
2384 // the compiler cannot follow.
2385 func escapes(x interface{}) {
2386 if dummy.b {
2387 dummy.x = x
2391 var dummy struct {
2392 b bool
2393 x interface{}