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

Ref. d2f97fc426/b2s_old.go.
Ref. d2f97fc426/b2s_new.go.
pull/2473/head
leonklingele 2023-05-19 11:07:20 +02:00 committed by GitHub
parent 182f9f0970
commit fe487934f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 8 deletions

View File

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