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 := 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, t *rtype, 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 = 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 = 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.anon() {
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:
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	if !ifaceIndir(typ) {
939		return Value{typ, *(*unsafe.Pointer)(e), fl}
940	}
941	// Copy result so future changes to the map
942	// won't change the underlying value.
943	c := unsafe_New(typ)
944	typedmemmove(typ, c, e)
945	return Value{typ, c, fl | flagIndir}
946}
947
948// MapKeys returns a slice containing all the keys present in the map,
949// in unspecified order.
950// It panics if v's Kind is not Map.
951// It returns an empty slice if v represents a nil map.
952func (v Value) MapKeys() []Value {
953	v.mustBe(Map)
954	tt := (*mapType)(unsafe.Pointer(v.typ))
955	keyType := tt.key
956
957	fl := v.flag.ro() | flag(keyType.Kind())
958
959	m := v.pointer()
960	mlen := int(0)
961	if m != nil {
962		mlen = maplen(m)
963	}
964	it := mapiterinit(v.typ, m)
965	a := make([]Value, mlen)
966	var i int
967	for i = 0; i < len(a); i++ {
968		key := mapiterkey(it)
969		if key == nil {
970			// Someone deleted an entry from the map since we
971			// called maplen above. It's a data race, but nothing
972			// we can do about it.
973			break
974		}
975		if ifaceIndir(keyType) {
976			// Copy result so future changes to the map
977			// won't change the underlying value.
978			c := unsafe_New(keyType)
979			typedmemmove(keyType, c, key)
980			a[i] = Value{keyType, c, fl | flagIndir}
981		} else {
982			a[i] = Value{keyType, *(*unsafe.Pointer)(key), fl}
983		}
984		mapiternext(it)
985	}
986	return a[:i]
987}
988
989// Method returns a function value corresponding to v's i'th method.
990// The arguments to a Call on the returned function should not include
991// a receiver; the returned function will always use v as the receiver.
992// Method panics if i is out of range or if v is a nil interface value.
993func (v Value) Method(i int) Value {
994	if v.typ == nil {
995		panic(&ValueError{"reflect.Value.Method", Invalid})
996	}
997	if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) {
998		panic("reflect: Method index out of range")
999	}
1000	if v.typ.Kind() == Interface && v.IsNil() {
1001		panic("reflect: Method on nil interface value")
1002	}
1003	fl := v.flag & (flagStickyRO | flagIndir) // Clear flagEmbedRO
1004	fl |= flag(Func)
1005	fl |= flag(i)<<flagMethodShift | flagMethod
1006	return Value{v.typ, v.ptr, fl}
1007}
1008
1009// NumMethod returns the number of exported methods in the value's method set.
1010func (v Value) NumMethod() int {
1011	if v.typ == nil {
1012		panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1013	}
1014	if v.flag&flagMethod != 0 {
1015		return 0
1016	}
1017	return v.typ.NumMethod()
1018}
1019
1020// MethodByName returns a function value corresponding to the method
1021// of v with the given name.
1022// The arguments to a Call on the returned function should not include
1023// a receiver; the returned function will always use v as the receiver.
1024// It returns the zero Value if no method was found.
1025func (v Value) MethodByName(name string) Value {
1026	if v.typ == nil {
1027		panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1028	}
1029	if v.flag&flagMethod != 0 {
1030		return Value{}
1031	}
1032	m, ok := v.typ.MethodByName(name)
1033	if !ok {
1034		return Value{}
1035	}
1036	return v.Method(m.Index)
1037}
1038
1039// NumField returns the number of fields in the struct v.
1040// It panics if v's Kind is not Struct.
1041func (v Value) NumField() int {
1042	v.mustBe(Struct)
1043	tt := (*structType)(unsafe.Pointer(v.typ))
1044	return len(tt.fields)
1045}
1046
1047// OverflowComplex reports whether the complex128 x cannot be represented by v's type.
1048// It panics if v's Kind is not Complex64 or Complex128.
1049func (v Value) OverflowComplex(x complex128) bool {
1050	k := v.kind()
1051	switch k {
1052	case Complex64:
1053		return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1054	case Complex128:
1055		return false
1056	}
1057	panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
1058}
1059
1060// OverflowFloat reports whether the float64 x cannot be represented by v's type.
1061// It panics if v's Kind is not Float32 or Float64.
1062func (v Value) OverflowFloat(x float64) bool {
1063	k := v.kind()
1064	switch k {
1065	case Float32:
1066		return overflowFloat32(x)
1067	case Float64:
1068		return false
1069	}
1070	panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
1071}
1072
1073func overflowFloat32(x float64) bool {
1074	if x < 0 {
1075		x = -x
1076	}
1077	return math.MaxFloat32 < x && x <= math.MaxFloat64
1078}
1079
1080// OverflowInt reports whether the int64 x cannot be represented by v's type.
1081// It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
1082func (v Value) OverflowInt(x int64) bool {
1083	k := v.kind()
1084	switch k {
1085	case Int, Int8, Int16, Int32, Int64:
1086		bitSize := v.typ.size * 8
1087		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1088		return x != trunc
1089	}
1090	panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
1091}
1092
1093// OverflowUint reports whether the uint64 x cannot be represented by v's type.
1094// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1095func (v Value) OverflowUint(x uint64) bool {
1096	k := v.kind()
1097	switch k {
1098	case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1099		bitSize := v.typ.size * 8
1100		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1101		return x != trunc
1102	}
1103	panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
1104}
1105
1106// Pointer returns v's value as a uintptr.
1107// It returns uintptr instead of unsafe.Pointer so that
1108// code using reflect cannot obtain unsafe.Pointers
1109// without importing the unsafe package explicitly.
1110// It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1111//
1112// If v's Kind is Func, the returned pointer is an underlying
1113// code pointer, but not necessarily enough to identify a
1114// single function uniquely. The only guarantee is that the
1115// result is zero if and only if v is a nil func Value.
1116//
1117// If v's Kind is Slice, the returned pointer is to the first
1118// element of the slice. If the slice is nil the returned value
1119// is 0.  If the slice is empty but non-nil the return value is non-zero.
1120func (v Value) Pointer() uintptr {
1121	// TODO: deprecate
1122	k := v.kind()
1123	switch k {
1124	case Chan, Map, Ptr, UnsafePointer:
1125		return uintptr(v.pointer())
1126	case Func:
1127		p := v.pointer()
1128		// Non-nil func value points at data block.
1129		// First word of data block is actual code.
1130		if p != nil {
1131			p = *(*unsafe.Pointer)(p)
1132		}
1133		return uintptr(p)
1134
1135	case Slice:
1136		return (*SliceHeader)(v.ptr).Data
1137	}
1138	panic(&ValueError{"reflect.Value.Pointer", v.kind()})
1139}
1140
1141// Recv receives and returns a value from the channel v.
1142// It panics if v's Kind is not Chan.
1143// The receive blocks until a value is ready.
1144// The boolean value ok is true if the value x corresponds to a send
1145// on the channel, false if it is a zero value received because the channel is closed.
1146func (v Value) Recv() (x Value, ok bool) {
1147	v.mustBe(Chan)
1148	v.mustBeExported()
1149	return v.recv(false)
1150}
1151
1152// internal recv, possibly non-blocking (nb).
1153// v is known to be a channel.
1154func (v Value) recv(nb bool) (val Value, ok bool) {
1155	tt := (*chanType)(unsafe.Pointer(v.typ))
1156	if ChanDir(tt.dir)&RecvDir == 0 {
1157		panic("reflect: recv on send-only channel")
1158	}
1159	t := tt.elem
1160	val = Value{t, nil, flag(t.Kind())}
1161	var p unsafe.Pointer
1162	if ifaceIndir(t) {
1163		p = unsafe_New(t)
1164		val.ptr = p
1165		val.flag |= flagIndir
1166	} else {
1167		p = unsafe.Pointer(&val.ptr)
1168	}
1169	selected, ok := chanrecv(v.pointer(), nb, p)
1170	if !selected {
1171		val = Value{}
1172	}
1173	return
1174}
1175
1176// Send sends x on the channel v.
1177// It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1178// As in Go, x's value must be assignable to the channel's element type.
1179func (v Value) Send(x Value) {
1180	v.mustBe(Chan)
1181	v.mustBeExported()
1182	v.send(x, false)
1183}
1184
1185// internal send, possibly non-blocking.
1186// v is known to be a channel.
1187func (v Value) send(x Value, nb bool) (selected bool) {
1188	tt := (*chanType)(unsafe.Pointer(v.typ))
1189	if ChanDir(tt.dir)&SendDir == 0 {
1190		panic("reflect: send on recv-only channel")
1191	}
1192	x.mustBeExported()
1193	x = x.assignTo("reflect.Value.Send", tt.elem, nil)
1194	var p unsafe.Pointer
1195	if x.flag&flagIndir != 0 {
1196		p = x.ptr
1197	} else {
1198		p = unsafe.Pointer(&x.ptr)
1199	}
1200	return chansend(v.pointer(), p, nb)
1201}
1202
1203// Set assigns x to the value v.
1204// It panics if CanSet returns false.
1205// As in Go, x's value must be assignable to v's type.
1206func (v Value) Set(x Value) {
1207	v.mustBeAssignable()
1208	x.mustBeExported() // do not let unexported x leak
1209	var target unsafe.Pointer
1210	if v.kind() == Interface {
1211		target = v.ptr
1212	}
1213	x = x.assignTo("reflect.Set", v.typ, target)
1214	if x.flag&flagIndir != 0 {
1215		typedmemmove(v.typ, v.ptr, x.ptr)
1216	} else {
1217		*(*unsafe.Pointer)(v.ptr) = x.ptr
1218	}
1219}
1220
1221// SetBool sets v's underlying value.
1222// It panics if v's Kind is not Bool or if CanSet() is false.
1223func (v Value) SetBool(x bool) {
1224	v.mustBeAssignable()
1225	v.mustBe(Bool)
1226	*(*bool)(v.ptr) = x
1227}
1228
1229// SetBytes sets v's underlying value.
1230// It panics if v's underlying value is not a slice of bytes.
1231func (v Value) SetBytes(x []byte) {
1232	v.mustBeAssignable()
1233	v.mustBe(Slice)
1234	if v.typ.Elem().Kind() != Uint8 {
1235		panic("reflect.Value.SetBytes of non-byte slice")
1236	}
1237	*(*[]byte)(v.ptr) = x
1238}
1239
1240// setRunes sets v's underlying value.
1241// It panics if v's underlying value is not a slice of runes (int32s).
1242func (v Value) setRunes(x []rune) {
1243	v.mustBeAssignable()
1244	v.mustBe(Slice)
1245	if v.typ.Elem().Kind() != Int32 {
1246		panic("reflect.Value.setRunes of non-rune slice")
1247	}
1248	*(*[]rune)(v.ptr) = x
1249}
1250
1251// SetComplex sets v's underlying value to x.
1252// It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1253func (v Value) SetComplex(x complex128) {
1254	v.mustBeAssignable()
1255	switch k := v.kind(); k {
1256	default:
1257		panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
1258	case Complex64:
1259		*(*complex64)(v.ptr) = complex64(x)
1260	case Complex128:
1261		*(*complex128)(v.ptr) = x
1262	}
1263}
1264
1265// SetFloat sets v's underlying value to x.
1266// It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1267func (v Value) SetFloat(x float64) {
1268	v.mustBeAssignable()
1269	switch k := v.kind(); k {
1270	default:
1271		panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
1272	case Float32:
1273		*(*float32)(v.ptr) = float32(x)
1274	case Float64:
1275		*(*float64)(v.ptr) = x
1276	}
1277}
1278
1279// SetInt sets v's underlying value to x.
1280// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1281func (v Value) SetInt(x int64) {
1282	v.mustBeAssignable()
1283	switch k := v.kind(); k {
1284	default:
1285		panic(&ValueError{"reflect.Value.SetInt", v.kind()})
1286	case Int:
1287		*(*int)(v.ptr) = int(x)
1288	case Int8:
1289		*(*int8)(v.ptr) = int8(x)
1290	case Int16:
1291		*(*int16)(v.ptr) = int16(x)
1292	case Int32:
1293		*(*int32)(v.ptr) = int32(x)
1294	case Int64:
1295		*(*int64)(v.ptr) = x
1296	}
1297}
1298
1299// SetLen sets v's length to n.
1300// It panics if v's Kind is not Slice or if n is negative or
1301// greater than the capacity of the slice.
1302func (v Value) SetLen(n int) {
1303	v.mustBeAssignable()
1304	v.mustBe(Slice)
1305	s := (*sliceHeader)(v.ptr)
1306	if uint(n) > uint(s.Cap) {
1307		panic("reflect: slice length out of range in SetLen")
1308	}
1309	s.Len = n
1310}
1311
1312// SetCap sets v's capacity to n.
1313// It panics if v's Kind is not Slice or if n is smaller than the length or
1314// greater than the capacity of the slice.
1315func (v Value) SetCap(n int) {
1316	v.mustBeAssignable()
1317	v.mustBe(Slice)
1318	s := (*sliceHeader)(v.ptr)
1319	if n < s.Len || n > s.Cap {
1320		panic("reflect: slice capacity out of range in SetCap")
1321	}
1322	s.Cap = n
1323}
1324
1325// SetMapIndex sets the value associated with key in the map v to val.
1326// It panics if v's Kind is not Map.
1327// If val is the zero Value, SetMapIndex deletes the key from the map.
1328// Otherwise if v holds a nil map, SetMapIndex will panic.
1329// As in Go, key's value must be assignable to the map's key type,
1330// and val's value must be assignable to the map's value type.
1331func (v Value) SetMapIndex(key, val Value) {
1332	v.mustBe(Map)
1333	v.mustBeExported()
1334	key.mustBeExported()
1335	tt := (*mapType)(unsafe.Pointer(v.typ))
1336	key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
1337	var k unsafe.Pointer
1338	if key.flag&flagIndir != 0 {
1339		k = key.ptr
1340	} else {
1341		k = unsafe.Pointer(&key.ptr)
1342	}
1343	if val.typ == nil {
1344		mapdelete(v.typ, v.pointer(), k)
1345		return
1346	}
1347	val.mustBeExported()
1348	val = val.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
1349	var e unsafe.Pointer
1350	if val.flag&flagIndir != 0 {
1351		e = val.ptr
1352	} else {
1353		e = unsafe.Pointer(&val.ptr)
1354	}
1355	mapassign(v.typ, v.pointer(), k, e)
1356}
1357
1358// SetUint sets v's underlying value to x.
1359// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1360func (v Value) SetUint(x uint64) {
1361	v.mustBeAssignable()
1362	switch k := v.kind(); k {
1363	default:
1364		panic(&ValueError{"reflect.Value.SetUint", v.kind()})
1365	case Uint:
1366		*(*uint)(v.ptr) = uint(x)
1367	case Uint8:
1368		*(*uint8)(v.ptr) = uint8(x)
1369	case Uint16:
1370		*(*uint16)(v.ptr) = uint16(x)
1371	case Uint32:
1372		*(*uint32)(v.ptr) = uint32(x)
1373	case Uint64:
1374		*(*uint64)(v.ptr) = x
1375	case Uintptr:
1376		*(*uintptr)(v.ptr) = uintptr(x)
1377	}
1378}
1379
1380// SetPointer sets the unsafe.Pointer value v to x.
1381// It panics if v's Kind is not UnsafePointer.
1382func (v Value) SetPointer(x unsafe.Pointer) {
1383	v.mustBeAssignable()
1384	v.mustBe(UnsafePointer)
1385	*(*unsafe.Pointer)(v.ptr) = x
1386}
1387
1388// SetString sets v's underlying value to x.
1389// It panics if v's Kind is not String or if CanSet() is false.
1390func (v Value) SetString(x string) {
1391	v.mustBeAssignable()
1392	v.mustBe(String)
1393	*(*string)(v.ptr) = x
1394}
1395
1396// Slice returns v[i:j].
1397// It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
1398// or if the indexes are out of bounds.
1399func (v Value) Slice(i, j int) Value {
1400	var (
1401		cap  int
1402		typ  *sliceType
1403		base unsafe.Pointer
1404	)
1405	switch kind := v.kind(); kind {
1406	default:
1407		panic(&ValueError{"reflect.Value.Slice", v.kind()})
1408
1409	case Array:
1410		if v.flag&flagAddr == 0 {
1411			panic("reflect.Value.Slice: slice of unaddressable array")
1412		}
1413		tt := (*arrayType)(unsafe.Pointer(v.typ))
1414		cap = int(tt.len)
1415		typ = (*sliceType)(unsafe.Pointer(tt.slice))
1416		base = v.ptr
1417
1418	case Slice:
1419		typ = (*sliceType)(unsafe.Pointer(v.typ))
1420		s := (*sliceHeader)(v.ptr)
1421		base = s.Data
1422		cap = s.Cap
1423
1424	case String:
1425		s := (*stringHeader)(v.ptr)
1426		if i < 0 || j < i || j > s.Len {
1427			panic("reflect.Value.Slice: string slice index out of bounds")
1428		}
1429		var t stringHeader
1430		if i < s.Len {
1431			t = stringHeader{arrayAt(s.Data, i, 1, "i < s.Len"), j - i}
1432		}
1433		return Value{v.typ, unsafe.Pointer(&t), v.flag}
1434	}
1435
1436	if i < 0 || j < i || j > cap {
1437		panic("reflect.Value.Slice: slice index out of bounds")
1438	}
1439
1440	// Declare slice so that gc can see the base pointer in it.
1441	var x []unsafe.Pointer
1442
1443	// Reinterpret as *sliceHeader to edit.
1444	s := (*sliceHeader)(unsafe.Pointer(&x))
1445	s.Len = j - i
1446	s.Cap = cap - i
1447	if cap-i > 0 {
1448		s.Data = arrayAt(base, i, typ.elem.Size(), "i < cap")
1449	} else {
1450		// do not advance pointer, to avoid pointing beyond end of slice
1451		s.Data = base
1452	}
1453
1454	fl := v.flag.ro() | flagIndir | flag(Slice)
1455	return Value{typ.common(), unsafe.Pointer(&x), fl}
1456}
1457
1458// Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
1459// It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
1460// or if the indexes are out of bounds.
1461func (v Value) Slice3(i, j, k int) Value {
1462	var (
1463		cap  int
1464		typ  *sliceType
1465		base unsafe.Pointer
1466	)
1467	switch kind := v.kind(); kind {
1468	default:
1469		panic(&ValueError{"reflect.Value.Slice3", v.kind()})
1470
1471	case Array:
1472		if v.flag&flagAddr == 0 {
1473			panic("reflect.Value.Slice3: slice of unaddressable array")
1474		}
1475		tt := (*arrayType)(unsafe.Pointer(v.typ))
1476		cap = int(tt.len)
1477		typ = (*sliceType)(unsafe.Pointer(tt.slice))
1478		base = v.ptr
1479
1480	case Slice:
1481		typ = (*sliceType)(unsafe.Pointer(v.typ))
1482		s := (*sliceHeader)(v.ptr)
1483		base = s.Data
1484		cap = s.Cap
1485	}
1486
1487	if i < 0 || j < i || k < j || k > cap {
1488		panic("reflect.Value.Slice3: slice index out of bounds")
1489	}
1490
1491	// Declare slice so that the garbage collector
1492	// can see the base pointer in it.
1493	var x []unsafe.Pointer
1494
1495	// Reinterpret as *sliceHeader to edit.
1496	s := (*sliceHeader)(unsafe.Pointer(&x))
1497	s.Len = j - i
1498	s.Cap = k - i
1499	if k-i > 0 {
1500		s.Data = arrayAt(base, i, typ.elem.Size(), "i < k <= cap")
1501	} else {
1502		// do not advance pointer, to avoid pointing beyond end of slice
1503		s.Data = base
1504	}
1505
1506	fl := v.flag.ro() | flagIndir | flag(Slice)
1507	return Value{typ.common(), unsafe.Pointer(&x), fl}
1508}
1509
1510// String returns the string v's underlying value, as a string.
1511// String is a special case because of Go's String method convention.
1512// Unlike the other getters, it does not panic if v's Kind is not String.
1513// Instead, it returns a string of the form "<T value>" where T is v's type.
1514// The fmt package treats Values specially. It does not call their String
1515// method implicitly but instead prints the concrete values they hold.
1516func (v Value) String() string {
1517	switch k := v.kind(); k {
1518	case Invalid:
1519		return "<invalid Value>"
1520	case String:
1521		return *(*string)(v.ptr)
1522	}
1523	// If you call String on a reflect.Value of other type, it's better to
1524	// print something than to panic. Useful in debugging.
1525	return "<" + v.Type().String() + " Value>"
1526}
1527
1528// TryRecv attempts to receive a value from the channel v but will not block.
1529// It panics if v's Kind is not Chan.
1530// If the receive delivers a value, x is the transferred value and ok is true.
1531// If the receive cannot finish without blocking, x is the zero Value and ok is false.
1532// If the channel is closed, x is the zero value for the channel's element type and ok is false.
1533func (v Value) TryRecv() (x Value, ok bool) {
1534	v.mustBe(Chan)
1535	v.mustBeExported()
1536	return v.recv(true)
1537}
1538
1539// TrySend attempts to send x on the channel v but will not block.
1540// It panics if v's Kind is not Chan.
1541// It reports whether the value was sent.
1542// As in Go, x's value must be assignable to the channel's element type.
1543func (v Value) TrySend(x Value) bool {
1544	v.mustBe(Chan)
1545	v.mustBeExported()
1546	return v.send(x, true)
1547}
1548
1549// Type returns v's type.
1550func (v Value) Type() Type {
1551	f := v.flag
1552	if f == 0 {
1553		panic(&ValueError{"reflect.Value.Type", Invalid})
1554	}
1555	if f&flagMethod == 0 {
1556		// Easy case
1557		return toType(v.typ)
1558	}
1559
1560	// Method value.
1561	// v.typ describes the receiver, not the method type.
1562	i := int(v.flag) >> flagMethodShift
1563	if v.typ.Kind() == Interface {
1564		// Method on interface.
1565		tt := (*interfaceType)(unsafe.Pointer(v.typ))
1566		if uint(i) >= uint(len(tt.methods)) {
1567			panic("reflect: internal error: invalid method index")
1568		}
1569		m := &tt.methods[i]
1570		return toType(m.typ)
1571	}
1572	// Method on concrete type.
1573	ms := v.typ.exportedMethods()
1574	if uint(i) >= uint(len(ms)) {
1575		panic("reflect: internal error: invalid method index")
1576	}
1577	m := ms[i]
1578	return toType(m.mtyp)
1579}
1580
1581// Uint returns v's underlying value, as a uint64.
1582// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1583func (v Value) Uint() uint64 {
1584	k := v.kind()
1585	p := v.ptr
1586	switch k {
1587	case Uint:
1588		return uint64(*(*uint)(p))
1589	case Uint8:
1590		return uint64(*(*uint8)(p))
1591	case Uint16:
1592		return uint64(*(*uint16)(p))
1593	case Uint32:
1594		return uint64(*(*uint32)(p))
1595	case Uint64:
1596		return *(*uint64)(p)
1597	case Uintptr:
1598		return uint64(*(*uintptr)(p))
1599	}
1600	panic(&ValueError{"reflect.Value.Uint", v.kind()})
1601}
1602
1603// UnsafeAddr returns a pointer to v's data.
1604// It is for advanced clients that also import the "unsafe" package.
1605// It panics if v is not addressable.
1606func (v Value) UnsafeAddr() uintptr {
1607	// TODO: deprecate
1608	if v.typ == nil {
1609		panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
1610	}
1611	if v.flag&flagAddr == 0 {
1612		panic("reflect.Value.UnsafeAddr of unaddressable value")
1613	}
1614	return uintptr(v.ptr)
1615}
1616
1617// StringHeader is the runtime representation of a string.
1618// It cannot be used safely or portably and its representation may
1619// change in a later release.
1620// Moreover, the Data field is not sufficient to guarantee the data
1621// it references will not be garbage collected, so programs must keep
1622// a separate, correctly typed pointer to the underlying data.
1623type StringHeader struct {
1624	Data uintptr
1625	Len  int
1626}
1627
1628// stringHeader is a safe version of StringHeader used within this package.
1629type stringHeader struct {
1630	Data unsafe.Pointer
1631	Len  int
1632}
1633
1634// SliceHeader is the runtime representation of a slice.
1635// It cannot be used safely or portably and its representation may
1636// change in a later release.
1637// Moreover, the Data field is not sufficient to guarantee the data
1638// it references will not be garbage collected, so programs must keep
1639// a separate, correctly typed pointer to the underlying data.
1640type SliceHeader struct {
1641	Data uintptr
1642	Len  int
1643	Cap  int
1644}
1645
1646// sliceHeader is a safe version of SliceHeader used within this package.
1647type sliceHeader struct {
1648	Data unsafe.Pointer
1649	Len  int
1650	Cap  int
1651}
1652
1653func typesMustMatch(what string, t1, t2 Type) {
1654	if t1 != t2 {
1655		panic(what + ": " + t1.String() + " != " + t2.String())
1656	}
1657}
1658
1659// arrayAt returns the i-th element of p,
1660// an array whose elements are eltSize bytes wide.
1661// The array pointed at by p must have at least i+1 elements:
1662// it is invalid (but impossible to check here) to pass i >= len,
1663// because then the result will point outside the array.
1664// whySafe must explain why i < len. (Passing "i < len" is fine;
1665// the benefit is to surface this assumption at the call site.)
1666func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
1667	return add(p, uintptr(i)*eltSize, "i < len")
1668}
1669
1670// grow grows the slice s so that it can hold extra more values, allocating
1671// more capacity if needed. It also returns the old and new slice lengths.
1672func grow(s Value, extra int) (Value, int, int) {
1673	i0 := s.Len()
1674	i1 := i0 + extra
1675	if i1 < i0 {
1676		panic("reflect.Append: slice overflow")
1677	}
1678	m := s.Cap()
1679	if i1 <= m {
1680		return s.Slice(0, i1), i0, i1
1681	}
1682	if m == 0 {
1683		m = extra
1684	} else {
1685		for m < i1 {
1686			if i0 < 1024 {
1687				m += m
1688			} else {
1689				m += m / 4
1690			}
1691		}
1692	}
1693	t := MakeSlice(s.Type(), i1, m)
1694	Copy(t, s)
1695	return t, i0, i1
1696}
1697
1698// Append appends the values x to a slice s and returns the resulting slice.
1699// As in Go, each x's value must be assignable to the slice's element type.
1700func Append(s Value, x ...Value) Value {
1701	s.mustBe(Slice)
1702	s, i0, i1 := grow(s, len(x))
1703	for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
1704		s.Index(i).Set(x[j])
1705	}
1706	return s
1707}
1708
1709// AppendSlice appends a slice t to a slice s and returns the resulting slice.
1710// The slices s and t must have the same element type.
1711func AppendSlice(s, t Value) Value {
1712	s.mustBe(Slice)
1713	t.mustBe(Slice)
1714	typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
1715	s, i0, i1 := grow(s, t.Len())
1716	Copy(s.Slice(i0, i1), t)
1717	return s
1718}
1719
1720// Copy copies the contents of src into dst until either
1721// dst has been filled or src has been exhausted.
1722// It returns the number of elements copied.
1723// Dst and src each must have kind Slice or Array, and
1724// dst and src must have the same element type.
1725//
1726// As a special case, src can have kind String if the element type of dst is kind Uint8.
1727func Copy(dst, src Value) int {
1728	dk := dst.kind()
1729	if dk != Array && dk != Slice {
1730		panic(&ValueError{"reflect.Copy", dk})
1731	}
1732	if dk == Array {
1733		dst.mustBeAssignable()
1734	}
1735	dst.mustBeExported()
1736
1737	sk := src.kind()
1738	var stringCopy bool
1739	if sk != Array && sk != Slice {
1740		stringCopy = sk == String && dst.typ.Elem().Kind() == Uint8
1741		if !stringCopy {
1742			panic(&ValueError{"reflect.Copy", sk})
1743		}
1744	}
1745	src.mustBeExported()
1746
1747	de := dst.typ.Elem()
1748	if !stringCopy {
1749		se := src.typ.Elem()
1750		typesMustMatch("reflect.Copy", de, se)
1751	}
1752
1753	var ds, ss sliceHeader
1754	if dk == Array {
1755		ds.Data = dst.ptr
1756		ds.Len = dst.Len()
1757		ds.Cap = ds.Len
1758	} else {
1759		ds = *(*sliceHeader)(dst.ptr)
1760	}
1761	if sk == Array {
1762		ss.Data = src.ptr
1763		ss.Len = src.Len()
1764		ss.Cap = ss.Len
1765	} else if sk == Slice {
1766		ss = *(*sliceHeader)(src.ptr)
1767	} else {
1768		sh := *(*stringHeader)(src.ptr)
1769		ss.Data = sh.Data
1770		ss.Len = sh.Len
1771		ss.Cap = sh.Len
1772	}
1773
1774	return typedslicecopy(de.common(), ds, ss)
1775}
1776
1777// A runtimeSelect is a single case passed to rselect.
1778// This must match ../runtime/select.go:/runtimeSelect
1779type runtimeSelect struct {
1780	dir SelectDir      // SelectSend, SelectRecv or SelectDefault
1781	typ *rtype         // channel type
1782	ch  unsafe.Pointer // channel
1783	val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
1784}
1785
1786// rselect runs a select. It returns the index of the chosen case.
1787// If the case was a receive, val is filled in with the received value.
1788// The conventional OK bool indicates whether the receive corresponds
1789// to a sent value.
1790//go:noescape
1791func rselect([]runtimeSelect) (chosen int, recvOK bool)
1792
1793// A SelectDir describes the communication direction of a select case.
1794type SelectDir int
1795
1796// NOTE: These values must match ../runtime/select.go:/selectDir.
1797
1798const (
1799	_             SelectDir = iota
1800	SelectSend              // case Chan <- Send
1801	SelectRecv              // case <-Chan:
1802	SelectDefault           // default
1803)
1804
1805// A SelectCase describes a single case in a select operation.
1806// The kind of case depends on Dir, the communication direction.
1807//
1808// If Dir is SelectDefault, the case represents a default case.
1809// Chan and Send must be zero Values.
1810//
1811// If Dir is SelectSend, the case represents a send operation.
1812// Normally Chan's underlying value must be a channel, and Send's underlying value must be
1813// assignable to the channel's element type. As a special case, if Chan is a zero Value,
1814// then the case is ignored, and the field Send will also be ignored and may be either zero
1815// or non-zero.
1816//
1817// If Dir is SelectRecv, the case represents a receive operation.
1818// Normally Chan's underlying value must be a channel and Send must be a zero Value.
1819// If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
1820// When a receive operation is selected, the received Value is returned by Select.
1821//
1822type SelectCase struct {
1823	Dir  SelectDir // direction of case
1824	Chan Value     // channel to use (for send or receive)
1825	Send Value     // value to send (for send)
1826}
1827
1828// Select executes a select operation described by the list of cases.
1829// Like the Go select statement, it blocks until at least one of the cases
1830// can proceed, makes a uniform pseudo-random choice,
1831// and then executes that case. It returns the index of the chosen case
1832// and, if that case was a receive operation, the value received and a
1833// boolean indicating whether the value corresponds to a send on the channel
1834// (as opposed to a zero value received because the channel is closed).
1835func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
1836	// NOTE: Do not trust that caller is not modifying cases data underfoot.
1837	// The range is safe because the caller cannot modify our copy of the len
1838	// and each iteration makes its own copy of the value c.
1839	runcases := make([]runtimeSelect, len(cases))
1840	haveDefault := false
1841	for i, c := range cases {
1842		rc := &runcases[i]
1843		rc.dir = c.Dir
1844		switch c.Dir {
1845		default:
1846			panic("reflect.Select: invalid Dir")
1847
1848		case SelectDefault: // default
1849			if haveDefault {
1850				panic("reflect.Select: multiple default cases")
1851			}
1852			haveDefault = true
1853			if c.Chan.IsValid() {
1854				panic("reflect.Select: default case has Chan value")
1855			}
1856			if c.Send.IsValid() {
1857				panic("reflect.Select: default case has Send value")
1858			}
1859
1860		case SelectSend:
1861			ch := c.Chan
1862			if !ch.IsValid() {
1863				break
1864			}
1865			ch.mustBe(Chan)
1866			ch.mustBeExported()
1867			tt := (*chanType)(unsafe.Pointer(ch.typ))
1868			if ChanDir(tt.dir)&SendDir == 0 {
1869				panic("reflect.Select: SendDir case using recv-only channel")
1870			}
1871			rc.ch = ch.pointer()
1872			rc.typ = &tt.rtype
1873			v := c.Send
1874			if !v.IsValid() {
1875				panic("reflect.Select: SendDir case missing Send value")
1876			}
1877			v.mustBeExported()
1878			v = v.assignTo("reflect.Select", tt.elem, nil)
1879			if v.flag&flagIndir != 0 {
1880				rc.val = v.ptr
1881			} else {
1882				rc.val = unsafe.Pointer(&v.ptr)
1883			}
1884
1885		case SelectRecv:
1886			if c.Send.IsValid() {
1887				panic("reflect.Select: RecvDir case has Send value")
1888			}
1889			ch := c.Chan
1890			if !ch.IsValid() {
1891				break
1892			}
1893			ch.mustBe(Chan)
1894			ch.mustBeExported()
1895			tt := (*chanType)(unsafe.Pointer(ch.typ))
1896			if ChanDir(tt.dir)&RecvDir == 0 {
1897				panic("reflect.Select: RecvDir case using send-only channel")
1898			}
1899			rc.ch = ch.pointer()
1900			rc.typ = &tt.rtype
1901			rc.val = unsafe_New(tt.elem)
1902		}
1903	}
1904
1905	chosen, recvOK = rselect(runcases)
1906	if runcases[chosen].dir == SelectRecv {
1907		tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
1908		t := tt.elem
1909		p := runcases[chosen].val
1910		fl := flag(t.Kind())
1911		if ifaceIndir(t) {
1912			recv = Value{t, p, fl | flagIndir}
1913		} else {
1914			recv = Value{t, *(*unsafe.Pointer)(p), fl}
1915		}
1916	}
1917	return chosen, recv, recvOK
1918}
1919
1920/*
1921 * constructors
1922 */
1923
1924// implemented in package runtime
1925func unsafe_New(*rtype) unsafe.Pointer
1926func unsafe_NewArray(*rtype, int) unsafe.Pointer
1927
1928// MakeSlice creates a new zero-initialized slice value
1929// for the specified slice type, length, and capacity.
1930func MakeSlice(typ Type, len, cap int) Value {
1931	if typ.Kind() != Slice {
1932		panic("reflect.MakeSlice of non-slice type")
1933	}
1934	if len < 0 {
1935		panic("reflect.MakeSlice: negative len")
1936	}
1937	if cap < 0 {
1938		panic("reflect.MakeSlice: negative cap")
1939	}
1940	if len > cap {
1941		panic("reflect.MakeSlice: len > cap")
1942	}
1943
1944	s := sliceHeader{unsafe_NewArray(typ.Elem().(*rtype), cap), len, cap}
1945	return Value{typ.common(), unsafe.Pointer(&s), flagIndir | flag(Slice)}
1946}
1947
1948// MakeChan creates a new channel with the specified type and buffer size.
1949func MakeChan(typ Type, buffer int) Value {
1950	if typ.Kind() != Chan {
1951		panic("reflect.MakeChan of non-chan type")
1952	}
1953	if buffer < 0 {
1954		panic("reflect.MakeChan: negative buffer size")
1955	}
1956	if typ.ChanDir() != BothDir {
1957		panic("reflect.MakeChan: unidirectional channel type")
1958	}
1959	ch := makechan(typ.(*rtype), buffer)
1960	return Value{typ.common(), unsafe.Pointer(&ch), flag(Chan) | flagIndir}
1961}
1962
1963// MakeMap creates a new map with the specified type.
1964func MakeMap(typ Type) Value {
1965	return MakeMapWithSize(typ, 0)
1966}
1967
1968// MakeMapWithSize creates a new map with the specified type
1969// and initial space for approximately n elements.
1970func MakeMapWithSize(typ Type, n int) Value {
1971	if typ.Kind() != Map {
1972		panic("reflect.MakeMapWithSize of non-map type")
1973	}
1974	m := makemap(typ.(*rtype), n)
1975	return Value{typ.common(), unsafe.Pointer(&m), flag(Map) | flagIndir}
1976}
1977
1978// Indirect returns the value that v points to.
1979// If v is a nil pointer, Indirect returns a zero Value.
1980// If v is not a pointer, Indirect returns v.
1981func Indirect(v Value) Value {
1982	if v.Kind() != Ptr {
1983		return v
1984	}
1985	return v.Elem()
1986}
1987
1988// ValueOf returns a new Value initialized to the concrete value
1989// stored in the interface i. ValueOf(nil) returns the zero Value.
1990func ValueOf(i interface{}) Value {
1991	if i == nil {
1992		return Value{}
1993	}
1994
1995	// TODO: Maybe allow contents of a Value to live on the stack.
1996	// For now we make the contents always escape to the heap. It
1997	// makes life easier in a few places (see chanrecv/mapassign
1998	// comment below).
1999	escapes(i)
2000
2001	return unpackEface(i)
2002}
2003
2004// Zero returns a Value representing the zero value for the specified type.
2005// The result is different from the zero value of the Value struct,
2006// which represents no value at all.
2007// For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
2008// The returned value is neither addressable nor settable.
2009func Zero(typ Type) Value {
2010	if typ == nil {
2011		panic("reflect: Zero(nil)")
2012	}
2013	t := typ.common()
2014	fl := flag(t.Kind())
2015	if ifaceIndir(t) {
2016		return Value{t, unsafe_New(typ.(*rtype)), fl | flagIndir}
2017	}
2018	return Value{t, nil, fl}
2019}
2020
2021// New returns a Value representing a pointer to a new zero value
2022// for the specified type. That is, the returned Value's Type is PtrTo(typ).
2023func New(typ Type) Value {
2024	if typ == nil {
2025		panic("reflect: New(nil)")
2026	}
2027	ptr := unsafe_New(typ.(*rtype))
2028	fl := flag(Ptr)
2029	return Value{typ.common().ptrTo(), ptr, fl}
2030}
2031
2032// NewAt returns a Value representing a pointer to a value of the
2033// specified type, using p as that pointer.
2034func NewAt(typ Type, p unsafe.Pointer) Value {
2035	fl := flag(Ptr)
2036	return Value{typ.common().ptrTo(), p, fl}
2037}
2038
2039// assignTo returns a value v that can be assigned directly to typ.
2040// It panics if v is not assignable to typ.
2041// For a conversion to an interface type, target is a suggested scratch space to use.
2042func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value {
2043	if v.flag&flagMethod != 0 {
2044		v = makeMethodValue(context, v)
2045	}
2046
2047	switch {
2048	case directlyAssignable(dst, v.typ):
2049		// Overwrite type so that they match.
2050		// Same memory layout, so no harm done.
2051		fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
2052		fl |= flag(dst.Kind())
2053		return Value{dst, v.ptr, fl}
2054
2055	case implements(dst, v.typ):
2056		if target == nil {
2057			target = unsafe_New(dst)
2058		}
2059		if v.Kind() == Interface && v.IsNil() {
2060			// A nil ReadWriter passed to nil Reader is OK,
2061			// but using ifaceE2I below will panic.
2062			// Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
2063			return Value{dst, nil, flag(Interface)}
2064		}
2065		x := valueInterface(v, false)
2066		if dst.NumMethod() == 0 {
2067			*(*interface{})(target) = x
2068		} else {
2069			ifaceE2I(dst, x, target)
2070		}
2071		return Value{dst, target, flagIndir | flag(Interface)}
2072	}
2073
2074	// Failed.
2075	panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
2076}
2077
2078// Convert returns the value v converted to type t.
2079// If the usual Go conversion rules do not allow conversion
2080// of the value v to type t, Convert panics.
2081func (v Value) Convert(t Type) Value {
2082	if v.flag&flagMethod != 0 {
2083		v = makeMethodValue("Convert", v)
2084	}
2085	op := convertOp(t.common(), v.typ)
2086	if op == nil {
2087		panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
2088	}
2089	return op(v, t)
2090}
2091
2092// convertOp returns the function to convert a value of type src
2093// to a value of type dst. If the conversion is illegal, convertOp returns nil.
2094func convertOp(dst, src *rtype) func(Value, Type) Value {
2095	switch src.Kind() {
2096	case Int, Int8, Int16, Int32, Int64:
2097		switch dst.Kind() {
2098		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2099			return cvtInt
2100		case Float32, Float64:
2101			return cvtIntFloat
2102		case String:
2103			return cvtIntString
2104		}
2105
2106	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2107		switch dst.Kind() {
2108		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2109			return cvtUint
2110		case Float32, Float64:
2111			return cvtUintFloat
2112		case String:
2113			return cvtUintString
2114		}
2115
2116	case Float32, Float64:
2117		switch dst.Kind() {
2118		case Int, Int8, Int16, Int32, Int64:
2119			return cvtFloatInt
2120		case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2121			return cvtFloatUint
2122		case Float32, Float64:
2123			return cvtFloat
2124		}
2125
2126	case Complex64, Complex128:
2127		switch dst.Kind() {
2128		case Complex64, Complex128:
2129			return cvtComplex
2130		}
2131
2132	case String:
2133		if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
2134			switch dst.Elem().Kind() {
2135			case Uint8:
2136				return cvtStringBytes
2137			case Int32:
2138				return cvtStringRunes
2139			}
2140		}
2141
2142	case Slice:
2143		if dst.Kind() == String && src.Elem().PkgPath() == "" {
2144			switch src.Elem().Kind() {
2145			case Uint8:
2146				return cvtBytesString
2147			case Int32:
2148				return cvtRunesString
2149			}
2150		}
2151	}
2152
2153	// dst and src have same underlying type.
2154	if haveIdenticalUnderlyingType(dst, src, false) {
2155		return cvtDirect
2156	}
2157
2158	// dst and src are unnamed pointer types with same underlying base type.
2159	if dst.Kind() == Ptr && dst.Name() == "" &&
2160		src.Kind() == Ptr && src.Name() == "" &&
2161		haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false) {
2162		return cvtDirect
2163	}
2164
2165	if implements(dst, src) {
2166		if src.Kind() == Interface {
2167			return cvtI2I
2168		}
2169		return cvtT2I
2170	}
2171
2172	return nil
2173}
2174
2175// makeInt returns a Value of type t equal to bits (possibly truncated),
2176// where t is a signed or unsigned int type.
2177func makeInt(f flag, bits uint64, t Type) Value {
2178	typ := t.common()
2179	ptr := unsafe_New(typ)
2180	switch typ.size {
2181	case 1:
2182		*(*uint8)(ptr) = uint8(bits)
2183	case 2:
2184		*(*uint16)(ptr) = uint16(bits)
2185	case 4:
2186		*(*uint32)(ptr) = uint32(bits)
2187	case 8:
2188		*(*uint64)(ptr) = bits
2189	}
2190	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2191}
2192
2193// makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2194// where t is a float32 or float64 type.
2195func makeFloat(f flag, v float64, t Type) Value {
2196	typ := t.common()
2197	ptr := unsafe_New(typ)
2198	switch typ.size {
2199	case 4:
2200		*(*float32)(ptr) = float32(v)
2201	case 8:
2202		*(*float64)(ptr) = v
2203	}
2204	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2205}
2206
2207// makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2208// where t is a complex64 or complex128 type.
2209func makeComplex(f flag, v complex128, t Type) Value {
2210	typ := t.common()
2211	ptr := unsafe_New(typ)
2212	switch typ.size {
2213	case 8:
2214		*(*complex64)(ptr) = complex64(v)
2215	case 16:
2216		*(*complex128)(ptr) = v
2217	}
2218	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2219}
2220
2221func makeString(f flag, v string, t Type) Value {
2222	ret := New(t).Elem()
2223	ret.SetString(v)
2224	ret.flag = ret.flag&^flagAddr | f
2225	return ret
2226}
2227
2228func makeBytes(f flag, v []byte, t Type) Value {
2229	ret := New(t).Elem()
2230	ret.SetBytes(v)
2231	ret.flag = ret.flag&^flagAddr | f
2232	return ret
2233}
2234
2235func makeRunes(f flag, v []rune, t Type) Value {
2236	ret := New(t).Elem()
2237	ret.setRunes(v)
2238	ret.flag = ret.flag&^flagAddr | f
2239	return ret
2240}
2241
2242// These conversion functions are returned by convertOp
2243// for classes of conversions. For example, the first function, cvtInt,
2244// takes any value v of signed int type and returns the value converted
2245// to type t, where t is any signed or unsigned int type.
2246
2247// convertOp: intXX -> [u]intXX
2248func cvtInt(v Value, t Type) Value {
2249	return makeInt(v.flag.ro(), uint64(v.Int()), t)
2250}
2251
2252// convertOp: uintXX -> [u]intXX
2253func cvtUint(v Value, t Type) Value {
2254	return makeInt(v.flag.ro(), v.Uint(), t)
2255}
2256
2257// convertOp: floatXX -> intXX
2258func cvtFloatInt(v Value, t Type) Value {
2259	return makeInt(v.flag.ro(), uint64(int64(v.Float())), t)
2260}
2261
2262// convertOp: floatXX -> uintXX
2263func cvtFloatUint(v Value, t Type) Value {
2264	return makeInt(v.flag.ro(), uint64(v.Float()), t)
2265}
2266
2267// convertOp: intXX -> floatXX
2268func cvtIntFloat(v Value, t Type) Value {
2269	return makeFloat(v.flag.ro(), float64(v.Int()), t)
2270}
2271
2272// convertOp: uintXX -> floatXX
2273func cvtUintFloat(v Value, t Type) Value {
2274	return makeFloat(v.flag.ro(), float64(v.Uint()), t)
2275}
2276
2277// convertOp: floatXX -> floatXX
2278func cvtFloat(v Value, t Type) Value {
2279	return makeFloat(v.flag.ro(), v.Float(), t)
2280}
2281
2282// convertOp: complexXX -> complexXX
2283func cvtComplex(v Value, t Type) Value {
2284	return makeComplex(v.flag.ro(), v.Complex(), t)
2285}
2286
2287// convertOp: intXX -> string
2288func cvtIntString(v Value, t Type) Value {
2289	return makeString(v.flag.ro(), string(v.Int()), t)
2290}
2291
2292// convertOp: uintXX -> string
2293func cvtUintString(v Value, t Type) Value {
2294	return makeString(v.flag.ro(), string(v.Uint()), t)
2295}
2296
2297// convertOp: []byte -> string
2298func cvtBytesString(v Value, t Type) Value {
2299	return makeString(v.flag.ro(), string(v.Bytes()), t)
2300}
2301
2302// convertOp: string -> []byte
2303func cvtStringBytes(v Value, t Type) Value {
2304	return makeBytes(v.flag.ro(), []byte(v.String()), t)
2305}
2306
2307// convertOp: []rune -> string
2308func cvtRunesString(v Value, t Type) Value {
2309	return makeString(v.flag.ro(), string(v.runes()), t)
2310}
2311
2312// convertOp: string -> []rune
2313func cvtStringRunes(v Value, t Type) Value {
2314	return makeRunes(v.flag.ro(), []rune(v.String()), t)
2315}
2316
2317// convertOp: direct copy
2318func cvtDirect(v Value, typ Type) Value {
2319	f := v.flag
2320	t := typ.common()
2321	ptr := v.ptr
2322	if f&flagAddr != 0 {
2323		// indirect, mutable word - make a copy
2324		c := unsafe_New(t)
2325		typedmemmove(t, c, ptr)
2326		ptr = c
2327		f &^= flagAddr
2328	}
2329	return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f?
2330}
2331
2332// convertOp: concrete -> interface
2333func cvtT2I(v Value, typ Type) Value {
2334	target := unsafe_New(typ.common())
2335	x := valueInterface(v, false)
2336	if typ.NumMethod() == 0 {
2337		*(*interface{})(target) = x
2338	} else {
2339		ifaceE2I(typ.(*rtype), x, target)
2340	}
2341	return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)}
2342}
2343
2344// convertOp: interface -> interface
2345func cvtI2I(v Value, typ Type) Value {
2346	if v.IsNil() {
2347		ret := Zero(typ)
2348		ret.flag |= v.flag.ro()
2349		return ret
2350	}
2351	return cvtT2I(v.Elem(), typ)
2352}
2353
2354// implemented in ../runtime
2355func chancap(ch unsafe.Pointer) int
2356func chanclose(ch unsafe.Pointer)
2357func chanlen(ch unsafe.Pointer) int
2358
2359// Note: some of the noescape annotations below are technically a lie,
2360// but safe in the context of this package. Functions like chansend
2361// and mapassign don't escape the referent, but may escape anything
2362// the referent points to (they do shallow copies of the referent).
2363// It is safe in this package because the referent may only point
2364// to something a Value may point to, and that is always in the heap
2365// (due to the escapes() call in ValueOf).
2366
2367//go:noescape
2368func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
2369
2370//go:noescape
2371func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
2372
2373func makechan(typ *rtype, size int) (ch unsafe.Pointer)
2374func makemap(t *rtype, cap int) (m unsafe.Pointer)
2375
2376//go:noescape
2377func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
2378
2379//go:noescape
2380func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
2381
2382//go:noescape
2383func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
2384
2385// m escapes into the return value, but the caller of mapiterinit
2386// doesn't let the return value escape.
2387//go:noescape
2388func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
2389
2390//go:noescape
2391func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
2392
2393//go:noescape
2394func mapiternext(it unsafe.Pointer)
2395
2396//go:noescape
2397func maplen(m unsafe.Pointer) int
2398func call(typ *rtype, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer)
2399
2400func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
2401
2402// typedmemmove copies a value of type t to dst from src.
2403//go:noescape
2404func typedmemmove(t *rtype, dst, src unsafe.Pointer)
2405
2406// typedslicecopy copies a slice of elemType values from src to dst,
2407// returning the number of elements copied.
2408//go:noescape
2409func typedslicecopy(elemType *rtype, dst, src sliceHeader) int
2410
2411//go:noescape
2412//extern memmove
2413func memmove(adst, asrc unsafe.Pointer, n uintptr)
2414
2415// Dummy annotation marking that the value x escapes,
2416// for use in cases where the reflect code is so clever that
2417// the compiler cannot follow.
2418func escapes(x interface{}) {
2419	if dummy.b {
2420		dummy.x = x
2421	}
2422}
2423
2424var dummy struct {
2425	b bool
2426	x interface{}
2427}
2428