Skip to content

Commit

Permalink
chore: update unsafe conversions
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Sep 22, 2024
1 parent d87deff commit d666197
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 21 deletions.
16 changes: 9 additions & 7 deletions driver/pgdriver/unsafe.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
//go:build !appengine
// +build !appengine

package pgdriver

import "unsafe"

func bytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
if len(b) == 0 {
return ""
}
return unsafe.String(&b[0], len(b))
}

//nolint:deadcode,unused
func stringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
if s == "" {
return []byte{}
}
return unsafe.Slice(unsafe.StringData(s), len(s))
}
16 changes: 9 additions & 7 deletions extra/bunotel/unsafe.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
//go:build !appengine
// +build !appengine

package bunotel

import "unsafe"

func bytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
if len(b) == 0 {
return ""
}
return unsafe.String(&b[0], len(b))
}

func stringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
if s == "" {
return []byte{}
}
return unsafe.Slice(unsafe.StringData(s), len(s))
}
16 changes: 9 additions & 7 deletions internal/unsafe.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build !appengine
// +build !appengine

package internal
Expand All @@ -6,15 +7,16 @@ import "unsafe"

// String converts byte slice to string.
func String(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
if len(b) == 0 {
return ""
}
return unsafe.String(&b[0], len(b))
}

// Bytes converts string to byte slice.
func Bytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
if s == "" {
return []byte{}
}
return unsafe.Slice(unsafe.StringData(s), len(s))
}

0 comments on commit d666197

Please sign in to comment.