Security Optimization string to byte slice

This commit is contained in:
todd 2022-10-06 21:31:22 +08:00
parent 78dad9d77d
commit 8c235252b6
1 changed files with 4 additions and 13 deletions

View File

@ -4,21 +4,12 @@
package bytesconv
import (
"unsafe"
)
// StringToBytes converts string to byte slice without a memory allocation.
// StringToBytes converts string to byte slice
func StringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
return []byte(s)
}
// BytesToString converts byte slice to string without a memory allocation.
// BytesToString converts byte slice to string
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
return string(b)
}