github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/mmap/mmap_windows.go (about)

     1  // +build windows
     2  
     3  package mmap
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"syscall"
     9  	"unsafe"
    10  )
    11  
    12  func mmap(fd *os.File, write bool, size int64) ([]byte, error) {
    13  	protect := syscall.PAGE_READONLY
    14  	access := syscall.FILE_MAP_READ
    15  
    16  	if write {
    17  		protect = syscall.PAGE_READWRITE
    18  		access = syscall.FILE_MAP_WRITE
    19  	}
    20  	fi, err := fd.Stat()
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	// In windows, we cannot mmap a file more than it's actual size.
    26  	// So truncate the file to the size of the mmap.
    27  	if fi.Size() < size {
    28  		if err := fd.Truncate(size); err != nil {
    29  			return nil, fmt.Errorf("truncate: %s", err)
    30  		}
    31  	}
    32  
    33  	// Open a file mapping handle.
    34  	sizelo := uint32(size >> 32)
    35  	sizehi := uint32(size) & 0xffffffff
    36  
    37  	handler, err := syscall.CreateFileMapping(syscall.Handle(fd.Fd()), nil,
    38  		uint32(protect), sizelo, sizehi, nil)
    39  	if err != nil {
    40  		return nil, os.NewSyscallError("CreateFileMapping", err)
    41  	}
    42  
    43  	// Create the memory map.
    44  	addr, err := syscall.MapViewOfFile(handler, uint32(access), 0, 0, uintptr(size))
    45  	if addr == 0 {
    46  		return nil, os.NewSyscallError("MapViewOfFile", err)
    47  	}
    48  
    49  	// Close mapping handle.
    50  	if err := syscall.CloseHandle(syscall.Handle(handler)); err != nil {
    51  		return nil, os.NewSyscallError("CloseHandle", err)
    52  	}
    53  
    54  	// Slice memory layout
    55  	// Copied this snippet from golang/sys package
    56  	var sl = struct {
    57  		addr uintptr
    58  		len  int
    59  		cap  int
    60  	}{addr, int(size), int(size)}
    61  
    62  	// Use unsafe to turn sl into a []byte.
    63  	data := *(*[]byte)(unsafe.Pointer(&sl))
    64  
    65  	return data, nil
    66  }
    67  
    68  func munmap(b []byte) error {
    69  	return syscall.UnmapViewOfFile(uintptr(unsafe.Pointer(&b[0])))
    70  }
    71  
    72  func madvise(b []byte, readahead bool) error {
    73  	// Do Nothing. We don’t care about this setting on Windows
    74  	return nil
    75  }
    76  
    77  func msync(b []byte) error {
    78  	return syscall.FlushViewOfFile(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)))
    79  }