lib/mmap: fix lint error on deprecated reflect.SliceHeader

reflect.SliceHeader is deprecated, however the replacement gives a go
vet warning so this disables the lint warning in one use of
reflect.SliceHeader and replaces it in the other.
This commit is contained in:
Nick Craig-Wood 2024-07-19 11:16:51 +01:00
parent d149d1ec3e
commit b809e71d6f

View File

@ -21,20 +21,29 @@ func Alloc(size int) ([]byte, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("mmap: failed to allocate memory for buffer: %w", err) return nil, fmt.Errorf("mmap: failed to allocate memory for buffer: %w", err)
} }
// SliceHeader is deprecated...
var mem []byte var mem []byte
sh := (*reflect.SliceHeader)(unsafe.Pointer(&mem)) sh := (*reflect.SliceHeader)(unsafe.Pointer(&mem)) // nolint:staticcheck
sh.Data = p sh.Data = p
sh.Len = size sh.Len = size
sh.Cap = size sh.Cap = size
return mem, nil return mem, nil
// ...However the correct code gives a go vet warning
// "possible misuse of unsafe.Pointer"
//
// Maybe there is a different way of writing this, but none of
// the allowed uses of unsafe.Pointer seemed to cover it other
// than using SliceHeader (use 6 of unsafe.Pointer).
//
// return unsafe.Slice((*byte)(unsafe.Pointer(p)), size), nil
} }
// Free frees buffers allocated by Alloc. Note it should be passed // Free frees buffers allocated by Alloc. Note it should be passed
// the same slice (not a derived slice) that Alloc returned. If the // the same slice (not a derived slice) that Alloc returned. If the
// free fails it will return with an error. // free fails it will return with an error.
func Free(mem []byte) error { func Free(mem []byte) error {
sh := (*reflect.SliceHeader)(unsafe.Pointer(&mem)) p := unsafe.SliceData(mem)
err := windows.VirtualFree(sh.Data, 0, windows.MEM_RELEASE) err := windows.VirtualFree(uintptr(unsafe.Pointer(p)), 0, windows.MEM_RELEASE)
if err != nil { if err != nil {
return fmt.Errorf("mmap: failed to unmap memory: %w", err) return fmt.Errorf("mmap: failed to unmap memory: %w", err)
} }