utils: add Go 1.20+ way of converting string to byte slice (#2462)

* utils: add Go 1.20+ way of converting string to byte slice

Ref. d2f97fc426/s2b_old.go.
Ref. d2f97fc426/s2b_new.go.

* utils: fix golangci-lint apparently running with Go < 1.20

See https://github.com/gofiber/fiber/actions/runs/4968641325/jobs/8891360463?pr=2462.
pull/2464/head
leonklingele 2023-05-15 07:21:16 +02:00 committed by GitHub
parent 77c1b4868a
commit eced39c47e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 16 deletions

View File

@ -13,8 +13,6 @@ import (
"unsafe" "unsafe"
) )
const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112)
// UnsafeString returns a string pointer without allocation // UnsafeString returns a string pointer without allocation
// //
//nolint:gosec // unsafe is used for better performance here //nolint:gosec // unsafe is used for better performance here
@ -22,20 +20,6 @@ func UnsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b)) 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 // CopyString copies a string to make it immutable
func CopyString(s string) string { func CopyString(s string) string {
return string(UnsafeBytes(s)) return string(UnsafeBytes(s))

13
utils/convert_s2b_new.go Normal file
View File

@ -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))
}

25
utils/convert_s2b_old.go Normal file
View File

@ -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)]
}