From 0d363365e98d5631ab00d2ed83a1f9e305ceca9d Mon Sep 17 00:00:00 2001 From: Evan Jones Date: Thu, 4 Nov 2021 17:33:26 -0400 Subject: [PATCH] unsafeBytesToString: Fix Go 1.16 SliceHeader vet warnings Go 1.16 added new vet warnings to check for unsafe uses of reflect.SliceHeader. To fix them, create an empty slice, then alter that slice using *reflect.SliceHeader/Stringheader. This is apparently safer because it works with escape analysis and garbage collection [1]. The pattern used here is also used in golang.org/x/sys, so I think this should be safe. [1] https://github.com/golang/go/issues/40701 Fixes: value.go:149:35: possible misuse of reflect.StringHeader --- value.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/value.go b/value.go index 7af7be1..4c7634c 100644 --- a/value.go +++ b/value.go @@ -145,6 +145,10 @@ func (v *Value) AsBytesSafe() ([]byte, error) { func unsafeBytesToString(b []byte) string { bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - sh := reflect.StringHeader{Data: bh.Data, Len: bh.Len} - return *(*string)(unsafe.Pointer(&sh)) + + var s string + sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) + sh.Data = bh.Data + sh.Len = bh.Len + return s }