Debian Codegraph @

internal/unsafe2/go1_20_unsafe.go

raw symbols SCIP
1 //go:build !go1.21
2 // +build !go1.21
3
4 // Package unsafe2 provides helpers to generate recursive struct types.
5 package unsafe2
6
7 import (
8 "reflect"
9 "unsafe"
10 )
11
12 type dummy struct{}
13
14 // DummyType represents a stand-in for a recursive type.
15 var DummyType = reflect.TypeOf(dummy{})
16
17 // the following type sizes must match their original definition in Go src/reflect/type.go.
18
19 type rtype struct {
20 _ uintptr
21 _ uintptr
22 _ uint32
23 _ uint32
24 _ uintptr
25 _ uintptr
26 _ uint32
27 _ uint32
28 }
29
30 type emptyInterface struct {
31 typ *rtype
32 _ unsafe.Pointer
33 }
34
35 type structField struct {
36 _ uintptr
37 typ *rtype
38 _ uintptr
39 }
40
41 type structType struct {
42 rtype
43 _ uintptr
44 fields []structField
45 }
46
47 // SetFieldType sets the type of the struct field at the given index, to the given type.
48 //
49 // The struct type must have been created at runtime. This is very unsafe.
50 func SetFieldType(s reflect.Type, idx int, t reflect.Type) {
51 if s.Kind() != reflect.Struct || idx >= s.NumField() {
52 return
53 }
54
55 rtyp := unpackType(s)
56 styp := (*structType)(unsafe.Pointer(rtyp))
57 f := styp.fields[idx]
58 f.typ = unpackType(t)
59 styp.fields[idx] = f
60 }
61
62 func unpackType(t reflect.Type) *rtype {
63 v := reflect.New(t).Elem().Interface()
64 return (*emptyInterface)(unsafe.Pointer(&v)).typ
65 }