Debian Codegraph @

libgo/go/reflect/value.go

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