Skip to content

Instantly share code, notes, and snippets.

@e7
Last active October 19, 2021 11:01
Show Gist options
  • Save e7/cfae09272383de11a6cb54bd983ba9fd to your computer and use it in GitHub Desktop.
Save e7/cfae09272383de11a6cb54bd983ba9fd to your computer and use it in GitHub Desktop.
// gin
func StringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// fasthttp
func s2b(s string) (b []byte) {
/* #nosec G103 */
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
/* #nosec G103 */
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Cap = sh.Len
bh.Len = sh.Len
return b
}
func b2s(b []byte) string {
/* #nosec G103 */
return *(*string)(unsafe.Pointer(&b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment