Skip to content

Instantly share code, notes, and snippets.

@yakuter
Created July 28, 2020 00:07
Show Gist options
  • Select an option

  • Save yakuter/c0df0f4253ea639529f3589e99dc940b to your computer and use it in GitHub Desktop.

Select an option

Save yakuter/c0df0f4253ea639529f3589e99dc940b to your computer and use it in GitHub Desktop.
String Byte Conversion Without Memory Allocation
// b2s converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func b2s(b []byte) string {
/* #nosec G103 */
return *(*string)(unsafe.Pointer(&b))
}
// s2b converts string to a byte slice without memory allocation.
//
// Note it may break if string and/or slice header will change
// in the future go versions.
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.Len = sh.Len
bh.Cap = sh.Len
return b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment