github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/reflect/value.go (about)

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