-
Notifications
You must be signed in to change notification settings - Fork 5
/
mmap.go
48 lines (42 loc) · 1.38 KB
/
mmap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package mmap
import (
"errors"
"os"
"syscall"
)
var (
// ErrUnmappedMemory is returned when a function is called on unmapped memory.
ErrUnmappedMemory = errors.New("unmapped memory")
// ErrIndexOutOfBound is returned when given offset lies beyond the mapped region.
ErrIndexOutOfBound = errors.New("offset out of mapped region")
)
// File provides abstraction around a memory mapped file.
type File struct {
data []byte
length int64
dirty bool
}
// NewSharedFileMmap maps a file into memory starting at a given offset, for given length.
// For documentation regarding prot, see documentation for syscall package.
// possible cases:
// case 1 => if file size > memory region (offset + length)
// then all the mapped memory is accessible
// case 2 => if file size <= memory region (offset + length)
// then from offset to file size memory region is accessible
func NewSharedFileMmap(f *os.File, offset int64, length int, prot int) (*File, error) {
data, err := syscall.Mmap(int(f.Fd()), offset, length, prot, syscall.MAP_SHARED)
if err != nil {
return nil, err
}
return &File{
data: data,
length: int64(length),
}, nil
}
// Unmap unmaps the memory mapped file. An error will be returned
// if any of the functions are called on Mmap after calling Unmap.
func (m *File) Unmap() error {
err := syscall.Munmap(m.data)
m.data = nil
return err
}