github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/internal/unsafeheader/convert.go (about)

     1  package unsafeheader
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  func StringToBytes(s string) []byte {
     9  	sh := (*StringHeader)(unsafe.Pointer(&s))
    10  	bh := &SliceHeader{
    11  		Data: sh.Data,
    12  		Len:  sh.Len,
    13  		Cap:  sh.Len,
    14  	}
    15  	return *(*[]byte)(unsafe.Pointer(bh))
    16  }
    17  
    18  func BytesToString(b []byte) string {
    19  	return *(*string)(unsafe.Pointer(&b))
    20  }
    21  
    22  // ToEface casts an empty interface{} value to an Eface value.
    23  func ToEface(ep *any) Eface {
    24  	return *(*Eface)(unsafe.Pointer(ep))
    25  }
    26  
    27  // ToIface casts a [reflect.Type] to an Iface value.
    28  func ToIface(t reflect.Type) Iface {
    29  	return *(*Iface)(unsafe.Pointer(&t))
    30  }
    31  
    32  // ToRType gets the underlying [*reflect.rtype] from a [reflect.Type].
    33  func ToRType(t reflect.Type) unsafe.Pointer {
    34  	return (*Iface)(unsafe.Pointer(&t)).Data
    35  }
    36  
    37  // ToReflectType convert an [*reflect.rtype] pointer to a [reflect.Type] value.
    38  // It is the reverse operation of ToRType.
    39  func ToReflectType(rtype unsafe.Pointer) reflect.Type {
    40  	t := reflectTypeTmpl
    41  	t.Data = rtype
    42  	return *(*reflect.Type)(unsafe.Pointer(&t))
    43  }
    44  
    45  var reflectTypeTmpl Iface
    46  
    47  func init() {
    48  	sampleTyp := reflect.TypeOf(0)
    49  	reflectTypeTmpl = *(*Iface)(unsafe.Pointer(&sampleTyp))
    50  }