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

     1  // Package mmap implements a large block memory allocator using
     2  // anonymous memory maps.
     3  
     4  // +build !plan9,!windows
     5  
     6  package mmap
     7  
     8  import (
     9  	"github.com/pkg/errors"
    10  	"golang.org/x/sys/unix"
    11  )
    12  
    13  // Alloc allocates size bytes and returns a slice containing them.  If
    14  // the allocation fails it will return with an error.  This is best
    15  // used for allocations which are a multiple of the PageSize.
    16  func Alloc(size int) ([]byte, error) {
    17  	mem, err := unix.Mmap(-1, 0, size, unix.PROT_READ|unix.PROT_WRITE, unix.MAP_PRIVATE|unix.MAP_ANON)
    18  	if err != nil {
    19  		return nil, errors.Wrap(err, "mmap: failed to allocate memory for buffer")
    20  	}
    21  	return mem, nil
    22  }
    23  
    24  // Free frees buffers allocated by Alloc.  Note it should be passed
    25  // the same slice (not a derived slice) that Alloc returned.  If the
    26  // free fails it will return with an error.
    27  func Free(mem []byte) error {
    28  	err := unix.Munmap(mem)
    29  	if err != nil {
    30  		return errors.Wrap(err, "mmap: failed to unmap memory")
    31  	}
    32  	return nil
    33  }