2018-05-22 15:47:30 +02:00
|
|
|
// Package mmap implements a large block memory allocator using
|
|
|
|
// anonymous memory maps.
|
|
|
|
|
2021-09-09 14:25:25 +02:00
|
|
|
//go:build !plan9 && !windows && !js
|
2020-07-31 20:57:48 +02:00
|
|
|
// +build !plan9,!windows,!js
|
2018-05-22 15:47:30 +02:00
|
|
|
|
|
|
|
package mmap
|
|
|
|
|
|
|
|
import (
|
2021-11-04 11:12:57 +01:00
|
|
|
"fmt"
|
|
|
|
|
2018-05-22 15:47:30 +02:00
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Alloc allocates size bytes and returns a slice containing them. If
|
|
|
|
// the allocation fails it will return with an error. This is best
|
|
|
|
// used for allocations which are a multiple of the PageSize.
|
|
|
|
func Alloc(size int) ([]byte, error) {
|
|
|
|
mem, err := unix.Mmap(-1, 0, size, unix.PROT_READ|unix.PROT_WRITE, unix.MAP_PRIVATE|unix.MAP_ANON)
|
|
|
|
if err != nil {
|
2021-11-04 11:12:57 +01:00
|
|
|
return nil, fmt.Errorf("mmap: failed to allocate memory for buffer: %w", err)
|
2018-05-22 15:47:30 +02:00
|
|
|
}
|
|
|
|
return mem, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Free frees buffers allocated by Alloc. Note it should be passed
|
|
|
|
// the same slice (not a derived slice) that Alloc returned. If the
|
|
|
|
// free fails it will return with an error.
|
|
|
|
func Free(mem []byte) error {
|
|
|
|
err := unix.Munmap(mem)
|
|
|
|
if err != nil {
|
2021-11-04 11:12:57 +01:00
|
|
|
return fmt.Errorf("mmap: failed to unmap memory: %w", err)
|
2018-05-22 15:47:30 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|