fix unsafe.go

This commit is contained in:
FJSDS 2018-01-11 16:07:24 +08:00
parent b879d4e0b9
commit a8340c6b74
1 changed files with 9 additions and 14 deletions

View File

@ -3,25 +3,20 @@
package internal
import (
"reflect"
"unsafe"
)
// BytesToString converts byte slice to string.
func BytesToString(b []byte) string {
bytesHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
strHeader := reflect.StringHeader{
Data: bytesHeader.Data,
Len: bytesHeader.Len,
}
return *(*string)(unsafe.Pointer(&strHeader))
return *(*string)(unsafe.Pointer(&b))
}
// StringToBytes converts string to byte slice.
func StringToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
return *(*[]byte)(unsafe.Pointer(&bh))
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s,len(s)},
))
}