lib/mmap: convert to using unsafe.Slice to avoid deprecated reflect.SliceHeader

This commit is contained in:
cui
2025-08-22 07:35:50 +08:00
committed by GitHub
parent 9b22e38450
commit f61d79396d

View File

@@ -7,7 +7,6 @@ package mmap
import ( import (
"fmt" "fmt"
"reflect"
"unsafe" "unsafe"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
@@ -21,21 +20,10 @@ 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 pp := unsafe.Pointer(&p)
sh := (*reflect.SliceHeader)(unsafe.Pointer(&mem)) // nolint:staticcheck up := *(*unsafe.Pointer)(pp)
sh.Data = p return unsafe.Slice((*byte)(up), size), nil
sh.Len = size
sh.Cap = size
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