diff --git a/utils/convert.go b/utils/convert.go index 233dfbce31..672ea7f42a 100644 --- a/utils/convert.go +++ b/utils/convert.go @@ -13,8 +13,6 @@ import ( "unsafe" ) -const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112) - // UnsafeString returns a string pointer without allocation // //nolint:gosec // unsafe is used for better performance here @@ -22,20 +20,6 @@ func UnsafeString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) } -// UnsafeBytes returns a byte pointer without allocation. -// String length shouldn't be more than 2147418112. -// -//nolint:gosec // unsafe is used for better performance here -func UnsafeBytes(s string) []byte { - if s == "" { - return nil - } - - return (*[MaxStringLen]byte)(unsafe.Pointer( - (*reflect.StringHeader)(unsafe.Pointer(&s)).Data), - )[:len(s):len(s)] -} - // CopyString copies a string to make it immutable func CopyString(s string) string { return string(UnsafeBytes(s)) diff --git a/utils/convert_s2b_new.go b/utils/convert_s2b_new.go new file mode 100644 index 0000000000..abe9a8e82a --- /dev/null +++ b/utils/convert_s2b_new.go @@ -0,0 +1,13 @@ +//go:build go1.20 +// +build go1.20 + +package utils + +import ( + "unsafe" +) + +// UnsafeBytes returns a byte pointer without allocation. +func UnsafeBytes(s string) []byte { + return unsafe.Slice(unsafe.StringData(s), len(s)) +} diff --git a/utils/convert_s2b_old.go b/utils/convert_s2b_old.go new file mode 100644 index 0000000000..e817dc3bee --- /dev/null +++ b/utils/convert_s2b_old.go @@ -0,0 +1,25 @@ +//go:build !go1.20 +// +build !go1.20 + +package utils + +import ( + "reflect" + "unsafe" +) + +const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112) + +// UnsafeBytes returns a byte pointer without allocation. +// String length shouldn't be more than 2147418112. +// +//nolint:gosec // unsafe is used for better performance here +func UnsafeBytes(s string) []byte { + if s == "" { + return nil + } + + return (*[MaxStringLen]byte)(unsafe.Pointer( + (*reflect.StringHeader)(unsafe.Pointer(&s)).Data), + )[:len(s):len(s)] +}