github.com/sunvim/utils@v0.1.0/fs/os_mmap_windows.go (about)

     1  //go:build windows
     2  
     3  package fs
     4  
     5  import (
     6  	"os"
     7  	"syscall"
     8  	"unsafe"
     9  )
    10  
    11  func Mmap(f *os.File, fileSize int64, mappingSize int64) ([]byte, error) {
    12  	size := fileSize
    13  	low, high := uint32(size), uint32(size>>32)
    14  	fmap, err := syscall.CreateFileMapping(syscall.Handle(f.Fd()), nil, syscall.PAGE_READONLY, high, low, nil)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  	defer syscall.CloseHandle(fmap)
    19  	ptr, err := syscall.MapViewOfFile(fmap, syscall.FILE_MAP_READ, 0, 0, uintptr(size))
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	data := (*[maxMmapSize]byte)(unsafe.Pointer(ptr))[:size]
    24  	return data, nil
    25  }
    26  
    27  func Munmap(data []byte) error {
    28  	return syscall.UnmapViewOfFile(uintptr(unsafe.Pointer(&data[0])))
    29  }
    30  
    31  func MadviceRandom(data []byte) error {
    32  	return nil
    33  }
    34  
    35  func (f *osMMapFile) Truncate(size int64) error {
    36  	// Truncating a memory-mapped file fails on Windows. Unmap it first.
    37  	if err := f.munmap(); err != nil {
    38  		return err
    39  	}
    40  	if err := f.File.Truncate(size); err != nil {
    41  		return err
    42  	}
    43  	f.size = size
    44  	return f.mremap()
    45  }