mirror of
https://github.com/yuin/goldmark
synced 2025-03-04 23:04:52 +00:00
fix possible memory confusion in unsafe slice cast
This commit is contained in:
parent
3d78558cf2
commit
813d953eeb
1 changed files with 8 additions and 2 deletions
|
|
@ -4,6 +4,7 @@ package util
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"runtime"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -14,7 +15,12 @@ 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) []byte {
|
||||||
|
b := make([]byte, 0)
|
||||||
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
|
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
|
||||||
bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len}
|
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||||
return *(*[]byte)(unsafe.Pointer(&bh))
|
bh.Data = sh.Data
|
||||||
|
bh.Cap = sh.Len
|
||||||
|
bh.Len = sh.Len
|
||||||
|
runtime.KeepAlive(s)
|
||||||
|
return b
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue