Skip to content

Commit

Permalink
Merge pull request #204 from jlauinger/fix-unsafe-slice-cast
Browse files Browse the repository at this point in the history
Fix possible memory confusion in unsafe slice cast
  • Loading branch information
AllenX2018 committed Jun 3, 2020
2 parents 84562f4 + a04c0ec commit 4eafe9b
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions bytes_unsafe.go
Expand Up @@ -6,6 +6,7 @@ import (
"reflect"
"strconv"
"unsafe"
"runtime"
)

//
Expand All @@ -32,11 +33,12 @@ func bytesToString(b *[]byte) string {
}

func StringToBytes(s string) []byte {
b := make([]byte, 0, 0)
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
return *(*[]byte)(unsafe.Pointer(&bh))
bh.Data = sh.Data
bh.Cap = sh.Len
bh.Len = sh.Len
runtime.KeepAlive(s)
return b
}

0 comments on commit 4eafe9b

Please sign in to comment.