// 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)
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code