mirror of
https://github.com/gofiber/fiber.git
synced 2025-05-31 11:52:41 +00:00
utils: add Go 1.20+ way of converting byte slice to string (#2468)
Ref.d2f97fc426/b2s_old.go
. Ref.d2f97fc426/b2s_new.go
.
This commit is contained in:
parent
182f9f0970
commit
fe487934f9
@ -10,16 +10,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// UnsafeString returns a string pointer without allocation
|
||||
//
|
||||
//nolint:gosec // unsafe is used for better performance here
|
||||
func UnsafeString(b []byte) string {
|
||||
return *(*string)(unsafe.Pointer(&b))
|
||||
}
|
||||
|
||||
// CopyString copies a string to make it immutable
|
||||
func CopyString(s string) string {
|
||||
return string(UnsafeBytes(s))
|
||||
|
13
utils/convert_b2s_new.go
Normal file
13
utils/convert_b2s_new.go
Normal file
@ -0,0 +1,13 @@
|
||||
//go:build go1.20
|
||||
// +build go1.20
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// UnsafeString returns a string pointer without allocation
|
||||
func UnsafeString(b []byte) string {
|
||||
return unsafe.String(unsafe.SliceData(b), len(b))
|
||||
}
|
15
utils/convert_b2s_old.go
Normal file
15
utils/convert_b2s_old.go
Normal file
@ -0,0 +1,15 @@
|
||||
//go:build !go1.20
|
||||
// +build !go1.20
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// UnsafeString returns a string pointer without allocation
|
||||
//
|
||||
//nolint:gosec // unsafe is used for better performance here
|
||||
func UnsafeString(b []byte) string {
|
||||
return *(*string)(unsafe.Pointer(&b))
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user