Skip to content

Commit

Permalink
🧹 update: replace UnsafeBytes util with suggested way (#2204)
Browse files Browse the repository at this point in the history
  • Loading branch information
efectn authored Nov 13, 2022
1 parent 8aeb147 commit e5ae764
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions utils/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,25 @@ import (
"unsafe"
)

const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112)

// #nosec G103
// UnsafeString returns a string pointer without allocation
func UnsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

// #nosec G103
// UnsafeBytes returns a byte pointer without allocation
func UnsafeBytes(s string) (bs []byte) {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
return
// UnsafeBytes returns a byte pointer without allocation.
// String length shouldn't be more than 2147418112.
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
Expand Down

0 comments on commit e5ae764

Please sign in to comment.