From d666197db1554a96e1279c5b38a44fb789b00d9a Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Sun, 22 Sep 2024 12:34:41 +0300 Subject: [PATCH] chore: update unsafe conversions --- driver/pgdriver/unsafe.go | 16 +++++++++------- extra/bunotel/unsafe.go | 16 +++++++++------- internal/unsafe.go | 16 +++++++++------- 3 files changed, 27 insertions(+), 21 deletions(-) diff --git a/driver/pgdriver/unsafe.go b/driver/pgdriver/unsafe.go index 6ba868105..80d6aff53 100644 --- a/driver/pgdriver/unsafe.go +++ b/driver/pgdriver/unsafe.go @@ -1,3 +1,4 @@ +//go:build !appengine // +build !appengine package pgdriver @@ -5,15 +6,16 @@ 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)) } diff --git a/extra/bunotel/unsafe.go b/extra/bunotel/unsafe.go index 23accd40e..67b687cbe 100644 --- a/extra/bunotel/unsafe.go +++ b/extra/bunotel/unsafe.go @@ -1,3 +1,4 @@ +//go:build !appengine // +build !appengine package bunotel @@ -5,14 +6,15 @@ 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)) } diff --git a/internal/unsafe.go b/internal/unsafe.go index 4bc79701f..1a0331297 100644 --- a/internal/unsafe.go +++ b/internal/unsafe.go @@ -1,3 +1,4 @@ +//go:build !appengine // +build !appengine package internal @@ -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)) }