mirror of https://github.com/gofiber/fiber.git
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.pull/2464/headd2f97fc426/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.
parent
77c1b4868a
commit
eced39c47e
|
@ -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))
|
||||
|
|
|
@ -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))
|
||||
}
|
|
@ -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)]
|
||||
}
|
Loading…
Reference in New Issue