Merge pull request #134 from jlauinger/fix-unsafe-slice-cast

Fix possible memory confusion in unsafe slice cast
This commit is contained in:
Yusuke Inuzuka 2020-06-04 00:26:44 +09:00 committed by GitHub
commit 6eb3819f4b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -13,8 +13,11 @@ func BytesToReadOnlyString(b []byte) string {
}
// StringToReadOnlyBytes returns bytes converted from given string.
func StringToReadOnlyBytes(s string) []byte {
func StringToReadOnlyBytes(s string) (bs []byte) {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len}
return *(*[]byte)(unsafe.Pointer(&bh))
bh := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
bh.Data = sh.Data
bh.Cap = sh.Len
bh.Len = sh.Len
return
}