// copy from prometheus source code
// NoAllocString convert []byte to string
func NoAllocString(bytes []byte) string {
return *(*string)(unsafe.Pointer(&bytes))
}
// NoAllocBytes convert string to []byte
func NoAllocBytes(s string) []byte {
strHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
sliceHeader := reflect.SliceHeader{Data: strHeader.Data, Len: strHeader.Len, Cap: strHeader.Len}
return *(*[]byte)(unsafe.Pointer(&sliceHeader))
}
func TestBytesToString(t *testing.T) {
b := []byte("hello world")
s := NoAllocString(b)
fmt.Println(s)
}
func TestStringToBytes(t *testing.T) {
s := "hello world"
b := NoAllocBytes(s)
fmt.Println(b)
}