Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🧹 update: replace UnsafeBytes util with suggested way #2204

Merged
merged 1 commit into from
Nov 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 == "" {
ReneWerner87 marked this conversation as resolved.
Show resolved Hide resolved
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