Source file src/reflect/value.go

Documentation: reflect

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

View as plain text