github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/strings/hack.go (about)

     1  package strings
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  // no copy to change slice to string
     9  // use your own risk
    10  func String(b []byte) (s string) {
    11  	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    12  	pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
    13  	pstring.Data = pbytes.Data
    14  	pstring.Len = pbytes.Len
    15  	return
    16  }
    17  
    18  // no copy to change string to slice
    19  // use your own risk
    20  func Slice(s string) (b []byte) {
    21  	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    22  	pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
    23  	pbytes.Data = pstring.Data
    24  	pbytes.Len = pstring.Len
    25  	pbytes.Cap = pstring.Len
    26  	return
    27  }