Debian Codegraph @

internal/runtime/rtype.go

raw
1 package runtime
2
3 import (
4 "reflect"
5 "unsafe"
6 )
7
8 type emptyInterface struct {
9 typ unsafe.Pointer
10 ptr unsafe.Pointer
11 }
12
13 // TypePtr returns the pointer to the type descriptor of the type.
14 // It is the type word of an interface value which holds a value of the type,
15 // and it is what the functions of the runtime package take as a type.
16 func TypePtr(t reflect.Type) unsafe.Pointer {
17 return (*emptyInterface)(unsafe.Pointer(&t)).ptr
18 }
19
20 // TypeOfPtr converts the pointer to the type descriptor to reflect.Type.
21 // reflect.TypeOf reads only the type word of the interface value, so the data word is left nil.
22 func TypeOfPtr(typ unsafe.Pointer) reflect.Type {
23 return reflect.TypeOf(*(*any)(unsafe.Pointer(&emptyInterface{typ: typ})))
24 }
25
26 // IfaceIndir reports whether a value of the type is stored indirectly in an interface value:
27 // the data word of the interface points to a copy of the value, instead of being the value itself.
28 //
29 // Which types are stored directly is decided by the compiler and the rule depends on the Go version
30 // ( e.g. a struct of a zero-sized field and a pointer is direct since Go 1.26 ), so the rule is not
31 // reimplemented here. Instead, a value whose first word is a known pointer is converted to an interface
32 // value, and the data word tells how it was stored.
33 func IfaceIndir(typ reflect.Type) bool {
34 if typ.Size() != unsafe.Sizeof(unsafe.Pointer(nil)) {
35 // only a pointer-sized value fits in the data word.
36 return true
37 }
38 probe := unsafe.Pointer(new(uintptr))
39 v := reflect.New(typ)
40 *(*unsafe.Pointer)(v.UnsafePointer()) = probe
41 iface := v.Elem().Interface()
42 return (*emptyInterface)(unsafe.Pointer(&iface)).ptr != probe
43 }