github.com/chaowen112/go-lib@v0.0.0-20231018124935-124cd26d7cbe/byteutils/byteutils.go (about)

     1  package byteutils
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  // b2s converts byte slice to a string without memory allocation.
     9  // See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
    10  //
    11  // Note it may break if string and/or slice header will change
    12  // in the future go versions.
    13  func ToString(b []byte) string {
    14  	return *(*string)(unsafe.Pointer(&b))
    15  }
    16  
    17  // s2b converts string to a byte slice without memory allocation.
    18  //
    19  // Note it may break if string and/or slice header will change
    20  // in the future go versions.
    21  func ToBytes(s string) (b []byte) {
    22  	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    23  	sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
    24  	bh.Data = sh.Data
    25  	bh.Len = sh.Len
    26  	bh.Cap = sh.Len
    27  	return b
    28  }