From ae39f917f022d87d4af9dd409d906aadb8790196 Mon Sep 17 00:00:00 2001 From: mask-pp Date: Wed, 2 Dec 2020 13:08:13 +0800 Subject: [PATCH] upgrade StringToBytes function --- internal/bytesconv/bytesconv.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/internal/bytesconv/bytesconv.go b/internal/bytesconv/bytesconv.go index 7b80e335..86e4c4d4 100644 --- a/internal/bytesconv/bytesconv.go +++ b/internal/bytesconv/bytesconv.go @@ -5,16 +5,17 @@ package bytesconv import ( - "reflect" "unsafe" ) // StringToBytes converts string to byte slice without a memory allocation. -func StringToBytes(s string) (b []byte) { - sh := *(*reflect.StringHeader)(unsafe.Pointer(&s)) - bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len - return b +func StringToBytes(s string) []byte { + return *(*[]byte)(unsafe.Pointer( + &struct { + string + Cap int + }{s, len(s)}, + )) } // BytesToString converts byte slice to string without a memory allocation.