github.com/go-playground/pkg/v5@v5.29.1/unsafe/conversions.go (about) 1 //go:build !go1.21 2 // +build !go1.21 3 4 package unsafeext 5 6 import ( 7 "reflect" 8 "unsafe" 9 ) 10 11 // BytesToString converts an array of bytes into a string without allocating. 12 // The byte slice passed to this function is not to be used after this call as it's unsafe; you have been warned. 13 func BytesToString(b []byte) string { 14 return *(*string)(unsafe.Pointer(&b)) 15 } 16 17 // StringToBytes converts an existing string into an []byte without allocating. 18 // The string passed to this functions is not to be used again after this call as it's unsafe; you have been warned. 19 func StringToBytes(s string) (b []byte) { 20 strHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) 21 sliceHdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 22 sliceHdr.Data = strHdr.Data 23 sliceHdr.Cap = strHdr.Len 24 sliceHdr.Len = strHdr.Len 25 return 26 }