update util_unsafe.go to use simpler, yet still safe, cast

This commit is contained in:
Johannes Lauinger 2020-06-03 15:45:44 +02:00 committed by GitHub
parent 813d953eeb
commit 2141537561
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,7 +4,6 @@ package util
import ( import (
"reflect" "reflect"
"runtime"
"unsafe" "unsafe"
) )
@ -14,13 +13,11 @@ func BytesToReadOnlyString(b []byte) string {
} }
// StringToReadOnlyBytes returns bytes converted from given string. // StringToReadOnlyBytes returns bytes converted from given string.
func StringToReadOnlyBytes(s string) []byte { func StringToReadOnlyBytes(s string) (bs []byte) {
b := make([]byte, 0)
sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) bh := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
bh.Data = sh.Data bh.Data = sh.Data
bh.Cap = sh.Len bh.Cap = sh.Len
bh.Len = sh.Len bh.Len = sh.Len
runtime.KeepAlive(s) return
return b
} }