-
Notifications
You must be signed in to change notification settings - Fork 2
/
mmap.go
43 lines (35 loc) · 974 Bytes
/
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
// +build !windows
package pto3
import (
"fmt"
"os"
"syscall"
)
// MapFile maps a file into read-only memory. If available, it also
// advises the operating system that access is going to be sequential.
func MapFile(f *os.File) ([]byte, int64, error) {
// Adapted from https://github.com/golang/exp/blob/master/mmap/mmap_unix.go
fi, err := f.Stat()
if err != nil {
return nil, 0, err
}
size := fi.Size()
if size < 0 {
return nil, 0, fmt.Errorf("mmap: file %q has negative size", f.Name())
}
if size != int64(int(size)) {
return nil, 0, fmt.Errorf("mmap: file %q is too large", f.Name())
}
data, err := syscall.Mmap(int(f.Fd()), 0, int(size), syscall.PROT_READ, syscall.MAP_SHARED)
if err != nil {
return nil, 0, err
}
if err := madviseSequential(data); err != nil {
return nil, 0, err
}
return data, size, nil
}
// UnmapFile unmaps bytes that were mapped by MapFile().
func UnmapFile(bytes []byte) error {
return syscall.Munmap(bytes)
}