github.com/sandwich-go/boost@v1.3.29/z/conv.go (about)

     1  package z
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  // StringToBytes converts string to byte slice without a memory allocation.
     9  func StringToBytes(s string) (b []byte) {
    10  	sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
    11  	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    12  	bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len
    13  	return b
    14  }
    15  
    16  // BytesToString converts byte slice to string without a memory allocation.
    17  func BytesToString(b []byte) string {
    18  	return *(*string)(unsafe.Pointer(&b))
    19  }