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