github.com/lemon-mint/libuseful@v1.3.1-0.20220724073654-ee73785d5aa0/reflect.go (about)

     1  package libuseful
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  //go:linkname ToType reflect.toType
     9  func ToType(t unsafe.Pointer) reflect.Type
    10  
    11  //go:linkname TypesByString reflect.typesByString
    12  func TypesByString(s string) []unsafe.Pointer
    13  
    14  func GetOffset(t reflect.Type, f string) (uintptr, bool) {
    15  	field, ok := t.FieldByName(f)
    16  	if !ok {
    17  		return 0, false
    18  	}
    19  	return field.Offset, true
    20  }
    21  
    22  func GetType(name string) reflect.Type {
    23  	types := TypesByString(name)
    24  	if len(types) == 0 {
    25  		return nil
    26  	}
    27  	return ToType(types[0])
    28  }
    29  
    30  func MustGetType(name string) reflect.Type {
    31  	t := GetType(name)
    32  	if t == nil {
    33  		panic("type not found")
    34  	}
    35  	return t
    36  }
    37  
    38  func MustGetOffset(t reflect.Type, f string) uintptr {
    39  	offset, ok := GetOffset(t, f)
    40  	if !ok {
    41  		panic("field not found")
    42  	}
    43  	return offset
    44  }