From c977ec393afb3f8e85cbacd2fd3a54ae89e65db3 Mon Sep 17 00:00:00 2001 From: Ciprian Dorin Craciun Date: Wed, 17 Nov 2021 21:42:36 +0200 Subject: [PATCH] [runtime] Fix `StringToBytes` implementation. --- sources/lib/common/runtime.go | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/sources/lib/common/runtime.go b/sources/lib/common/runtime.go index 7c3d7fc..1cf6797 100644 --- a/sources/lib/common/runtime.go +++ b/sources/lib/common/runtime.go @@ -1,6 +1,7 @@ package common +import "reflect" import "unsafe" @@ -13,11 +14,11 @@ func NoEscape (p unsafe.Pointer) (unsafe.Pointer) { } func NoEscapeBytes (p *[]byte) (*[]byte) { - return (*[]byte) (NoEscape (unsafe.Pointer (&p))) + return (*[]byte) (NoEscape (unsafe.Pointer (p))) } func NoEscapeString (p *string) (*string) { - return (*string) (NoEscape (unsafe.Pointer (&p))) + return (*string) (NoEscape (unsafe.Pointer (p))) } @@ -25,7 +26,18 @@ func BytesToString (b []byte) (string) { return *(*string) (unsafe.Pointer (&b)) } -func StringToBytes (s string) ([]byte) { - return *(*[]byte) (unsafe.Pointer (&s)) +func StringToBytes (_string string) ([]byte) { + + // NOTE: The following is broken! + // return *(*[]byte) (unsafe.Pointer (&_string)) + + // NOTE: Based on `https://github.com/valyala/fasthttp/blob/2a6f7db5bbc4d7c11f1ccc0cb827e145b9b7d7ea/bytesconv.go#L342` + _bytes := []byte (nil) + _bytesHeader := (*reflect.SliceHeader) (unsafe.Pointer (&_bytes)) + _stringHeader := (*reflect.StringHeader) (unsafe.Pointer (&_string)) + _bytesHeader.Data = _stringHeader.Data + _bytesHeader.Len = _stringHeader.Len + _bytesHeader.Cap = _stringHeader.Len + return _bytes }