github.com/songzhibin97/gkit@v1.2.13/internal/hack/hack.go (about)

     1  package hack
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  // StringToBytes converts a string to a byte slice.
     9  //
    10  // This is a shallow copy, means that the returned byte slice reuse
    11  // the underlying array in string, so you can't change the returned
    12  // byte slice in any situations.
    13  func StringToBytes(s string) (b []byte) {
    14  	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    15  	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
    16  	bh.Data = sh.Data
    17  	bh.Len = sh.Len
    18  	bh.Cap = sh.Len
    19  	return b
    20  }
    21  
    22  // BytesToString converts a byte slice to a string.
    23  //
    24  // This is a shallow copy, means that the returned string reuse the
    25  // underlying array in byte slice, it's your responsibility to keep
    26  // the input byte slice survive until you don't access the string anymore.
    27  func BytesToString(b []byte) string {
    28  	return *(*string)(unsafe.Pointer(&b))
    29  }