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