As the unsafe and pointer methods in `reflect` are to be depreciated, and seeing no replacement functions, it is now forced that some unsafe is needed to replace this as when and interface is dereferenced it is made unsettable by reflect. With this in mind, this adds real recursive types by hot swapping the struct field type on the fly. This removes a lot of compensation code, simplifying all previous cases. **Note:** While the struct field type is swapped for the real type, the type string is not changed. Due to this, unsafe will recreate the same type.
53 lines
958 B
Go
53 lines
958 B
Go
package unsafe2
|
|
|
|
import (
|
|
"reflect"
|
|
"unsafe"
|
|
)
|
|
|
|
type dummy struct{}
|
|
|
|
// DummyType represents a stand-in for a recursive type.
|
|
var DummyType = reflect.TypeOf(dummy{})
|
|
|
|
type rtype struct {
|
|
_ [48]byte
|
|
}
|
|
|
|
type emptyInterface struct {
|
|
typ *rtype
|
|
_ unsafe.Pointer
|
|
}
|
|
|
|
type structField struct {
|
|
_ int64
|
|
typ *rtype
|
|
_ uintptr
|
|
}
|
|
|
|
type structType struct {
|
|
rtype
|
|
_ int64
|
|
fields []structField
|
|
}
|
|
|
|
// SwapFieldType swaps the type of the struct field with the given type.
|
|
//
|
|
// The struct type must have been created at runtime. This is very unsafe.
|
|
func SwapFieldType(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
|
|
}
|