File: go1_20_unsafe.go

package info (click to toggle)
golang-github-traefik-yaegi 0.16.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,608 kB
  • sloc: sh: 457; makefile: 39
file content (65 lines) | stat: -rw-r--r-- 1,252 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//go:build !go1.21
// +build !go1.21

// Package unsafe2 provides helpers to generate recursive struct types.
package unsafe2

import (
	"reflect"
	"unsafe"
)

type dummy struct{}

// DummyType represents a stand-in for a recursive type.
var DummyType = reflect.TypeOf(dummy{})

// the following type sizes must match their original definition in Go src/reflect/type.go.

type rtype struct {
	_ uintptr
	_ uintptr
	_ uint32
	_ uint32
	_ uintptr
	_ uintptr
	_ uint32
	_ uint32
}

type emptyInterface struct {
	typ *rtype
	_   unsafe.Pointer
}

type structField struct {
	_   uintptr
	typ *rtype
	_   uintptr
}

type structType struct {
	rtype
	_      uintptr
	fields []structField
}

// SetFieldType sets the type of the struct field at the given index, to the given type.
//
// The struct type must have been created at runtime. This is very unsafe.
func SetFieldType(s reflect.Type, idx int, t reflect.Type) {
	if s.Kind() != reflect.Struct || idx >= s.NumField() {
		return
	}

	rtyp := unpackType(s)
	styp := (*structType)(unsafe.Pointer(rtyp))
	f := styp.fields[idx]
	f.typ = unpackType(t)
	styp.fields[idx] = f
}

func unpackType(t reflect.Type) *rtype {
	v := reflect.New(t).Elem().Interface()
	return (*emptyInterface)(unsafe.Pointer(&v)).typ
}