Skip to content

Commit

Permalink
Rewrite unsafeStringToBytes to satisfy 1.16 vet check (#466)
Browse files Browse the repository at this point in the history
Fixes #465.

According to https://golang.org/pkg/unsafe/#Pointer (6), one of the only safe ways to use pointers:
> Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer.
...
> In general, reflect.SliceHeader and reflect.StringHeader should be used only as *reflect.SliceHeader and *reflect.StringHeader pointing at actual slices or strings, never as plain structs. A program should not declare or allocate variables of these struct types.

This rewrites the unsafe to only modify to not allocate a `reflect.SliceHeader ` manually making the vet check happy.
  • Loading branch information
robbertvanginkel authored and r-hang committed Feb 18, 2021
1 parent 08a35a1 commit 915afae
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions wire/unsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,14 @@ import (
// new memory for it with the assumption that the resulting byte slice will not
// be mutated.
func unsafeStringToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
sliceHeader := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
return *(*[]byte)(unsafe.Pointer(&sliceHeader))
p := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)

var b []byte
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
hdr.Data = uintptr(p)
hdr.Cap = len(s)
hdr.Len = len(s)
return b
}

// unsafeBytesToString converts a byte slice into a string without allocating
Expand Down

0 comments on commit 915afae

Please sign in to comment.