The Go Programming Language

Source file src/pkg/reflect/value.go

     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		"strconv"
    11		"unsafe"
    12	)
    13	
    14	const ptrSize = unsafe.Sizeof((*byte)(nil))
    15	const cannotSet = "cannot set value obtained from unexported struct field"
    16	
    17	// TODO: This will have to go away when
    18	// the new gc goes in.
    19	func memmove(adst, asrc unsafe.Pointer, n uintptr) {
    20		dst := uintptr(adst)
    21		src := uintptr(asrc)
    22		switch {
    23		case src < dst && src+n > dst:
    24			// byte copy backward
    25			// careful: i is unsigned
    26			for i := n; i > 0; {
    27				i--
    28				*(*byte)(unsafe.Pointer(dst + i)) = *(*byte)(unsafe.Pointer(src + i))
    29			}
    30		case (n|src|dst)&(ptrSize-1) != 0:
    31			// byte copy forward
    32			for i := uintptr(0); i < n; i++ {
    33				*(*byte)(unsafe.Pointer(dst + i)) = *(*byte)(unsafe.Pointer(src + i))
    34			}
    35		default:
    36			// word copy forward
    37			for i := uintptr(0); i < n; i += ptrSize {
    38				*(*uintptr)(unsafe.Pointer(dst + i)) = *(*uintptr)(unsafe.Pointer(src + i))
    39			}
    40		}
    41	}
    42	
    43	// Value is the reflection interface to a Go value.
    44	//
    45	// Not all methods apply to all kinds of values.  Restrictions,
    46	// if any, are noted in the documentation for each method.
    47	// Use the Kind method to find out the kind of value before
    48	// calling kind-specific methods.  Calling a method
    49	// inappropriate to the kind of type causes a run time panic.
    50	//
    51	// The zero Value represents no value.
    52	// Its IsValid method returns false, its Kind method returns Invalid,
    53	// its String method returns "<invalid Value>", and all other methods panic.
    54	// Most functions and methods never return an invalid value.
    55	// If one does, its documentation states the conditions explicitly.
    56	//
    57	// The fields of Value are exported so that clients can copy and
    58	// pass Values around, but they should not be edited or inspected
    59	// directly.  A future language change may make it possible not to
    60	// export these fields while still keeping Values usable as values.
    61	type Value struct {
    62		Internal       interface{}
    63		InternalMethod int
    64	}
    65	
    66	// A ValueError occurs when a Value method is invoked on
    67	// a Value that does not support it.  Such cases are documented
    68	// in the description of each method.
    69	type ValueError struct {
    70		Method string
    71		Kind   Kind
    72	}
    73	
    74	func (e *ValueError) String() string {
    75		if e.Kind == 0 {
    76			return "reflect: call of " + e.Method + " on zero Value"
    77		}
    78		return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
    79	}
    80	
    81	// methodName returns the name of the calling method,
    82	// assumed to be two stack frames above.
    83	func methodName() string {
    84		pc, _, _, _ := runtime.Caller(2)
    85		f := runtime.FuncForPC(pc)
    86		if f == nil {
    87			return "unknown method"
    88		}
    89		return f.Name()
    90	}
    91	
    92	// An iword is the word that would be stored in an
    93	// interface to represent a given value v.  Specifically, if v is
    94	// bigger than a pointer, its word is a pointer to v's data.
    95	// Otherwise, its word is a zero uintptr with the data stored
    96	// in the leading bytes.
    97	type iword uintptr
    98	
    99	func loadIword(p unsafe.Pointer, size uintptr) iword {
   100		// Run the copy ourselves instead of calling memmove
   101		// to avoid moving v to the heap.
   102		w := iword(0)
   103		switch size {
   104		default:
   105			panic("reflect: internal error: loadIword of " + strconv.Itoa(int(size)) + "-byte value")
   106		case 0:
   107		case 1:
   108			*(*uint8)(unsafe.Pointer(&w)) = *(*uint8)(p)
   109		case 2:
   110			*(*uint16)(unsafe.Pointer(&w)) = *(*uint16)(p)
   111		case 3:
   112			*(*[3]byte)(unsafe.Pointer(&w)) = *(*[3]byte)(p)
   113		case 4:
   114			*(*uint32)(unsafe.Pointer(&w)) = *(*uint32)(p)
   115		case 5:
   116			*(*[5]byte)(unsafe.Pointer(&w)) = *(*[5]byte)(p)
   117		case 6:
   118			*(*[6]byte)(unsafe.Pointer(&w)) = *(*[6]byte)(p)
   119		case 7:
   120			*(*[7]byte)(unsafe.Pointer(&w)) = *(*[7]byte)(p)
   121		case 8:
   122			*(*uint64)(unsafe.Pointer(&w)) = *(*uint64)(p)
   123		}
   124		return w
   125	}
   126	
   127	func storeIword(p unsafe.Pointer, w iword, size uintptr) {
   128		// Run the copy ourselves instead of calling memmove
   129		// to avoid moving v to the heap.
   130		switch size {
   131		default:
   132			panic("reflect: internal error: storeIword of " + strconv.Itoa(int(size)) + "-byte value")
   133		case 0:
   134		case 1:
   135			*(*uint8)(p) = *(*uint8)(unsafe.Pointer(&w))
   136		case 2:
   137			*(*uint16)(p) = *(*uint16)(unsafe.Pointer(&w))
   138		case 3:
   139			*(*[3]byte)(p) = *(*[3]byte)(unsafe.Pointer(&w))
   140		case 4:
   141			*(*uint32)(p) = *(*uint32)(unsafe.Pointer(&w))
   142		case 5:
   143			*(*[5]byte)(p) = *(*[5]byte)(unsafe.Pointer(&w))
   144		case 6:
   145			*(*[6]byte)(p) = *(*[6]byte)(unsafe.Pointer(&w))
   146		case 7:
   147			*(*[7]byte)(p) = *(*[7]byte)(unsafe.Pointer(&w))
   148		case 8:
   149			*(*uint64)(p) = *(*uint64)(unsafe.Pointer(&w))
   150		}
   151	}
   152	
   153	// emptyInterface is the header for an interface{} value.
   154	type emptyInterface struct {
   155		typ  *runtime.Type
   156		word iword
   157	}
   158	
   159	// nonEmptyInterface is the header for a interface value with methods.
   160	type nonEmptyInterface struct {
   161		// see ../runtime/iface.c:/Itab
   162		itab *struct {
   163			ityp   *runtime.Type // static interface type
   164			typ    *runtime.Type // dynamic concrete type
   165			link   unsafe.Pointer
   166			bad    int32
   167			unused int32
   168			fun    [100000]unsafe.Pointer // method table
   169		}
   170		word iword
   171	}
   172	
   173	// Regarding the implementation of Value:
   174	//
   175	// The Internal interface is a true interface value in the Go sense,
   176	// but it also serves as a (type, address) pair in which one cannot
   177	// be changed separately from the other.  That is, it serves as a way
   178	// to prevent unsafe mutations of the Internal state even though
   179	// we cannot (yet?) hide the field while preserving the ability for
   180	// clients to make copies of Values.
   181	//
   182	// The internal method converts a Value into the expanded internalValue struct.
   183	// If we could avoid exporting fields we'd probably make internalValue the
   184	// definition of Value.
   185	//
   186	// If a Value is addressable (CanAddr returns true), then the Internal
   187	// interface value holds a pointer to the actual field data, and Set stores
   188	// through that pointer.  If a Value is not addressable (CanAddr returns false),
   189	// then the Internal interface value holds the actual value.
   190	//
   191	// In addition to whether a value is addressable, we track whether it was
   192	// obtained by using an unexported struct field.  Such values are allowed
   193	// to be read, mainly to make fmt.Print more useful, but they are not
   194	// allowed to be written.  We call such values read-only.
   195	//
   196	// A Value can be set (via the Set, SetUint, etc. methods) only if it is both
   197	// addressable and not read-only.
   198	//
   199	// The two permission bits - addressable and read-only - are stored in
   200	// the bottom two bits of the type pointer in the interface value.
   201	//
   202	//	ordinary value: Internal = value
   203	//	addressable value: Internal = value, Internal.typ |= flagAddr
   204	//	read-only value: Internal = value, Internal.typ |= flagRO
   205	//	addressable, read-only value: Internal = value, Internal.typ |= flagAddr | flagRO
   206	//
   207	// It is important that the read-only values have the extra bit set
   208	// (as opposed to using the bit to mean writable), because client code
   209	// can grab the interface field and try to use it.  Having the extra bit
   210	// set makes the type pointer compare not equal to any real type,
   211	// so that a client cannot, say, write through v.Internal.(*int).
   212	// The runtime routines that access interface types reject types with
   213	// low bits set.
   214	//
   215	// If a Value fv = v.Method(i), then fv = v with the InternalMethod
   216	// field set to i+1.  Methods are never addressable.
   217	//
   218	// All in all, this is a lot of effort just to avoid making this new API
   219	// depend on a language change we'll probably do anyway, but
   220	// it's helpful to keep the two separate, and much of the logic is
   221	// necessary to implement the Interface method anyway.
   222	
   223	const (
   224		flagAddr uint32 = 1 << iota // holds address of value
   225		flagRO                      // read-only
   226	
   227		reflectFlags = 3
   228	)
   229	
   230	// An internalValue is the unpacked form of a Value.
   231	// The zero Value unpacks to a zero internalValue
   232	type internalValue struct {
   233		typ       *commonType // type of value
   234		kind      Kind        // kind of value
   235		flag      uint32
   236		word      iword
   237		addr      unsafe.Pointer
   238		rcvr      iword
   239		method    bool
   240		nilmethod bool
   241	}
   242	
   243	func (v Value) internal() internalValue {
   244		var iv internalValue
   245		eface := *(*emptyInterface)(unsafe.Pointer(&v.Internal))
   246		p := uintptr(unsafe.Pointer(eface.typ))
   247		iv.typ = toCommonType((*runtime.Type)(unsafe.Pointer(p &^ reflectFlags)))
   248		if iv.typ == nil {
   249			return iv
   250		}
   251		iv.flag = uint32(p & reflectFlags)
   252		iv.word = eface.word
   253		if iv.flag&flagAddr != 0 {
   254			iv.addr = unsafe.Pointer(iv.word)
   255			iv.typ = iv.typ.Elem().common()
   256			if iv.typ.size <= ptrSize {
   257				iv.word = loadIword(iv.addr, iv.typ.size)
   258			}
   259		} else {
   260			if iv.typ.size > ptrSize {
   261				iv.addr = unsafe.Pointer(iv.word)
   262			}
   263		}
   264		iv.kind = iv.typ.Kind()
   265	
   266		// Is this a method?  If so, iv describes the receiver.
   267		// Rewrite to describe the method function.
   268		if v.InternalMethod != 0 {
   269			// If this Value is a method value (x.Method(i) for some Value x)
   270			// then we will invoke it using the interface form of the method,
   271			// which always passes the receiver as a single word.
   272			// Record that information.
   273			i := v.InternalMethod - 1
   274			if iv.kind == Interface {
   275				it := (*interfaceType)(unsafe.Pointer(iv.typ))
   276				if i < 0 || i >= len(it.methods) {
   277					panic("reflect: broken Value")
   278				}
   279				m := &it.methods[i]
   280				if m.pkgPath != nil {
   281					iv.flag |= flagRO
   282				}
   283				iv.typ = toCommonType(m.typ)
   284				iface := (*nonEmptyInterface)(iv.addr)
   285				if iface.itab == nil {
   286					iv.word = 0
   287					iv.nilmethod = true
   288				} else {
   289					iv.word = iword(iface.itab.fun[i])
   290				}
   291				iv.rcvr = iface.word
   292			} else {
   293				ut := iv.typ.uncommon()
   294				if ut == nil || i < 0 || i >= len(ut.methods) {
   295					panic("reflect: broken Value")
   296				}
   297				m := &ut.methods[i]
   298				if m.pkgPath != nil {
   299					iv.flag |= flagRO
   300				}
   301				iv.typ = toCommonType(m.mtyp)
   302				iv.rcvr = iv.word
   303				iv.word = iword(m.ifn)
   304			}
   305			iv.kind = Func
   306			iv.method = true
   307			iv.flag &^= flagAddr
   308			iv.addr = nil
   309		}
   310	
   311		return iv
   312	}
   313	
   314	// packValue returns a Value with the given flag bits, type, and interface word.
   315	func packValue(flag uint32, typ *runtime.Type, word iword) Value {
   316		if typ == nil {
   317			panic("packValue")
   318		}
   319		t := uintptr(unsafe.Pointer(typ))
   320		t |= uintptr(flag)
   321		eface := emptyInterface{(*runtime.Type)(unsafe.Pointer(t)), word}
   322		return Value{Internal: *(*interface{})(unsafe.Pointer(&eface))}
   323	}
   324	
   325	// valueFromAddr returns a Value using the given type and address.
   326	func valueFromAddr(flag uint32, typ Type, addr unsafe.Pointer) Value {
   327		if flag&flagAddr != 0 {
   328			// Addressable, so the internal value is
   329			// an interface containing a pointer to the real value.
   330			return packValue(flag, PtrTo(typ).runtimeType(), iword(addr))
   331		}
   332	
   333		var w iword
   334		if n := typ.Size(); n <= ptrSize {
   335			// In line, so the interface word is the actual value.
   336			w = loadIword(addr, n)
   337		} else {
   338			// Not in line: the interface word is the address.
   339			w = iword(addr)
   340		}
   341		return packValue(flag, typ.runtimeType(), w)
   342	}
   343	
   344	// valueFromIword returns a Value using the given type and interface word.
   345	func valueFromIword(flag uint32, typ Type, w iword) Value {
   346		if flag&flagAddr != 0 {
   347			panic("reflect: internal error: valueFromIword addressable")
   348		}
   349		return packValue(flag, typ.runtimeType(), w)
   350	}
   351	
   352	func (iv internalValue) mustBe(want Kind) {
   353		if iv.kind != want {
   354			panic(&ValueError{methodName(), iv.kind})
   355		}
   356	}
   357	
   358	func (iv internalValue) mustBeExported() {
   359		if iv.kind == 0 {
   360			panic(&ValueError{methodName(), iv.kind})
   361		}
   362		if iv.flag&flagRO != 0 {
   363			panic(methodName() + " using value obtained using unexported field")
   364		}
   365	}
   366	
   367	func (iv internalValue) mustBeAssignable() {
   368		if iv.kind == 0 {
   369			panic(&ValueError{methodName(), iv.kind})
   370		}
   371		// Assignable if addressable and not read-only.
   372		if iv.flag&flagRO != 0 {
   373			panic(methodName() + " using value obtained using unexported field")
   374		}
   375		if iv.flag&flagAddr == 0 {
   376			panic(methodName() + " using unaddressable value")
   377		}
   378	}
   379	
   380	// Addr returns a pointer value representing the address of v.
   381	// It panics if CanAddr() returns false.
   382	// Addr is typically used to obtain a pointer to a struct field
   383	// or slice element in order to call a method that requires a
   384	// pointer receiver.
   385	func (v Value) Addr() Value {
   386		iv := v.internal()
   387		if iv.flag&flagAddr == 0 {
   388			panic("reflect.Value.Addr of unaddressable value")
   389		}
   390		return valueFromIword(iv.flag&flagRO, PtrTo(iv.typ.toType()), iword(iv.addr))
   391	}
   392	
   393	// Bool returns v's underlying value.
   394	// It panics if v's kind is not Bool.
   395	func (v Value) Bool() bool {
   396		iv := v.internal()
   397		iv.mustBe(Bool)
   398		return *(*bool)(unsafe.Pointer(&iv.word))
   399	}
   400	
   401	// CanAddr returns true if the value's address can be obtained with Addr.
   402	// Such values are called addressable.  A value is addressable if it is
   403	// an element of a slice, an element of an addressable array,
   404	// a field of an addressable struct, or the result of dereferencing a pointer.
   405	// If CanAddr returns false, calling Addr will panic.
   406	func (v Value) CanAddr() bool {
   407		iv := v.internal()
   408		return iv.flag&flagAddr != 0
   409	}
   410	
   411	// CanSet returns true if the value of v can be changed.
   412	// A Value can be changed only if it is addressable and was not
   413	// obtained by the use of unexported struct fields.
   414	// If CanSet returns false, calling Set or any type-specific
   415	// setter (e.g., SetBool, SetInt64) will panic.
   416	func (v Value) CanSet() bool {
   417		iv := v.internal()
   418		return iv.flag&(flagAddr|flagRO) == flagAddr
   419	}
   420	
   421	// Call calls the function v with the input arguments in.
   422	// For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
   423	// Call panics if v's Kind is not Func.
   424	// It returns the output results as Values.
   425	// As in Go, each input argument must be assignable to the
   426	// type of the function's corresponding input parameter.
   427	// If v is a variadic function, Call creates the variadic slice parameter
   428	// itself, copying in the corresponding values.
   429	func (v Value) Call(in []Value) []Value {
   430		iv := v.internal()
   431		iv.mustBe(Func)
   432		iv.mustBeExported()
   433		return iv.call("Call", in)
   434	}
   435	
   436	// CallSlice calls the variadic function v with the input arguments in,
   437	// assigning the slice in[len(in)-1] to v's final variadic argument.  
   438	// For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]...).
   439	// Call panics if v's Kind is not Func or if v is not variadic.
   440	// It returns the output results as Values.
   441	// As in Go, each input argument must be assignable to the
   442	// type of the function's corresponding input parameter.
   443	func (v Value) CallSlice(in []Value) []Value {
   444		iv := v.internal()
   445		iv.mustBe(Func)
   446		iv.mustBeExported()
   447		return iv.call("CallSlice", in)
   448	}
   449	
   450	func (iv internalValue) call(method string, in []Value) []Value {
   451		if iv.word == 0 {
   452			if iv.nilmethod {
   453				panic("reflect.Value.Call: call of method on nil interface value")
   454			}
   455			panic("reflect.Value.Call: call of nil function")
   456		}
   457	
   458		isSlice := method == "CallSlice"
   459		t := iv.typ
   460		n := t.NumIn()
   461		if isSlice {
   462			if !t.IsVariadic() {
   463				panic("reflect: CallSlice of non-variadic function")
   464			}
   465			if len(in) < n {
   466				panic("reflect: CallSlice with too few input arguments")
   467			}
   468			if len(in) > n {
   469				panic("reflect: CallSlice with too many input arguments")
   470			}
   471		} else {
   472			if t.IsVariadic() {
   473				n--
   474			}
   475			if len(in) < n {
   476				panic("reflect: Call with too few input arguments")
   477			}
   478			if !t.IsVariadic() && len(in) > n {
   479				panic("reflect: Call with too many input arguments")
   480			}
   481		}
   482		for _, x := range in {
   483			if x.Kind() == Invalid {
   484				panic("reflect: " + method + " using zero Value argument")
   485			}
   486		}
   487		for i := 0; i < n; i++ {
   488			if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
   489				panic("reflect: " + method + " using " + xt.String() + " as type " + targ.String())
   490			}
   491		}
   492		if !isSlice && t.IsVariadic() {
   493			// prepare slice for remaining values
   494			m := len(in) - n
   495			slice := MakeSlice(t.In(n), m, m)
   496			elem := t.In(n).Elem()
   497			for i := 0; i < m; i++ {
   498				x := in[n+i]
   499				if xt := x.Type(); !xt.AssignableTo(elem) {
   500					panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + method)
   501				}
   502				slice.Index(i).Set(x)
   503			}
   504			origIn := in
   505			in = make([]Value, n+1)
   506			copy(in[:n], origIn)
   507			in[n] = slice
   508		}
   509	
   510		nin := len(in)
   511		if nin != t.NumIn() {
   512			panic("reflect.Value.Call: wrong argument count")
   513		}
   514		nout := t.NumOut()
   515	
   516		// Compute arg size & allocate.
   517		// This computation is 5g/6g/8g-dependent
   518		// and probably wrong for gccgo, but so
   519		// is most of this function.
   520		size := uintptr(0)
   521		if iv.method {
   522			// extra word for interface value
   523			size += ptrSize
   524		}
   525		for i := 0; i < nin; i++ {
   526			tv := t.In(i)
   527			a := uintptr(tv.Align())
   528			size = (size + a - 1) &^ (a - 1)
   529			size += tv.Size()
   530		}
   531		size = (size + ptrSize - 1) &^ (ptrSize - 1)
   532		for i := 0; i < nout; i++ {
   533			tv := t.Out(i)
   534			a := uintptr(tv.Align())
   535			size = (size + a - 1) &^ (a - 1)
   536			size += tv.Size()
   537		}
   538	
   539		// size must be > 0 in order for &args[0] to be valid.
   540		// the argument copying is going to round it up to
   541		// a multiple of ptrSize anyway, so make it ptrSize to begin with.
   542		if size < ptrSize {
   543			size = ptrSize
   544		}
   545	
   546		// round to pointer size
   547		size = (size + ptrSize - 1) &^ (ptrSize - 1)
   548	
   549		// Copy into args.
   550		//
   551		// TODO(rsc): revisit when reference counting happens.
   552		// The values are holding up the in references for us,
   553		// but something must be done for the out references.
   554		// For now make everything look like a pointer by pretending
   555		// to allocate a []*int.
   556		args := make([]*int, size/ptrSize)
   557		ptr := uintptr(unsafe.Pointer(&args[0]))
   558		off := uintptr(0)
   559		if iv.method {
   560			// Hard-wired first argument.
   561			*(*iword)(unsafe.Pointer(ptr)) = iv.rcvr
   562			off = ptrSize
   563		}
   564		for i, v := range in {
   565			iv := v.internal()
   566			iv.mustBeExported()
   567			targ := t.In(i).(*commonType)
   568			a := uintptr(targ.align)
   569			off = (off + a - 1) &^ (a - 1)
   570			n := targ.size
   571			addr := unsafe.Pointer(ptr + off)
   572			iv = convertForAssignment("reflect.Value.Call", addr, targ, iv)
   573			if iv.addr == nil {
   574				storeIword(addr, iv.word, n)
   575			} else {
   576				memmove(addr, iv.addr, n)
   577			}
   578			off += n
   579		}
   580		off = (off + ptrSize - 1) &^ (ptrSize - 1)
   581	
   582		// Call.
   583		call(unsafe.Pointer(iv.word), unsafe.Pointer(ptr), uint32(size))
   584	
   585		// Copy return values out of args.
   586		//
   587		// TODO(rsc): revisit like above.
   588		ret := make([]Value, nout)
   589		for i := 0; i < nout; i++ {
   590			tv := t.Out(i)
   591			a := uintptr(tv.Align())
   592			off = (off + a - 1) &^ (a - 1)
   593			ret[i] = valueFromAddr(0, tv, unsafe.Pointer(ptr+off))
   594			off += tv.Size()
   595		}
   596	
   597		return ret
   598	}
   599	
   600	// Cap returns v's capacity.
   601	// It panics if v's Kind is not Array, Chan, or Slice.
   602	func (v Value) Cap() int {
   603		iv := v.internal()
   604		switch iv.kind {
   605		case Array:
   606			return iv.typ.Len()
   607		case Chan:
   608			return int(chancap(iv.word))
   609		case Slice:
   610			return (*SliceHeader)(iv.addr).Cap
   611		}
   612		panic(&ValueError{"reflect.Value.Cap", iv.kind})
   613	}
   614	
   615	// Close closes the channel v.
   616	// It panics if v's Kind is not Chan.
   617	func (v Value) Close() {
   618		iv := v.internal()
   619		iv.mustBe(Chan)
   620		iv.mustBeExported()
   621		ch := iv.word
   622		chanclose(ch)
   623	}
   624	
   625	// Complex returns v's underlying value, as a complex128.
   626	// It panics if v's Kind is not Complex64 or Complex128
   627	func (v Value) Complex() complex128 {
   628		iv := v.internal()
   629		switch iv.kind {
   630		case Complex64:
   631			if iv.addr == nil {
   632				return complex128(*(*complex64)(unsafe.Pointer(&iv.word)))
   633			}
   634			return complex128(*(*complex64)(iv.addr))
   635		case Complex128:
   636			return *(*complex128)(iv.addr)
   637		}
   638		panic(&ValueError{"reflect.Value.Complex", iv.kind})
   639	}
   640	
   641	// Elem returns the value that the interface v contains
   642	// or that the pointer v points to.
   643	// It panics if v's Kind is not Interface or Ptr.
   644	// It returns the zero Value if v is nil.
   645	func (v Value) Elem() Value {
   646		iv := v.internal()
   647		return iv.Elem()
   648	}
   649	
   650	func (iv internalValue) Elem() Value {
   651		switch iv.kind {
   652		case Interface:
   653			// Empty interface and non-empty interface have different layouts.
   654			// Convert to empty interface.
   655			var eface emptyInterface
   656			if iv.typ.NumMethod() == 0 {
   657				eface = *(*emptyInterface)(iv.addr)
   658			} else {
   659				iface := (*nonEmptyInterface)(iv.addr)
   660				if iface.itab != nil {
   661					eface.typ = iface.itab.typ
   662				}
   663				eface.word = iface.word
   664			}
   665			if eface.typ == nil {
   666				return Value{}
   667			}
   668			return valueFromIword(iv.flag&flagRO, toType(eface.typ), eface.word)
   669	
   670		case Ptr:
   671			// The returned value's address is v's value.
   672			if iv.word == 0 {
   673				return Value{}
   674			}
   675			return valueFromAddr(iv.flag&flagRO|flagAddr, iv.typ.Elem(), unsafe.Pointer(iv.word))
   676		}
   677		panic(&ValueError{"reflect.Value.Elem", iv.kind})
   678	}
   679	
   680	// Field returns the i'th field of the struct v.
   681	// It panics if v's Kind is not Struct or i is out of range.
   682	func (v Value) Field(i int) Value {
   683		iv := v.internal()
   684		iv.mustBe(Struct)
   685		t := iv.typ.toType()
   686		if i < 0 || i >= t.NumField() {
   687			panic("reflect: Field index out of range")
   688		}
   689		f := t.Field(i)
   690	
   691		// Inherit permission bits from v.
   692		flag := iv.flag
   693		// Using an unexported field forces flagRO.
   694		if f.PkgPath != "" {
   695			flag |= flagRO
   696		}
   697		return valueFromValueOffset(flag, f.Type, iv, f.Offset)
   698	}
   699	
   700	// valueFromValueOffset returns a sub-value of outer
   701	// (outer is an array or a struct) with the given flag and type
   702	// starting at the given byte offset into outer.
   703	func valueFromValueOffset(flag uint32, typ Type, outer internalValue, offset uintptr) Value {
   704		if outer.addr != nil {
   705			return valueFromAddr(flag, typ, unsafe.Pointer(uintptr(outer.addr)+offset))
   706		}
   707	
   708		// outer is so tiny it is in line.
   709		// We have to use outer.word and derive
   710		// the new word (it cannot possibly be bigger).
   711		// In line, so not addressable.
   712		if flag&flagAddr != 0 {
   713			panic("reflect: internal error: misuse of valueFromValueOffset")
   714		}
   715		b := *(*[ptrSize]byte)(unsafe.Pointer(&outer.word))
   716		for i := uintptr(0); i < typ.Size(); i++ {
   717			b[i] = b[offset+i]
   718		}
   719		for i := typ.Size(); i < ptrSize; i++ {
   720			b[i] = 0
   721		}
   722		w := *(*iword)(unsafe.Pointer(&b))
   723		return valueFromIword(flag, typ, w)
   724	}
   725	
   726	// FieldByIndex returns the nested field corresponding to index.
   727	// It panics if v's Kind is not struct.
   728	func (v Value) FieldByIndex(index []int) Value {
   729		v.internal().mustBe(Struct)
   730		for i, x := range index {
   731			if i > 0 {
   732				if v.Kind() == Ptr && v.Elem().Kind() == Struct {
   733					v = v.Elem()
   734				}
   735			}
   736			v = v.Field(x)
   737		}
   738		return v
   739	}
   740	
   741	// FieldByName returns the struct field with the given name.
   742	// It returns the zero Value if no field was found.
   743	// It panics if v's Kind is not struct.
   744	func (v Value) FieldByName(name string) Value {
   745		iv := v.internal()
   746		iv.mustBe(Struct)
   747		if f, ok := iv.typ.FieldByName(name); ok {
   748			return v.FieldByIndex(f.Index)
   749		}
   750		return Value{}
   751	}
   752	
   753	// FieldByNameFunc returns the struct field with a name
   754	// that satisfies the match function.
   755	// It panics if v's Kind is not struct.
   756	// It returns the zero Value if no field was found.
   757	func (v Value) FieldByNameFunc(match func(string) bool) Value {
   758		v.internal().mustBe(Struct)
   759		if f, ok := v.Type().FieldByNameFunc(match); ok {
   760			return v.FieldByIndex(f.Index)
   761		}
   762		return Value{}
   763	}
   764	
   765	// Float returns v's underlying value, as an float64.
   766	// It panics if v's Kind is not Float32 or Float64
   767	func (v Value) Float() float64 {
   768		iv := v.internal()
   769		switch iv.kind {
   770		case Float32:
   771			return float64(*(*float32)(unsafe.Pointer(&iv.word)))
   772		case Float64:
   773			// If the pointer width can fit an entire float64,
   774			// the value is in line when stored in an interface.
   775			if iv.addr == nil {
   776				return *(*float64)(unsafe.Pointer(&iv.word))
   777			}
   778			// Otherwise we have a pointer.
   779			return *(*float64)(iv.addr)
   780		}
   781		panic(&ValueError{"reflect.Value.Float", iv.kind})
   782	}
   783	
   784	// Index returns v's i'th element.
   785	// It panics if v's Kind is not Array or Slice or i is out of range.
   786	func (v Value) Index(i int) Value {
   787		iv := v.internal()
   788		switch iv.kind {
   789		default:
   790			panic(&ValueError{"reflect.Value.Index", iv.kind})
   791		case Array:
   792			flag := iv.flag // element flag same as overall array
   793			t := iv.typ.toType()
   794			if i < 0 || i > t.Len() {
   795				panic("reflect: array index out of range")
   796			}
   797			typ := t.Elem()
   798			return valueFromValueOffset(flag, typ, iv, uintptr(i)*typ.Size())
   799	
   800		case Slice:
   801			// Element flag same as Elem of Ptr.
   802			// Addressable, possibly read-only.
   803			flag := iv.flag&flagRO | flagAddr
   804			s := (*SliceHeader)(iv.addr)
   805			if i < 0 || i >= s.Len {
   806				panic("reflect: slice index out of range")
   807			}
   808			typ := iv.typ.Elem()
   809			addr := unsafe.Pointer(s.Data + uintptr(i)*typ.Size())
   810			return valueFromAddr(flag, typ, addr)
   811		}
   812	
   813		panic("not reached")
   814	}
   815	
   816	// Int returns v's underlying value, as an int64.
   817	// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
   818	func (v Value) Int() int64 {
   819		iv := v.internal()
   820		switch iv.kind {
   821		case Int:
   822			return int64(*(*int)(unsafe.Pointer(&iv.word)))
   823		case Int8:
   824			return int64(*(*int8)(unsafe.Pointer(&iv.word)))
   825		case Int16:
   826			return int64(*(*int16)(unsafe.Pointer(&iv.word)))
   827		case Int32:
   828			return int64(*(*int32)(unsafe.Pointer(&iv.word)))
   829		case Int64:
   830			if iv.addr == nil {
   831				return *(*int64)(unsafe.Pointer(&iv.word))
   832			}
   833			return *(*int64)(iv.addr)
   834		}
   835		panic(&ValueError{"reflect.Value.Int", iv.kind})
   836	}
   837	
   838	// CanInterface returns true if Interface can be used without panicking.
   839	func (v Value) CanInterface() bool {
   840		iv := v.internal()
   841		if iv.kind == Invalid {
   842			panic(&ValueError{"reflect.Value.CanInterface", iv.kind})
   843		}
   844		return v.InternalMethod == 0 && iv.flag&flagRO == 0
   845	}
   846	
   847	// Interface returns v's value as an interface{}.
   848	// If v is a method obtained by invoking Value.Method
   849	// (as opposed to Type.Method), Interface cannot return an
   850	// interface value, so it panics.
   851	func (v Value) Interface() interface{} {
   852		return valueInterface(v, true)
   853	}
   854	
   855	func valueInterface(v Value, safe bool) interface{} {
   856		iv := v.internal()
   857		return iv.valueInterface(safe)
   858	}
   859	
   860	func (iv internalValue) valueInterface(safe bool) interface{} {
   861		if iv.kind == 0 {
   862			panic(&ValueError{"reflect.Value.Interface", iv.kind})
   863		}
   864		if iv.method {
   865			panic("reflect.Value.Interface: cannot create interface value for method with bound receiver")
   866		}
   867	
   868		if safe && iv.flag&flagRO != 0 {
   869			// Do not allow access to unexported values via Interface,
   870			// because they might be pointers that should not be 
   871			// writable or methods or function that should not be callable.
   872			panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
   873		}
   874		if iv.kind == Interface {
   875			// Special case: return the element inside the interface.
   876			// Won't recurse further because an interface cannot contain an interface.
   877			if iv.IsNil() {
   878				return nil
   879			}
   880			return iv.Elem().Interface()
   881		}
   882	
   883		// Non-interface value.
   884		var eface emptyInterface
   885		eface.typ = iv.typ.runtimeType()
   886		eface.word = iv.word
   887		return *(*interface{})(unsafe.Pointer(&eface))
   888	}
   889	
   890	// InterfaceData returns the interface v's value as a uintptr pair.
   891	// It panics if v's Kind is not Interface.
   892	func (v Value) InterfaceData() [2]uintptr {
   893		iv := v.internal()
   894		iv.mustBe(Interface)
   895		// We treat this as a read operation, so we allow
   896		// it even for unexported data, because the caller
   897		// has to import "unsafe" to turn it into something
   898		// that can be abused.
   899		return *(*[2]uintptr)(iv.addr)
   900	}
   901	
   902	// IsNil returns true if v is a nil value.
   903	// It panics if v's Kind is not Chan, Func, Interface, Map, Ptr, or Slice.
   904	func (v Value) IsNil() bool {
   905		return v.internal().IsNil()
   906	}
   907	
   908	func (iv internalValue) IsNil() bool {
   909		switch iv.kind {
   910		case Chan, Func, Map, Ptr:
   911			if iv.method {
   912				panic("reflect: IsNil of method Value")
   913			}
   914			return iv.word == 0
   915		case Interface, Slice:
   916			// Both interface and slice are nil if first word is 0.
   917			return *(*uintptr)(iv.addr) == 0
   918		}
   919		panic(&ValueError{"reflect.Value.IsNil", iv.kind})
   920	}
   921	
   922	// IsValid returns true if v represents a value.
   923	// It returns false if v is the zero Value.
   924	// If IsValid returns false, all other methods except String panic.
   925	// Most functions and methods never return an invalid value.
   926	// If one does, its documentation states the conditions explicitly.
   927	func (v Value) IsValid() bool {
   928		return v.Internal != nil
   929	}
   930	
   931	// Kind returns v's Kind.
   932	// If v is the zero Value (IsValid returns false), Kind returns Invalid.
   933	func (v Value) Kind() Kind {
   934		return v.internal().kind
   935	}
   936	
   937	// Len returns v's length.
   938	// It panics if v's Kind is not Array, Chan, Map, Slice, or String.
   939	func (v Value) Len() int {
   940		iv := v.internal()
   941		switch iv.kind {
   942		case Array:
   943			return iv.typ.Len()
   944		case Chan:
   945			return int(chanlen(iv.word))
   946		case Map:
   947			return int(maplen(iv.word))
   948		case Slice:
   949			return (*SliceHeader)(iv.addr).Len
   950		case String:
   951			return (*StringHeader)(iv.addr).Len
   952		}
   953		panic(&ValueError{"reflect.Value.Len", iv.kind})
   954	}
   955	
   956	// MapIndex returns the value associated with key in the map v.
   957	// It panics if v's Kind is not Map.
   958	// It returns the zero Value if key is not found in the map or if v represents a nil map.
   959	// As in Go, the key's value must be assignable to the map's key type.
   960	func (v Value) MapIndex(key Value) Value {
   961		iv := v.internal()
   962		iv.mustBe(Map)
   963		typ := iv.typ.toType()
   964	
   965		// Do not require ikey to be exported, so that DeepEqual
   966		// and other programs can use all the keys returned by
   967		// MapKeys as arguments to MapIndex.  If either the map
   968		// or the key is unexported, though, the result will be
   969		// considered unexported.
   970	
   971		ikey := key.internal()
   972		ikey = convertForAssignment("reflect.Value.MapIndex", nil, typ.Key(), ikey)
   973		if iv.word == 0 {
   974			return Value{}
   975		}
   976	
   977		flag := (iv.flag | ikey.flag) & flagRO
   978		elemType := typ.Elem()
   979		elemWord, ok := mapaccess(typ.runtimeType(), iv.word, ikey.word)
   980		if !ok {
   981			return Value{}
   982		}
   983		return valueFromIword(flag, elemType, elemWord)
   984	}
   985	
   986	// MapKeys returns a slice containing all the keys present in the map,
   987	// in unspecified order.
   988	// It panics if v's Kind is not Map.
   989	// It returns an empty slice if v represents a nil map.
   990	func (v Value) MapKeys() []Value {
   991		iv := v.internal()
   992		iv.mustBe(Map)
   993		keyType := iv.typ.Key()
   994	
   995		flag := iv.flag & flagRO
   996		m := iv.word
   997		mlen := int32(0)
   998		if m != 0 {
   999			mlen = maplen(m)
  1000		}
  1001		it := mapiterinit(iv.typ.runtimeType(), m)
  1002		a := make([]Value, mlen)
  1003		var i int
  1004		for i = 0; i < len(a); i++ {
  1005			keyWord, ok := mapiterkey(it)
  1006			if !ok {
  1007				break
  1008			}
  1009			a[i] = valueFromIword(flag, keyType, keyWord)
  1010			mapiternext(it)
  1011		}
  1012		return a[:i]
  1013	}
  1014	
  1015	// Method returns a function value corresponding to v's i'th method.
  1016	// The arguments to a Call on the returned function should not include
  1017	// a receiver; the returned function will always use v as the receiver.
  1018	// Method panics if i is out of range.
  1019	func (v Value) Method(i int) Value {
  1020		iv := v.internal()
  1021		if iv.kind == Invalid {
  1022			panic(&ValueError{"reflect.Value.Method", Invalid})
  1023		}
  1024		if i < 0 || i >= iv.typ.NumMethod() {
  1025			panic("reflect: Method index out of range")
  1026		}
  1027		return Value{v.Internal, i + 1}
  1028	}
  1029	
  1030	// NumMethod returns the number of methods in the value's method set.
  1031	func (v Value) NumMethod() int {
  1032		iv := v.internal()
  1033		if iv.kind == Invalid {
  1034			panic(&ValueError{"reflect.Value.NumMethod", Invalid})
  1035		}
  1036		return iv.typ.NumMethod()
  1037	}
  1038	
  1039	// MethodByName returns a function value corresponding to the method
  1040	// of v with the given name.
  1041	// The arguments to a Call on the returned function should not include
  1042	// a receiver; the returned function will always use v as the receiver.
  1043	// It returns the zero Value if no method was found.
  1044	func (v Value) MethodByName(name string) Value {
  1045		iv := v.internal()
  1046		if iv.kind == Invalid {
  1047			panic(&ValueError{"reflect.Value.MethodByName", Invalid})
  1048		}
  1049		m, ok := iv.typ.MethodByName(name)
  1050		if ok {
  1051			return Value{v.Internal, m.Index + 1}
  1052		}
  1053		return Value{}
  1054	}
  1055	
  1056	// NumField returns the number of fields in the struct v.
  1057	// It panics if v's Kind is not Struct.
  1058	func (v Value) NumField() int {
  1059		iv := v.internal()
  1060		iv.mustBe(Struct)
  1061		return iv.typ.NumField()
  1062	}
  1063	
  1064	// OverflowComplex returns true if the complex128 x cannot be represented by v's type.
  1065	// It panics if v's Kind is not Complex64 or Complex128.
  1066	func (v Value) OverflowComplex(x complex128) bool {
  1067		iv := v.internal()
  1068		switch iv.kind {
  1069		case Complex64:
  1070			return overflowFloat32(real(x)) || overflowFloat32(imag(x))
  1071		case Complex128:
  1072			return false
  1073		}
  1074		panic(&ValueError{"reflect.Value.OverflowComplex", iv.kind})
  1075	}
  1076	
  1077	// OverflowFloat returns true if the float64 x cannot be represented by v's type.
  1078	// It panics if v's Kind is not Float32 or Float64.
  1079	func (v Value) OverflowFloat(x float64) bool {
  1080		iv := v.internal()
  1081		switch iv.kind {
  1082		case Float32:
  1083			return overflowFloat32(x)
  1084		case Float64:
  1085			return false
  1086		}
  1087		panic(&ValueError{"reflect.Value.OverflowFloat", iv.kind})
  1088	}
  1089	
  1090	func overflowFloat32(x float64) bool {
  1091		if x < 0 {
  1092			x = -x
  1093		}
  1094		return math.MaxFloat32 <= x && x <= math.MaxFloat64
  1095	}
  1096	
  1097	// OverflowInt returns true if the int64 x cannot be represented by v's type.
  1098	// It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
  1099	func (v Value) OverflowInt(x int64) bool {
  1100		iv := v.internal()
  1101		switch iv.kind {
  1102		case Int, Int8, Int16, Int32, Int64:
  1103			bitSize := iv.typ.size * 8
  1104			trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1105			return x != trunc
  1106		}
  1107		panic(&ValueError{"reflect.Value.OverflowInt", iv.kind})
  1108	}
  1109	
  1110	// OverflowUint returns true if the uint64 x cannot be represented by v's type.
  1111	// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  1112	func (v Value) OverflowUint(x uint64) bool {
  1113		iv := v.internal()
  1114		switch iv.kind {
  1115		case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
  1116			bitSize := iv.typ.size * 8
  1117			trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1118			return x != trunc
  1119		}
  1120		panic(&ValueError{"reflect.Value.OverflowUint", iv.kind})
  1121	}
  1122	
  1123	// Pointer returns v's value as a uintptr.
  1124	// It returns uintptr instead of unsafe.Pointer so that
  1125	// code using reflect cannot obtain unsafe.Pointers
  1126	// without importing the unsafe package explicitly.
  1127	// It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
  1128	func (v Value) Pointer() uintptr {
  1129		iv := v.internal()
  1130		switch iv.kind {
  1131		case Chan, Func, Map, Ptr, UnsafePointer:
  1132			if iv.kind == Func && v.InternalMethod != 0 {
  1133				panic("reflect.Value.Pointer of method Value")
  1134			}
  1135			return uintptr(iv.word)
  1136		case Slice:
  1137			return (*SliceHeader)(iv.addr).Data
  1138		}
  1139		panic(&ValueError{"reflect.Value.Pointer", iv.kind})
  1140	}
  1141	
  1142	// Recv receives and returns a value from the channel v.
  1143	// It panics if v's Kind is not Chan.
  1144	// The receive blocks until a value is ready.
  1145	// The boolean value ok is true if the value x corresponds to a send
  1146	// on the channel, false if it is a zero value received because the channel is closed.
  1147	func (v Value) Recv() (x Value, ok bool) {
  1148		iv := v.internal()
  1149		iv.mustBe(Chan)
  1150		iv.mustBeExported()
  1151		return iv.recv(false)
  1152	}
  1153	
  1154	// internal recv, possibly non-blocking (nb)
  1155	func (iv internalValue) recv(nb bool) (val Value, ok bool) {
  1156		t := iv.typ.toType()
  1157		if t.ChanDir()&RecvDir == 0 {
  1158			panic("recv on send-only channel")
  1159		}
  1160		ch := iv.word
  1161		if ch == 0 {
  1162			panic("recv on nil channel")
  1163		}
  1164		valWord, selected, ok := chanrecv(iv.typ.runtimeType(), ch, nb)
  1165		if selected {
  1166			val = valueFromIword(0, t.Elem(), valWord)
  1167		}
  1168		return
  1169	}
  1170	
  1171	// Send sends x on the channel v.
  1172	// It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
  1173	// As in Go, x's value must be assignable to the channel's element type.
  1174	func (v Value) Send(x Value) {
  1175		iv := v.internal()
  1176		iv.mustBe(Chan)
  1177		iv.mustBeExported()
  1178		iv.send(x, false)
  1179	}
  1180	
  1181	// internal send, possibly non-blocking
  1182	func (iv internalValue) send(x Value, nb bool) (selected bool) {
  1183		t := iv.typ.toType()
  1184		if t.ChanDir()&SendDir == 0 {
  1185			panic("send on recv-only channel")
  1186		}
  1187		ix := x.internal()
  1188		ix.mustBeExported() // do not let unexported x leak
  1189		ix = convertForAssignment("reflect.Value.Send", nil, t.Elem(), ix)
  1190		ch := iv.word
  1191		if ch == 0 {
  1192			panic("send on nil channel")
  1193		}
  1194		return chansend(iv.typ.runtimeType(), ch, ix.word, nb)
  1195	}
  1196	
  1197	// Set assigns x to the value v.
  1198	// It panics if CanSet returns false.
  1199	// As in Go, x's value must be assignable to v's type.
  1200	func (v Value) Set(x Value) {
  1201		iv := v.internal()
  1202		ix := x.internal()
  1203	
  1204		iv.mustBeAssignable()
  1205		ix.mustBeExported() // do not let unexported x leak
  1206	
  1207		ix = convertForAssignment("reflect.Set", iv.addr, iv.typ, ix)
  1208	
  1209		n := ix.typ.size
  1210		if n <= ptrSize {
  1211			storeIword(iv.addr, ix.word, n)
  1212		} else {
  1213			memmove(iv.addr, ix.addr, n)
  1214		}
  1215	}
  1216	
  1217	// SetBool sets v's underlying value.
  1218	// It panics if v's Kind is not Bool or if CanSet() is false.
  1219	func (v Value) SetBool(x bool) {
  1220		iv := v.internal()
  1221		iv.mustBeAssignable()
  1222		iv.mustBe(Bool)
  1223		*(*bool)(iv.addr) = x
  1224	}
  1225	
  1226	// SetComplex sets v's underlying value to x.
  1227	// It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
  1228	func (v Value) SetComplex(x complex128) {
  1229		iv := v.internal()
  1230		iv.mustBeAssignable()
  1231		switch iv.kind {
  1232		default:
  1233			panic(&ValueError{"reflect.Value.SetComplex", iv.kind})
  1234		case Complex64:
  1235			*(*complex64)(iv.addr) = complex64(x)
  1236		case Complex128:
  1237			*(*complex128)(iv.addr) = x
  1238		}
  1239	}
  1240	
  1241	// SetFloat sets v's underlying value to x.
  1242	// It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
  1243	func (v Value) SetFloat(x float64) {
  1244		iv := v.internal()
  1245		iv.mustBeAssignable()
  1246		switch iv.kind {
  1247		default:
  1248			panic(&ValueError{"reflect.Value.SetFloat", iv.kind})
  1249		case Float32:
  1250			*(*float32)(iv.addr) = float32(x)
  1251		case Float64:
  1252			*(*float64)(iv.addr) = x
  1253		}
  1254	}
  1255	
  1256	// SetInt sets v's underlying value to x.
  1257	// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
  1258	func (v Value) SetInt(x int64) {
  1259		iv := v.internal()
  1260		iv.mustBeAssignable()
  1261		switch iv.kind {
  1262		default:
  1263			panic(&ValueError{"reflect.Value.SetInt", iv.kind})
  1264		case Int:
  1265			*(*int)(iv.addr) = int(x)
  1266		case Int8:
  1267			*(*int8)(iv.addr) = int8(x)
  1268		case Int16:
  1269			*(*int16)(iv.addr) = int16(x)
  1270		case Int32:
  1271			*(*int32)(iv.addr) = int32(x)
  1272		case Int64:
  1273			*(*int64)(iv.addr) = x
  1274		}
  1275	}
  1276	
  1277	// SetLen sets v's length to n.
  1278	// It panics if v's Kind is not Slice.
  1279	func (v Value) SetLen(n int) {
  1280		iv := v.internal()
  1281		iv.mustBeAssignable()
  1282		iv.mustBe(Slice)
  1283		s := (*SliceHeader)(iv.addr)
  1284		if n < 0 || n > int(s.Cap) {
  1285			panic("reflect: slice length out of range in SetLen")
  1286		}
  1287		s.Len = n
  1288	}
  1289	
  1290	// SetMapIndex sets the value associated with key in the map v to val.
  1291	// It panics if v's Kind is not Map.
  1292	// If val is the zero Value, SetMapIndex deletes the key from the map.
  1293	// As in Go, key's value must be assignable to the map's key type,
  1294	// and val's value must be assignable to the map's value type.
  1295	func (v Value) SetMapIndex(key, val Value) {
  1296		iv := v.internal()
  1297		ikey := key.internal()
  1298		ival := val.internal()
  1299	
  1300		iv.mustBe(Map)
  1301		iv.mustBeExported()
  1302	
  1303		ikey.mustBeExported()
  1304		ikey = convertForAssignment("reflect.Value.SetMapIndex", nil, iv.typ.Key(), ikey)
  1305	
  1306		if ival.kind != Invalid {
  1307			ival.mustBeExported()
  1308			ival = convertForAssignment("reflect.Value.SetMapIndex", nil, iv.typ.Elem(), ival)
  1309		}
  1310	
  1311		mapassign(iv.typ.runtimeType(), iv.word, ikey.word, ival.word, ival.kind != Invalid)
  1312	}
  1313	
  1314	// SetUint sets v's underlying value to x.
  1315	// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
  1316	func (v Value) SetUint(x uint64) {
  1317		iv := v.internal()
  1318		iv.mustBeAssignable()
  1319		switch iv.kind {
  1320		default:
  1321			panic(&ValueError{"reflect.Value.SetUint", iv.kind})
  1322		case Uint:
  1323			*(*uint)(iv.addr) = uint(x)
  1324		case Uint8:
  1325			*(*uint8)(iv.addr) = uint8(x)
  1326		case Uint16:
  1327			*(*uint16)(iv.addr) = uint16(x)
  1328		case Uint32:
  1329			*(*uint32)(iv.addr) = uint32(x)
  1330		case Uint64:
  1331			*(*uint64)(iv.addr) = x
  1332		case Uintptr:
  1333			*(*uintptr)(iv.addr) = uintptr(x)
  1334		}
  1335	}
  1336	
  1337	// SetPointer sets the unsafe.Pointer value v to x.
  1338	// It panics if v's Kind is not UnsafePointer.
  1339	func (v Value) SetPointer(x unsafe.Pointer) {
  1340		iv := v.internal()
  1341		iv.mustBeAssignable()
  1342		iv.mustBe(UnsafePointer)
  1343		*(*unsafe.Pointer)(iv.addr) = x
  1344	}
  1345	
  1346	// SetString sets v's underlying value to x.
  1347	// It panics if v's Kind is not String or if CanSet() is false.
  1348	func (v Value) SetString(x string) {
  1349		iv := v.internal()
  1350		iv.mustBeAssignable()
  1351		iv.mustBe(String)
  1352		*(*string)(iv.addr) = x
  1353	}
  1354	
  1355	// Slice returns a slice of v.
  1356	// It panics if v's Kind is not Array or Slice.
  1357	func (v Value) Slice(beg, end int) Value {
  1358		iv := v.internal()
  1359		if iv.kind != Array && iv.kind != Slice {
  1360			panic(&ValueError{"reflect.Value.Slice", iv.kind})
  1361		}
  1362		cap := v.Cap()
  1363		if beg < 0 || end < beg || end > cap {
  1364			panic("reflect.Value.Slice: slice index out of bounds")
  1365		}
  1366		var typ Type
  1367		var base uintptr
  1368		switch iv.kind {
  1369		case Array:
  1370			if iv.flag&flagAddr == 0 {
  1371				panic("reflect.Value.Slice: slice of unaddressable array")
  1372			}
  1373			typ = toType((*arrayType)(unsafe.Pointer(iv.typ)).slice)
  1374			base = uintptr(iv.addr)
  1375		case Slice:
  1376			typ = iv.typ.toType()
  1377			base = (*SliceHeader)(iv.addr).Data
  1378		}
  1379		s := new(SliceHeader)
  1380		s.Data = base + uintptr(beg)*typ.Elem().Size()
  1381		s.Len = end - beg
  1382		s.Cap = cap - beg
  1383		return valueFromAddr(iv.flag&flagRO, typ, unsafe.Pointer(s))
  1384	}
  1385	
  1386	// String returns the string v's underlying value, as a string.
  1387	// String is a special case because of Go's String method convention.
  1388	// Unlike the other getters, it does not panic if v's Kind is not String.
  1389	// Instead, it returns a string of the form "<T value>" where T is v's type.
  1390	func (v Value) String() string {
  1391		iv := v.internal()
  1392		switch iv.kind {
  1393		case Invalid:
  1394			return "<invalid Value>"
  1395		case String:
  1396			return *(*string)(iv.addr)
  1397		}
  1398		return "<" + iv.typ.String() + " Value>"
  1399	}
  1400	
  1401	// TryRecv attempts to receive a value from the channel v but will not block.
  1402	// It panics if v's Kind is not Chan.
  1403	// If the receive cannot finish without blocking, x is the zero Value.
  1404	// The boolean ok is true if the value x corresponds to a send
  1405	// on the channel, false if it is a zero value received because the channel is closed.
  1406	func (v Value) TryRecv() (x Value, ok bool) {
  1407		iv := v.internal()
  1408		iv.mustBe(Chan)
  1409		iv.mustBeExported()
  1410		return iv.recv(true)
  1411	}
  1412	
  1413	// TrySend attempts to send x on the channel v but will not block.
  1414	// It panics if v's Kind is not Chan.
  1415	// It returns true if the value was sent, false otherwise.
  1416	// As in Go, x's value must be assignable to the channel's element type.
  1417	func (v Value) TrySend(x Value) bool {
  1418		iv := v.internal()
  1419		iv.mustBe(Chan)
  1420		iv.mustBeExported()
  1421		return iv.send(x, true)
  1422	}
  1423	
  1424	// Type returns v's type.
  1425	func (v Value) Type() Type {
  1426		t := v.internal().typ
  1427		if t == nil {
  1428			panic(&ValueError{"reflect.Value.Type", Invalid})
  1429		}
  1430		return t.toType()
  1431	}
  1432	
  1433	// Uint returns v's underlying value, as a uint64.
  1434	// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  1435	func (v Value) Uint() uint64 {
  1436		iv := v.internal()
  1437		switch iv.kind {
  1438		case Uint:
  1439			return uint64(*(*uint)(unsafe.Pointer(&iv.word)))
  1440		case Uint8:
  1441			return uint64(*(*uint8)(unsafe.Pointer(&iv.word)))
  1442		case Uint16:
  1443			return uint64(*(*uint16)(unsafe.Pointer(&iv.word)))
  1444		case Uint32:
  1445			return uint64(*(*uint32)(unsafe.Pointer(&iv.word)))
  1446		case Uintptr:
  1447			return uint64(*(*uintptr)(unsafe.Pointer(&iv.word)))
  1448		case Uint64:
  1449			if iv.addr == nil {
  1450				return *(*uint64)(unsafe.Pointer(&iv.word))
  1451			}
  1452			return *(*uint64)(iv.addr)
  1453		}
  1454		panic(&ValueError{"reflect.Value.Uint", iv.kind})
  1455	}
  1456	
  1457	// UnsafeAddr returns a pointer to v's data.
  1458	// It is for advanced clients that also import the "unsafe" package.
  1459	// It panics if v is not addressable.
  1460	func (v Value) UnsafeAddr() uintptr {
  1461		iv := v.internal()
  1462		if iv.kind == Invalid {
  1463			panic(&ValueError{"reflect.Value.UnsafeAddr", iv.kind})
  1464		}
  1465		if iv.flag&flagAddr == 0 {
  1466			panic("reflect.Value.UnsafeAddr of unaddressable value")
  1467		}
  1468		return uintptr(iv.addr)
  1469	}
  1470	
  1471	// StringHeader is the runtime representation of a string.
  1472	// It cannot be used safely or portably.
  1473	type StringHeader struct {
  1474		Data uintptr
  1475		Len  int
  1476	}
  1477	
  1478	// SliceHeader is the runtime representation of a slice.
  1479	// It cannot be used safely or portably.
  1480	type SliceHeader struct {
  1481		Data uintptr
  1482		Len  int
  1483		Cap  int
  1484	}
  1485	
  1486	func typesMustMatch(what string, t1, t2 Type) {
  1487		if t1 != t2 {
  1488			panic("reflect: " + what + ": " + t1.String() + " != " + t2.String())
  1489		}
  1490	}
  1491	
  1492	// grow grows the slice s so that it can hold extra more values, allocating
  1493	// more capacity if needed. It also returns the old and new slice lengths.
  1494	func grow(s Value, extra int) (Value, int, int) {
  1495		i0 := s.Len()
  1496		i1 := i0 + extra
  1497		if i1 < i0 {
  1498			panic("reflect.Append: slice overflow")
  1499		}
  1500		m := s.Cap()
  1501		if i1 <= m {
  1502			return s.Slice(0, i1), i0, i1
  1503		}
  1504		if m == 0 {
  1505			m = extra
  1506		} else {
  1507			for m < i1 {
  1508				if i0 < 1024 {
  1509					m += m
  1510				} else {
  1511					m += m / 4
  1512				}
  1513			}
  1514		}
  1515		t := MakeSlice(s.Type(), i1, m)
  1516		Copy(t, s)
  1517		return t, i0, i1
  1518	}
  1519	
  1520	// Append appends the values x to a slice s and returns the resulting slice.
  1521	// As in Go, each x's value must be assignable to the slice's element type.
  1522	func Append(s Value, x ...Value) Value {
  1523		s.internal().mustBe(Slice)
  1524		s, i0, i1 := grow(s, len(x))
  1525		for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
  1526			s.Index(i).Set(x[j])
  1527		}
  1528		return s
  1529	}
  1530	
  1531	// AppendSlice appends a slice t to a slice s and returns the resulting slice.
  1532	// The slices s and t must have the same element type.
  1533	func AppendSlice(s, t Value) Value {
  1534		s.internal().mustBe(Slice)
  1535		t.internal().mustBe(Slice)
  1536		typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
  1537		s, i0, i1 := grow(s, t.Len())
  1538		Copy(s.Slice(i0, i1), t)
  1539		return s
  1540	}
  1541	
  1542	// Copy copies the contents of src into dst until either
  1543	// dst has been filled or src has been exhausted.
  1544	// It returns the number of elements copied.
  1545	// Dst and src each must have kind Slice or Array, and
  1546	// dst and src must have the same element type.
  1547	func Copy(dst, src Value) int {
  1548		idst := dst.internal()
  1549		isrc := src.internal()
  1550	
  1551		if idst.kind != Array && idst.kind != Slice {
  1552			panic(&ValueError{"reflect.Copy", idst.kind})
  1553		}
  1554		if idst.kind == Array {
  1555			idst.mustBeAssignable()
  1556		}
  1557		idst.mustBeExported()
  1558		if isrc.kind != Array && isrc.kind != Slice {
  1559			panic(&ValueError{"reflect.Copy", isrc.kind})
  1560		}
  1561		isrc.mustBeExported()
  1562	
  1563		de := idst.typ.Elem()
  1564		se := isrc.typ.Elem()
  1565		typesMustMatch("reflect.Copy", de, se)
  1566	
  1567		n := dst.Len()
  1568		if sn := src.Len(); n > sn {
  1569			n = sn
  1570		}
  1571	
  1572		// If sk is an in-line array, cannot take its address.
  1573		// Instead, copy element by element.
  1574		if isrc.addr == nil {
  1575			for i := 0; i < n; i++ {
  1576				dst.Index(i).Set(src.Index(i))
  1577			}
  1578			return n
  1579		}
  1580	
  1581		// Copy via memmove.
  1582		var da, sa unsafe.Pointer
  1583		if idst.kind == Array {
  1584			da = idst.addr
  1585		} else {
  1586			da = unsafe.Pointer((*SliceHeader)(idst.addr).Data)
  1587		}
  1588		if isrc.kind == Array {
  1589			sa = isrc.addr
  1590		} else {
  1591			sa = unsafe.Pointer((*SliceHeader)(isrc.addr).Data)
  1592		}
  1593		memmove(da, sa, uintptr(n)*de.Size())
  1594		return n
  1595	}
  1596	
  1597	/*
  1598	 * constructors
  1599	 */
  1600	
  1601	// MakeSlice creates a new zero-initialized slice value
  1602	// for the specified slice type, length, and capacity.
  1603	func MakeSlice(typ Type, len, cap int) Value {
  1604		if typ.Kind() != Slice {
  1605			panic("reflect: MakeSlice of non-slice type")
  1606		}
  1607		s := &SliceHeader{
  1608			Data: uintptr(unsafe.NewArray(typ.Elem(), cap)),
  1609			Len:  len,
  1610			Cap:  cap,
  1611		}
  1612		return valueFromAddr(0, typ, unsafe.Pointer(s))
  1613	}
  1614	
  1615	// MakeChan creates a new channel with the specified type and buffer size.
  1616	func MakeChan(typ Type, buffer int) Value {
  1617		if typ.Kind() != Chan {
  1618			panic("reflect: MakeChan of non-chan type")
  1619		}
  1620		if buffer < 0 {
  1621			panic("MakeChan: negative buffer size")
  1622		}
  1623		if typ.ChanDir() != BothDir {
  1624			panic("MakeChan: unidirectional channel type")
  1625		}
  1626		ch := makechan(typ.runtimeType(), uint32(buffer))
  1627		return valueFromIword(0, typ, ch)
  1628	}
  1629	
  1630	// MakeMap creates a new map of the specified type.
  1631	func MakeMap(typ Type) Value {
  1632		if typ.Kind() != Map {
  1633			panic("reflect: MakeMap of non-map type")
  1634		}
  1635		m := makemap(typ.runtimeType())
  1636		return valueFromIword(0, typ, m)
  1637	}
  1638	
  1639	// Indirect returns the value that v points to.
  1640	// If v is a nil pointer, Indirect returns a nil Value.
  1641	// If v is not a pointer, Indirect returns v.
  1642	func Indirect(v Value) Value {
  1643		if v.Kind() != Ptr {
  1644			return v
  1645		}
  1646		return v.Elem()
  1647	}
  1648	
  1649	// ValueOf returns a new Value initialized to the concrete value
  1650	// stored in the interface i.  ValueOf(nil) returns the zero Value.
  1651	func ValueOf(i interface{}) Value {
  1652		if i == nil {
  1653			return Value{}
  1654		}
  1655		// For an interface value with the noAddr bit set,
  1656		// the representation is identical to an empty interface.
  1657		eface := *(*emptyInterface)(unsafe.Pointer(&i))
  1658		return packValue(0, eface.typ, eface.word)
  1659	}
  1660	
  1661	// Zero returns a Value representing a zero value for the specified type.
  1662	// The result is different from the zero value of the Value struct,
  1663	// which represents no value at all.
  1664	// For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
  1665	func Zero(typ Type) Value {
  1666		if typ == nil {
  1667			panic("reflect: Zero(nil)")
  1668		}
  1669		if typ.Size() <= ptrSize {
  1670			return valueFromIword(0, typ, 0)
  1671		}
  1672		return valueFromAddr(0, typ, unsafe.New(typ))
  1673	}
  1674	
  1675	// New returns a Value representing a pointer to a new zero value
  1676	// for the specified type.  That is, the returned Value's Type is PtrTo(t).
  1677	func New(typ Type) Value {
  1678		if typ == nil {
  1679			panic("reflect: New(nil)")
  1680		}
  1681		ptr := unsafe.New(typ)
  1682		return valueFromIword(0, PtrTo(typ), iword(ptr))
  1683	}
  1684	
  1685	// convertForAssignment 
  1686	func convertForAssignment(what string, addr unsafe.Pointer, dst Type, iv internalValue) internalValue {
  1687		if iv.method {
  1688			panic(what + ": cannot assign method value to type " + dst.String())
  1689		}
  1690	
  1691		dst1 := dst.(*commonType)
  1692		if directlyAssignable(dst1, iv.typ) {
  1693			// Overwrite type so that they match.
  1694			// Same memory layout, so no harm done.
  1695			iv.typ = dst1
  1696			return iv
  1697		}
  1698		if implements(dst1, iv.typ) {
  1699			if addr == nil {
  1700				addr = unsafe.Pointer(new(interface{}))
  1701			}
  1702			x := iv.valueInterface(false)
  1703			if dst.NumMethod() == 0 {
  1704				*(*interface{})(addr) = x
  1705			} else {
  1706				ifaceE2I(dst1.runtimeType(), x, addr)
  1707			}
  1708			iv.addr = addr
  1709			iv.word = iword(addr)
  1710			iv.typ = dst1
  1711			return iv
  1712		}
  1713	
  1714		// Failed.
  1715		panic(what + ": value of type " + iv.typ.String() + " is not assignable to type " + dst.String())
  1716	}
  1717	
  1718	// implemented in ../pkg/runtime
  1719	func chancap(ch iword) int32
  1720	func chanclose(ch iword)
  1721	func chanlen(ch iword) int32
  1722	func chanrecv(t *runtime.Type, ch iword, nb bool) (val iword, selected, received bool)
  1723	func chansend(t *runtime.Type, ch iword, val iword, nb bool) bool
  1724	
  1725	func makechan(typ *runtime.Type, size uint32) (ch iword)
  1726	func makemap(t *runtime.Type) iword
  1727	func mapaccess(t *runtime.Type, m iword, key iword) (val iword, ok bool)
  1728	func mapassign(t *runtime.Type, m iword, key, val iword, ok bool)
  1729	func mapiterinit(t *runtime.Type, m iword) *byte
  1730	func mapiterkey(it *byte) (key iword, ok bool)
  1731	func mapiternext(it *byte)
  1732	func maplen(m iword) int32
  1733	
  1734	func call(fn, arg unsafe.Pointer, n uint32)
  1735	func ifaceE2I(t *runtime.Type, src interface{}, dst unsafe.Pointer)

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.