github.com/ncw/rclone@v1.48.1-0.20190724201158-a35aa1360e3e/lib/mmap/mmap_windows.go (about)

     1  // Package mmap implements a large block memory allocator using
     2  // anonymous memory maps.
     3  
     4  // +build windows
     5  
     6  package mmap
     7  
     8  import (
     9  	"reflect"
    10  	"unsafe"
    11  
    12  	"github.com/pkg/errors"
    13  	"golang.org/x/sys/windows"
    14  )
    15  
    16  // Alloc allocates size bytes and returns a slice containing them.  If
    17  // the allocation fails it will return with an error.  This is best
    18  // used for allocations which are a multiple of the PageSize.
    19  func Alloc(size int) ([]byte, error) {
    20  	p, err := windows.VirtualAlloc(0, uintptr(size), windows.MEM_COMMIT, windows.PAGE_READWRITE)
    21  	if err != nil {
    22  		return nil, errors.Wrap(err, "mmap: failed to allocate memory for buffer")
    23  	}
    24  	var mem []byte
    25  	sh := (*reflect.SliceHeader)(unsafe.Pointer(&mem))
    26  	sh.Data = p
    27  	sh.Len = size
    28  	sh.Cap = size
    29  	return mem, nil
    30  }
    31  
    32  // Free frees buffers allocated by Alloc.  Note it should be passed
    33  // the same slice (not a derived slice) that Alloc returned.  If the
    34  // free fails it will return with an error.
    35  func Free(mem []byte) error {
    36  	sh := (*reflect.SliceHeader)(unsafe.Pointer(&mem))
    37  	err := windows.VirtualFree(sh.Data, 0, windows.MEM_RELEASE)
    38  	if err != nil {
    39  		return errors.Wrap(err, "mmap: failed to unmap memory")
    40  	}
    41  	return nil
    42  }